HexaPDF: the cool kid on the block!
Using a JVM-based tool like pdftk to process PDFs in Ruby?
There are some Ruby gems for PDF generation, like Prawn, but previously there were no great options for filling out PDF forms. In the past you needed to fall-back to JVM-based tools like pdftk for doing this.
HexaPDF is a native Ruby gem that is greatly improving PDF creation and manipulation for Ruby developers, and simplifying the dependencies of your project.
HexaPDF offers a wider range of features, including the manipulation and merging of existing PDFs, extracting content, optimizing files, and filling out forms. Prawn, on the other hand, primarily focuses on PDF generation from scratch.
HexaPDF also supports advanced features like embedding various image formats, font subsetting, PDF forms, digital signatures, and encryption. Prawn, while capable of embedding images and fonts, lacks the advanced features like forms, signatures, and encryption.
Explore more about HexaPDF on GitHub and on their Wiki. There is a section about the differences to Prawn, as well as a migration guide.
Example
When it comes to filling-out forms, one of the key features of HexaPDF is its ability to handle various types of PDF forms, such as text fields, button fields (like checkboxes), and choice fields (like dropdowns). This versatility makes it an invaluable tool for developers working on projects that require complex PDF manipulation.
The following sample program demonstrates HexaPDF’s ease of use and functionality:
require 'hexapdf'
input_pdf = '/tmp/f1099msc.pdf'
output_pdf = '/tmp/output.pdf'
doc = HexaPDF::Document.open(input_pdf)
i = 0
if doc.acro_form
doc.acro_form.each_field do |field|
begin
case field.field_type
when :Tx # Text field
field.field_value = field.field_name
when :Btn # Button field (like checkboxes)
# Handle button-specific logic here
when :Ch # Choice field (like dropdowns)
# Handle choice-specific logic here
else
puts "Unsupported field type: #{field[:FT]}"
end
rescue
field.field_value = i.to_s
puts "Field size limitation for field: #{field.field_name}, using: #{i}"
i += 1
end
end
doc.write(output_pdf)
else
puts "No form fields found in the PDF."
end
In this example, HexaPDF is used to open a 1099-misc form, iterate through its form fields, and modify them based on their type. It then fills out the form with the field names that are used internally in the PDF.
Conclusion
HexaPDF is a powerful tool that has more functionality than Prawn, and being a native Ruby gem, you no longer have to deal with JVM-based tools when having to fill out PDF documents. It simplifies your code and your project dependencies.
Explore more about HexaPDF on GitHub and on their Wiki.
enjoy! 🎉