jorisschellekens / borb

borb is a library for reading, creating and manipulating PDF files in python.
https://borbpdf.com/
Other
3.4k stars 147 forks source link

Is it possible to add FormFields to existing PDFs? #137

Closed stimon closed 2 years ago

stimon commented 2 years ago

Hi!

I'm trying to add simple input TextField at the end of each page of an existing PDF, using absolute position. The aim is that the entered text is updated on every page before printing.

from borb.pdf import Document
from borb.pdf import PDF
from borb.pdf.canvas.geometry.rectangle import Rectangle
from decimal import Decimal
from borb.pdf import Page
from borb.pdf import Paragraph
from borb.pdf import TextField

with open("questionnaire.pdf", "rb") as in_file_handle:
    doc = PDF.loads(in_file_handle)

info = doc.get_document_info()
N = int(info.get_number_of_pages())
r: Rectangle = Rectangle(
        Decimal(50),
        Decimal(5),
        Decimal(100),
        Decimal(5),
    )
subfield = TextField(field_name="subject_id")
for i in range(0, N):
    page = doc.get_page(i)
    subfield.paint(page, r)

with open("borbtest.pdf", "wb") as pdf_out_handle:
    PDF.dumps(pdf_out_handle, doc)

The TextField is displayed when opened in any viewer (I have tried mac Preview, Acrobat and Chrome), but it is not editable.

However, a simple example does work:

from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import PageLayout
from borb.pdf import SingleColumnLayout
from borb.pdf import Paragraph
from borb.pdf import FixedColumnWidthTable

# create Document
d: Document = Document()
# create Page
p: Page = Page()
# add Page to Document
d.add_page(p)
# set a PageLayout
l: PageLayout = SingleColumnLayout(p)
# add FixedColumnWidthTable containing Paragraph and TextField objects
l.add(
    FixedColumnWidthTable(number_of_columns=2, number_of_rows=3)
    .add(TextField(field_name="name"))
    .set_padding_on_all_cells(Decimal(2), Decimal(2), Decimal(2), Decimal(2))
    .no_borders()
)
with open("output.pdf", "wb") as pdf_file_handle:
    PDF.dumps(pdf_file_handle, d)

Am I doing anything wrong?

Thanks!

jorisschellekens commented 2 years ago

Hi there,

There is a template you can fill in for filing a bug. It contains some questions I will otherwise have to ask you anyway.

Please edit your issue to ensure it follows the template. Keep in mind I will close issues after 7 days of inactivity.

Kind regards, Joris Schellekens

stimon commented 2 years ago

Hi Joris,

Sorry, I wasn't sure if it would be a bug or just me doing something wrong. That is why I didn't use the template.
I just filed a BUG issue and closing this one.

Thanks! Santi