Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill PDF form in python?

I'm searching best way to fill pre-made pdf with forms with database data and "flatten" it. For now I use pdftk, but it does not process national characters correctly

Is there any library for python or example how to fill pdf form and render it to non-editable PDF?

like image 553
Marek Wajdzik Avatar asked Jul 19 '13 09:07

Marek Wajdzik


People also ask

How do I fill in a PDF with text?

You can manually fill or add text. Click Add Text in the toolbar. Click at the place in the document where you want to add the text, and then start typing.


2 Answers

Give the fillpdf library a try, it makes this process very simple (pip install fillpdf and poppler dependency conda install -c conda-forge poppler)

Basic usage:

from fillpdf import fillpdfs

fillpdfs.get_form_fields("blank.pdf")

# returns a dictionary of fields
# Set the returned dictionary values a save to a variable
# For radio boxes ('Off' = not filled, 'Yes' = filled)

data_dict = {
'Text2': 'Name',
'Text4': 'LastName',
'box': 'Yes',
}

fillpdfs.write_fillable_pdf('blank.pdf', 'new.pdf', data_dict)

# If you want it flattened:
fillpdfs.flatten_pdf('new.pdf', 'newflat.pdf')

More info here: https://github.com/t-houssian/fillpdf

Seems to fill very well.

See this answer here for more info: https://stackoverflow.com/a/66809578/13537359

like image 138
Tyler Houssian Avatar answered Sep 25 '22 06:09

Tyler Houssian


Straight from the PyPDF2 docs (added years after the question was asked):

from PyPDF2 import PdfFileReader, PdfFileWriter

reader = PdfFileReader("form.pdf")
writer = PdfFileWriter()

page = reader.pages[0]
fields = reader.getFields()

writer.addPage(page)

# Now you add your data to the forms!
writer.updatePageFormFieldValues(
    writer.getPage(0), {"fieldname": "some filled in text"}
)

# write "output" to PyPDF2-output.pdf
with open("filled-out.pdf", "wb") as output_stream:
    writer.write(output_stream)
like image 27
Martin Thoma Avatar answered Sep 26 '22 06:09

Martin Thoma