Issue: PyMuPDF (fitz) fills right-aligned comb text fields as left-aligned, ignoring PDF alignment attributes.
Expected: LastName “Doe” right-aligned in comb field.
Actual: “Doe” left-filled, alignment ignored.
I also notice both Off Gender radio buttons are filled.
Can anyone suggest a workaround other than left padding with spaces?
Sample Files:
- test_filled.pdf (shows LEFT alignment bug)
- sample_template_with_comb_text_field_right_aligned.pdf
- test.fdf (sample data: LastName=Doe)
- PyMuPdf_Fdf_Loader.py (working FDF parser/filler)
test_filled.pdf (27.3 KB)
test.fdf
%FDF-1.4
1 0 obj
<< /FDF << /F (test.pdf) /UF (test.pdf) /Fields [
<< /T (Awesomeness) /V (Off) >>
<< /T (FirstName) /V () >>
<< /T (Gender) /V (Off) >>
<< /T (LastName) /V (Doe) >>
<< /T (MiddleName) /V () >>
] /ID [<ECB52F8A018ABD74B7CBCDFED9C3FB73> <3EF278CFEF2D81C0A157F92C3E37D336>] >> /Type /Catalog >>
endobj
trailer
<< /Root 1 0 R >>
%%EOF
PyMuPdf_Fdf_Loader.py
import fitz # PyMuPDF
import re
# Step 1: Parse FDF to dict
def fdf_to_dict(fdf_path):
with open(fdf_path, 'r') as f:
fdf = f.read()
pattern = r'<<\s*/T\s*\(\s*([^)]+)\s*\)\s*/V\s*\(\s*(.*?)\s*\)\s*>>'
fields = {}
for match in re.finditer(pattern, fdf, re.DOTALL):
name = match.group(1).strip()
value = match.group(2).strip()
fields[name] = value
print("FDF fields:", fields)
return fields
# Step 2: Load PDF, fill forms
doc = fitz.open("test.pdf")
form_data = fdf_to_dict("test.fdf")
# Debug: PDF fields match FDF perfectly
pdf_fields = [w.field_name for page in doc for w in page.widgets()]
print("PDF fields:", set(pdf_fields))
filled = 0
for page in doc:
for field in page.widgets():
name = field.field_name
if name in form_data:
field.field_value = form_data[name] # Correct: direct assignment
field.update() # Commit to PDF
print(f"Filled {name}: {form_data[name]}")
filled += 1
print(f"Filled {filled} fields")
doc.save("test_filled.pdf", garbage=4, deflate=True)
doc.close()
print("Saved test_filled.pdf")
Windows commands:
echo Y | copy "sample_template_with_comb_text_field_right_aligned.pdf" test.pdf
python PyMuPdf_Fdf_Loader.py
PyMuPDF Code (line 30 fills correctly but alignment broken):
field.field_value = form_data[name] # Works, but ignores right-alignment
field.update()
PDF Field Properties (template has):
- Comb: Yes (n chars)
- Alignment: Right (explicit)
- PyMuPDF respects comb separation but drops alignment.
Version: PyMuPDF 1.24.10, Python 3.11, Windows 11