Home > Back-end >  HexaPDF add font when importing other document's page
HexaPDF add font when importing other document's page

Time:12-01

I have app that adding texts for original pdf and generate new pdf. All is good until I have page that contain different font, then target pdf have no glyphs(boxes instead of characters), when source_doc saved, it displays font properly.

Perhaps something to do with how .import method work but i did not found way :/

Here is part of code:

target_doc = HexaPDF::Document.new
source_doc = HexaPDF::Document.open("source.pdf")
page = source_doc.pages[0]
canvas = page.canvas(type: :overlay)
# ... some code filling the doc with the text

font_file = "new_font.ttf"
source_doc.fonts.add(font_file)
canvas.font font_file
canvas.text(text, at: [x, y])
# back to default font
canvas.font(FONT_FAMILY, size: FONT_SIZE)

source_doc.pages.each { |page| target_doc.pages << target_doc.import(page) }

target_doc.write(output_file)

I have tried to .add font to target_doc but it did not added(tried before and after import) In the target_doc.fonts I can see font loaded in loaded_fonts_cache and in glyphs.

Anyone has any clue how can I import pages including font used in it ?

Document used: https://hexapdf.gettalong.org/examples/merging.html

CodePudding user response:

In order to import page with missing information(like new fonts), need to call this method before importing pages to a new pdf, after source_doc.fonts.add(font_file) because this info available only after all glyps are known to the source document.

source_doc.dispatch_message(:complete_objects)

Thanks to Thomas, author of HexaPDF <3 https://github.com/gettalong/hexapdf/issues/214

  • Related