Skip to content

How to duplicate page with AcroForm fields and correctly rename fields on the new (copied) page #250

Closed Answered by gettalong
ekzobrain asked this question in Q&A
Discussion options

You must be logged in to vote

So, the following will do the trick:

require 'hexapdf'

pdf = HexaPDF::Document.open('page.duplicate.pdf')
page = pdf.pages[0]

(1..2).each do |idx|
  HexaPDF::Importer.instance_variable_get(:@map)&.delete(pdf.hash)
  copy_page = HexaPDF::Importer.for(pdf).import(page)

  field = copy_page[:Annots].find { |annot| annot[:Subtype] == :Widget && annot[:T].start_with?('name_') }
  field[:T] = "name_#{idx}"
  pdf.acro_form[:Fields] << field

  pdf.pages << copy_page
end

pdf.write('page duplicate result 1.pdf')

Since the importer doesn't currently expose a possibility to forget a certain destination document object, we need to manually delete it. I will maybe add a HexaPDF::Importer.forget(pdf)

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@gettalong
Comment options

Answer selected by ekzobrain
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants