gettalong / hexapdf

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

can I use composer text inside page_style block? #272

Closed adas172002 closed 8 months ago

adas172002 commented 10 months ago

Hi,

I am trying to create a pdf page template with composer page_style method. From the examples I understand it receives 2 objects: canvas and style. Using canvas instance methods inside page_style block to create primates like rectangles is working, however I don't know how to (if possible?) create a text box with composer text call, code that calls composer.text inside page_style block generates an error undefined method 'fit' for nil:NilClass. Is this possible?

LBNL many thanks for your ongoing work on HexaPDF, list of features is growing with each release.

gettalong commented 10 months ago

What you want to do isn't built-in currently, i.e. use composer-like methods for a single page (i.e. canvas).

You can work-around this by doing something like this:

require 'hexapdf'

HexaPDF::Composer.create('cer.pdf', skip_page_creation: true) do |c|
  layout = c.document.layout
  c.page_style(:default, page_size: :A4) do |canvas, style|
    style.frame = style.create_frame(canvas.context, 36)

    frame2 = style.create_frame(canvas.context, 36)
    box_fitter = HexaPDF::Layout::BoxFitter.new([frame2])
    box_fitter.fit(layout.text("Test"))
    box_fitter.fit(layout.lorem_ipsum)
    if box_fitter.fit_successful?
      box_fitter.fit_results.each {|result| result.draw(canvas)}
    else
      # do something here
    end
  end
  c.new_page
end

I.e. you need to create the frame and box fitter yourself and do everything manually.

Btw. enabling this functionality is already on my todo list, will keep the issue open as reminder to implement this sooner than later :)

gettalong commented 8 months ago

A new HexaPDF::Content::CanvasComposer will be in the next release which can be created using canvas.composer and allows using a HexaPDF::Composer like interface for a single canvas object.