Earlier Prawn
gem allowed to create a table by its html representation (having an html table string as an input argument like <table class="abc"> .... </table>
). Now I didn't find this facility in the manual.
So is it possible now? If not, is there any other option then?
TL;DR: if your use-case is 1) generating both HTML and PDF data (like online invoices etc.), and 2) making sure both look the same, then Prawn is not really the best solution (which is the same suggestion in the Prawn Readme).
In your case, you could parse the HTML using Nokogiri or Upton and extract the data from the HTML table and then use it to generate the PDF representation via Prawn. The HTML styles may not directly translate into the ones used by Prawn and so, even with a lot of code-wrangling, you might not achieve the consistency in styling — which I assume, from the comments on the answer by royalGhost
, is the result you want. Also, a simple Nokogiri parsing solution won't work if your HTML table is nested and the parsing code does not cater to that. For example, consider this:
<table>
<tr>
<td>First Column, First Row</td>
<td>Second Column, First Row</td>
</tr>
<tr>
<table>
<tr>
<td>First Column, Second Row</td>
<td>Second Column, Second Row</td>
<td>Third Column, Second Row</td>
</tr>
</table>
</tr>
</table>
Then, in the Ruby parsing snippet, you should ensure that the inner <table>...</table>
is parsed into a Prawn::Table
object and not a row of Prawn::Table::Cell
objects.
Any wkhtmltopdf
based options such as WickedPDF or PDFKit offer much cleaner way of achieving the HTML to PDF conversion solution.
You have two options:
- Ditch Prawn entirely and prefer the solution above.
- Use Prawn by extracting the data from the HTML via Nokogiri/Upton and generate the PDF and not worry about styling being the same as that in the HTML representation.
Well you can use prawnto gem for templates to create table using prawn.
For e.g if you define the following templates, it will draw table with 3 columns with x, y and z width.
data = [ ["Column 1", "Column 2", "Column 3"] ]
table(data, :column_widths => [x,y,z], :cell_style => { :inline_format => true })