Create a table in Prawn by its html representation

﹥>﹥吖頭↗ 提交于 2020-01-07 09:34:51

问题


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?


回答1:


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:

  1. Ditch Prawn entirely and prefer the solution above.
  2. 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.



回答2:


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 })


来源:https://stackoverflow.com/questions/19041641/create-a-table-in-prawn-by-its-html-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!