I have an image here at this link: http://i711.photobucket.com/albums/ww116/xuanchienuit/1.png
I am trying to insert this image as background to the pdf using the following method:
image_path = "..." #path to the image
pdf = Prawn::Document.new
pdf.image image_path, width: pdf.bounds.width, height: pdf.bounds.height
pdf.render_file "test.png"
And the output PDF is at this link: https://drive.google.com/file/d/0B5iZPOjOn1osUzJSUTdDZGROZzQ/view?usp=sharing
The problem is in the PDF, you can see a gray border on top and bottom of the image (if you don't see the border, try zooming in/out and you would see the border).
What is going on here? I think there could be something wrong with the image but I am not sure. I hope you guys will have a better thought.
Thanks in advance!
Rather than setting height and width, try setting the position, and letting the image scale to best fit the available space (match height, match width, match both)? You might -- all conjecture here -- be seeing some artifact of the image getting stretched to the pdf region (if the image dimensions don't match the pdf precisely).
pdf.image image_path,
:position => :center,
:vposition => :center,
:fit => [pdf.bounds.width, pdf.bounds.height]
Related
I imagine this is a shot in the dark, but is it possible to have a vector file of a shape (in this case a hexagon with rounded corners), and pass an image through some code and have it coming out cropped in the shape of that vector?
I'm attempting to utilize hexagons in my design and have gone through every page I possibly can. I've seen the many HTML and CSS solutions, but none of them achieve what I'm looking for flawlessly.
Another idea I have is maybe overlaying a transparent hexagon shape with white corners on top of the existing image with imagemagick, and then going through and making any white transparent. Thoughts?
I don't have any code for cropping in the shape of a vector file, but here's what I have for overlaying an outline of the shape I want on top of the other picture:
imgfile = "public/" + SecureRandom.uuid + ".png"
SmartCropper.from_file(art.url(:original)).smart_square.resize(225,225).write(imgfile)
overlay = Magick::Image.read("app/assets/images/overlay.png")
img = Magick::Image.read(imgfile)
img.composite(overlay,0,0, Magick::OverCompositeOp)
Right now it's giving me an undefined method error for composite, which is strange because I've followed some other stack overflow questions using the same thing in their models.
Any help is appreciated!
You have fallen for a common ImageMagick trap - the objects you get from the .read method are not Magick::Image objects but Magick::ImageList ones, and for most image types you want the first item from the list.
Without knowing how you have set up your overlay.png file, it is difficult to tell what the best composite option is. However, in a similar situation I found CopyOpacityCompositeOp to be useful, and to have the overlay's transparency control the transparency in the final image.
I tested the following code and it looks like it would do what you want if overlay.png was set up that way:
require 'smartcropper'
imgfile = "test_square.png"
SmartCropper.from_file( 'test_input.png' ).
smart_square.resize( 225, 225 ).write( imgfile )
overlay = Magick::Image.read( 'overlay.png' ).first
img = Magick::Image.read( imgfile ).first
img.composite( overlay, 0, 0, Magick::CopyOpacityCompositeOp ).
write( "test_result.png" )
Instead of reading overlay from a file, you could create it using Magick::Draw like this:
overlay = Magick::Image.new( 225, 225 ) do |i|
i.background_color= "Transparent"
end
gc = Magick::Draw.new
gc.stroke('white').stroke_width(10)
gc.fill('white')
gc.polygon(97.5, 26.25, 178.5, 73.125, 178.5, 167,
97.5, 213.75, 16.5, 167, 16.5, 73.125)
gc.draw( overlay )
NB That's a hexagon, but I've not bothered centering it.
Can you tell me how to insert image which will be a link to for example page 20? I know how to make with normal text:
text "<link anchor='page20'>Go to page 20</link>", :inline_format=>true
and then on page 20 I have
add_dest('page20', dest_fit(page.dictionary))
but how to do this with image ?
Partly thanks to lightswitch05 for some prodding in the right direction, I've found a way to get the effect I want through this inelegant way:
Insert an image in a bounding_box (the page cursor is at this point at the bottom of the image)
Move the cursor back up to the top of the image
Insert a text link over the image (in my case I just used however many vertical bars '|' were needed to cover the image)
Confirm visually that the clickable link area is about the same as the boundaries of the image
Make the text link transparent, and voilĂ , it looks like you're clicking the image.
Here's some example code (measurements not exact; there was a lot of tweaking involved):
bounding_box([0, cursor], width: 35) do
image open("http://mysite.com/remote_image.jpg"),
fit: [35, 35],
align: :center
move_up 35
transparent(0) do
formatted_text([{
text: "|||", # placeholder
size: 40,
link: "http://example.com/"
}], align: :center)
end
# stroke_bounds
end
Needless to say, this experience has got me looking a bit more at Wicked PDF in order to do what I think I want to do with PDFs.
I'm sure a better/more elegant solution exists, so I'm not planning on considering this my final answer.
Prawn does not support this functionality. In fact, even if you placed a formatted_text_box over an image and fill it with white space, it still will not work. An anchor has to include text to work. If you don't mind having text over your image, then that might be a solution.
Prawn's own readme states:
One thing Prawn is not, and will never be, is an HTML to PDF generator.
After dealing with many of Prawn's shortcomings, I've switched to using wicked_pdf for my Ruby on Rails PDF generation and have been very happy with it. If you can do it in html & css, it can be done with wicked_pdf.
I'm creating a pdf book where I need to put a background image for each page.
The size of the page is (576 x 576) and the size of the background image is 2700 x 2700 (300 dpi.) (These sizes are the requirements so cannot be adjusted).
My problem is - the background image appears out of proportion in the page. How can I fix this ?
Here's my code:
Prawn::Document.generate("#{Rails.root.to_s}/public/#{filename}.pdf", :page_size => [576,576], :left_margin => 50,
:right_margin => 50, :page_layout => :portrait, :skip_page_creation => true, :skip_encoding => true,
:background => "#{Rails.root.to_s}/public/images/pdf/bg_blank_low.jpg" ) do |pdf|
....
....
....
)
Is there any other way by which I can place the image of 300 dpi as a background image.
I even tried adding pdf template as a background, but still no luck.
Any suggestion or hint will be much appreciated.
Thanks.
What you're trying to do can't be done using the :background option of Prawn::Document.generate since the :background option can't scale the image. If you want to use the :background option, you need to make sure your image is the same dpi as the PDF (normally 72dpi).
You can however simply imbed the image in the page, like you would a normal image and then float the text over the top of it. This works since when you embed an image you're able to scale it. The code might look something like this:
Prawn::Document.generate("#{Rails.root.to_s}/public/#{filename}.pdf", :page_size => [576,576], :left_margin => 50, :right_margin => 50, :page_layout => :portrait, :skip_page_creation => true, :skip_encoding => true) do |pdf|
bg_image = "#{Rails.root.to_s}/public/images/pdf/bg_blank_low.jpg"
pdf.image bg_image, :scale => 0.2311
pdf.move_up 576
end
This will make your 'background' fully cover the page (since we manually calculated the scale 2700/576), if you want to respect your margins (this is probably a better way in general), you might alter to something like:
pdf.image bg_image, :width => pdf.bounds.width
This should automatically scale the image based on the width of the bounding box of the page. Of course you would need to change your move_up as well, something like:
pdf.move_up pdf.bounds.height
After you did this you can start putting your text in and it should appear over the top of your image and so we get our simulated scaled background.
Update
This is an update with regards to the comment. If you have pages being automatically created and you want them to have the same background then you're out of luck if you're using the current prawn release the way it is. If you really need this functionality, then you have to patch prawn.
Grab the prawn source (from https://github.com/sandal/prawn) and have a look at it. What you're after is lib/document.rb, on line 244 there is a method start_new_page, this is the one you're after. Within this method on line 280, you can see where the background is being set. Unfortunately it is using canvas which means, your image already has to be of the right size. This is why the background image doesn't scale automatically.
You will need to override this behaviour. Since this is Ruby, all you have to do is reopen the class within your project and then copy paste this method in (if you need more info on how to do this, there is plenty around on monkey-patching Ruby classes). Now you edit this method to your hearts content. The easiest way is probably to remove the canvas all together and then use our image trick from above. So the line ends up as:
image(#background, :width => bounds.width) if #background
move_up bounds.height
You can now go back to using the standard way of setting the background and everything should work.
Infact, you may even be able to get away with changing line 280 to this:
canvas { image(#background, :width => bounds.width) } if #background
And everything should work fine, saving you having to type an extra line :). Using image with the :width option should automatically scale the image, while using the :at option as prawn does won't scale the image.
Note: I haven't actually done this so you may need to work the kinks out.
If you only have one PDF page, a solution is to just don't use the background property at all, but just place the image at the first position of each page and define width as the full width with
pdf.bounds.width
If someone needs to add the picture after pages have been generated or just adding a transparent picture you can use :
pdf.transparent(0.5) do
pdf.image(file, options = {
:at => [200, 220],
:scale => 0.2
})
end
I want to clip an image if it goes beyond the dimensions of a bounding box. Just like how CSS overflow: hidden would do it. Eg.
pdf.grid([0, 0], [3, 27]).bounding_box do
pdf.image image_file
end
Now currently, this image would overflow outside the bounding box if its larger than it. Is there any way to clip the image when it goes beyond the bounding box. ? I know this is possible for text when using text_box.
you can set the size of the image or get the image to scale so it fits within a certain area while maintaining proportions, do not believe you can crop an image.
If your page is not dynamic, that is the image area will always be the same this should be OK.
pdf.image "image_file_path_&_name", :position => :center, :fit => [100,450];
This is based on v0.8.4.
Unfortunately, there seems to exist no proper way to crop an image to a bounding box at the moment. Faced with this problem I figured out this beauty:
class SamplePdf
include Prawn::View
def initialize
crop_width = 100 # your width here
crop_height = 50 # your height here
image_path = '/path/to/your_image.jpg'
bounding_box [0, 0], width: crop_width, height: crop_height do
pdf_obj, _ = build_image_object(image_path)
x, y = document.send(:image_position, crop_width, crop_height, {})
document.send(:move_text_position, crop_height)
label = "I#{document.send(:next_image_id)}"
document.state.page.xobjects.merge!(label => pdf_obj)
cm_params = PDF::Core.real_params([crop_width, 0, 0, crop_height, x, y - crop_height])
document.renderer.add_content("\nq\n#{cm_params} cm\n/#{label} Do\nQ")
end
end
end
It basically adapts the Prawn::Images#image method, but skips the calculation of the image's dimensions and the scaling respectively.
It's not exactly a clean solution. Please keep me posted if you find a better one.
You should keep in mind though that this snippet leverages some implementation details which are not part of Prawn's public API and can change anytime.
At the time of writing Prawn 2.0.1 was the most recent version.
s it posible to align an image to the right and wrap text around the image like it is in html and css using the float:right property ?
If so how do you do this ?
I can align an image but dont't know how to wrap the text around it. The text is dynamic text therefore varies alot in length.
Thanks alot
Rick
One suggestion is to try nested bounding boxes. The main bounding box would have the text inside it. with at some point another bounding box for the image. Something along the lines of
bounding_box([x,y], :width => bounds.width, :height => 400) do
text "blah"
text "blah"
# image
bounding_box([bounds.right - image_width, 0], :width => image_width) do
image("path_to_file", :at => [0,0], :width => bounds)
text "more blah"
end
You may be able to simply use the image without the bounding box, but the bounding box would ensure that the text flows around it.