tes" /> tes" /> tes"/>

Prawn Html text and image not same line

179 Views Asked by At

I am using prawn and prawn html, when I using PrawnHtml.append_html(pdf, '<p style="display:inline;"><img height="26" width="26" src="path_image" >test</p>')

the image and text are not on the same line.

how can I make the image and text on the same line?

do you have any solution for that?

1

There are 1 best solutions below

1
Matthew On

Welcome Devi!

Prawn explicitly states that it's not ideal for HTML rendering:

One thing Prawn is not, and will never be, is an HTML to PDF generator.

Prawn HTML has a similar warning:

Notice: render HTML documents properly is not an easy task, this gem support only some HTML tags and a small set of CSS attributes. If you need more rendering accuracy take a look at other projects like WickedPDF or PDFKit.

So you probably don't want to turn HTML into a PDF using Prawn...

That aside, there are a few things wrong with your code:

  • display is not one of Prawn HTML's supported CSS attributes
  • height and width should be in the style attribute... from the readme:

    <img src="image.jpg" style="height: 200px"/>

Looking at the supported tags I think the best you can hope for is to use absolute positioning but it doesn't seem to work with image tags. The text moves but the image goes where it would have gone.

require 'prawn-html'

pdf = Prawn::Document.new(page_size: 'A4')
PrawnHtml.append_html(pdf, '<p style="position: absolute; left: 300px; top: 200px"><img style="position: absolute; left: 200px; top: 200px;  height: 26px; width: 26px;" src="path_image.jpg">test</p>')
pdf.render_file('test.pdf')

Renders:
enter image description here

Even wrapping the img in an absolutely positioned div doesn't seem to work ‍♂️

Unless you want to keep fighting against it I suggest you use one of the HTML alternatives Prawn and Prawn HTML suggest...

...or use Prawn natively. To get an image on the same line as text with Prawn you could write something like this:

require 'prawn'

pdf = Prawn::Document.new(page_size: 'A4')

image_height = 26
image_width = 26

pdf.image "path_image.jpg", width: image_width, height: image_height

y_position = pdf.cursor + image_height / 2 # origin is at bottom of page so adding to the cursor moves it up
x_position = image_width + 10
pdf.draw_text "test", at: [x_position, y_position]

pdf.render_file "prawn.pdf"

Renders:
enter image description here