i try to change some input-fields in a pdf using the following code:
from fillpdf import fillpdfs
erg = fillpdfs.get_form_fields("template.pdf")
erg["þÿ\x00f\x002\x00_\x000\x001\x00[\x000\x00]"] = "TEST1"
erg["þÿ\x00f\x002\x00_\x000\x002\x00[\x000\x00]"] = "TEST2"
erg["þÿ\x00f\x002\x00_\x000\x003\x00[\x000\x00]"] = "TEST3"
fillpdfs.write_fillable_pdf("template.pdf", "new.pdf", erg, flatten=False)
The pdf looks like that:
Why is this not working? Or is there maybe another better way to solve this?
I was able to solve this using pymupdf
import pymupdf
import xlwings as xw
# read the data from an excel-sheet
fn = os.path.join(path, "inp.xlsx")
print(f"Try to open excel in {fn}")
wb = xw.Book (fn)
wsInp = wb.sheets["W-2"]
inpData = wsInp.range ("C8:O109").value
header = [x[0] for x in inpData]
inpDict = {}
for i in range(1, 12):
inpDict[i] = [x[i+1] for x in inpData]
# create the pdf outputs and replace the input-fields
for k,v in inpDict.items():
if not v[1]:
continue
if v[0] == "X":
continue
sheetNr = v[1]
sheetName = v[5].replace(" ", "_").replace(".", "_")
print(f"Working for sheet {sheetNr}")
doc = pymupdf.open("templ.pdf")
for page in doc:
for field in page.widgets():
if field.field_name == CopyB[0].BoxA_ReadOrder[0].f2_01[0]":
field.field_value = v[3]
field.update()
elif field.field_name == "CopyB[0].Col_Left[0].f2_02[0]":
field.field_value = v[4]
field.update()
elif field.field_name == "CopyB[0].Col_Left[0].f2_03[0]":
if v[6]:
worker = f"{v[5]}\n{v[6]}\n{v[7]}, {v[8]}\n{v[9]} {v[10]}"
else:
worker = f"{v[5]}\n{v[7]}, {v[8]}\n{v[9]} {v[10]}"
field.field_value = worker
field.update()
# create the pdf as read-only / only as image
out = pymupdf.open()
for page in doc:
w, h = page.rect.brcoords
outpage = out.new_page(width=w, height=h)
pix = page.get_pixmap(dpi=400)
outpage.insert_image(page.rect, pixmap=pix)
out.save(f"{sheetName}_{sheetNr}.pdf", garbage=3, deflate=True)