Set dynamic height for the entire PDF Prawn document

I am trying to create a document using Prawn gem for Rails

What I'm trying to do is set the height of the variable for my pdf, so depending on some queries in the database, the height of the PDF will change. I do this because I need a document in one PDF page.

Currently, my code looks like this:

pdf = Prawn::Document.new(page_size: [297.64, 419.53], margin: 0) .... data = [ ["Header1", "Header2", "Header3", "Header4", "Header5", "Header6"] ] // here is the variable data cart.cart_products.each do |cp| arr = [ cp.product_code, cp.product_description, cp.amount, cp.product_metric, cp.product_unit_value, cp.total_value ] data.push(arr) end // populating the table with data pdf.table(data, :cell_style => {:border_width => 0}, :column_widths => [45, 80, 30, 42.36, 50, 50]) do |table| table.row(0).border_width = 0.1.mm table.row(0).font_style = :bold table.row(0).borders = [:bottom] end .... pdf.render_file("path/to/dir/document.pdf") 

Can anyone help me with this? Thanks.

+4
source share
2 answers

Not knowing what exactly you are adjusting, I will have to make some guesses here.

So, I would set some line height for the returned data and the minimum height of the document.

 line_height = 14 min_height = 419.53 

Then I will run the queries and count the results. Then I would figure out what the variable height will be and add it to the minimum height.

 variable_height = results.length * line_height height = min_height + variable_height 

Finally:

 pdf = Prawn::Document.new(page_size: [297.64, height], margin: 0) 

Something like this should work with tricks for your specific needs.

+5
source

Thomas Leitner suggested the best option in a comment on the GitHub issue ( https://github.com/prawnpdf/prawn/issues/974#issuecomment-239751947 ):

Just what I wanted to publish πŸ˜„ - so here it is:

You can probably use a very high height for your document so that the shrimp does not automatically create a new one. And once you're done, use Prawn :: Document # y to determine your current vertical position.

Then you can use the Prawn :: Document # page (PDF :: Core :: Page object) to configure the MediaBox for the page, for example:

 require 'prawn' Prawn::Document.generate("test.pdf", page_size: [100, 2000], margin: 10) do |doc| rand(100).times do doc.text("some text") end doc.page.dictionary.data[:MediaBox] = [0, doc.y - 10, 100, 2000] end 

Credits to Thomas Leitner ( https://github.com/gettalong )

+1
source

All Articles