gettalong / hexapdf

Versatile PDF creation and manipulation for Ruby
https://hexapdf.gettalong.org
Other
1.21k stars 69 forks source link

Automatically wrap long text to a new page? #230

Closed dlfischer-cmm closed 1 year ago

dlfischer-cmm commented 1 year ago

Greetings! I'm using HexaPDF::Document.open(filename) to open an existing PDF and draw some text on it at predetermined x, y positions. Sometimes this text, which comes from user input, is too long to fit into the predetermined space. In that case, I create a new page to hold the additional information. To accomplish this, I'm currently doing this:

      page = @document.new_page
      canvas = @document.new_canvas(page, :page)
      frame = @document.new_frame

      text_from_user.each do |text|
        box = @document.pdf.layout.formatted_text_box([text], style: style)
        result = frame.fit(box)
        frame.draw(canvas, result) if result.success?
      end

Which draws something like this on the page:

Here is text value 1, it's just fine.
Here is text value 2, also normal.
Text value 3 has waaaay too many characters to fit on this page and could even span multiple pages. 
Text value 4 is normal.
Look at this beautiful, short text value.

This all works great until it gets to Text value 3 which has too many characters to fit on a single page in which case result.success? returns false.

What's the best way to fit as much text as possible on the current page and then automatically wrap the remaining text to additional pages as needed? I tried various Box and Frame methods (can't remember what all the were now - split, find_next_region, etc.?) but couldn't get it to work properly.

Any suggestions or guidance you can offer are greatly appreciated. Thank you for your help!

gettalong commented 1 year ago

Have a look at what the HexaPDF::Composer does in such a case. I think the referenced code should be easily adaptable to your situation.

dlfischer-cmm commented 1 year ago

That's exactly what I needed. Thank you!