I am using python libraries PyPDF2
and reportlab
to add text fields into an existing PDF.
I currently use the function
def makeTextFields():
packet = io.BytesIO()
can = canvas.Canvas(packet, pagesize=landscape(letter))
can.acroForm.textfield(name='fname', tooltip='First Name',
x=500, y=20, borderStyle='inset',
borderColor=blue, fillColor=blue,
width=79, height=24,
textColor=black, forceBorder=False, annotationFlags ="")
can.showPage()
can.save()
packet.seek(0)
text_fields = PdfFileReader(packet)
return text_fields
to create a PDF with the text fields then the following to load the base pdf, merge and save
main = PdfFileReader(open("master.pdf", 'rb'))
text_fields = makeTextFields()
output = PdfFileWriter()
text_field_page = text_fields.getPage(0)
page = main.getPage(0)
page.mergePage(text_field_page)
output.addPage(text_field_page)
stream = open("dest.pdf", "wb")
output.write(stream)
stream.close()
this solution would work fine however master.pdf
has a rotation of 90
this means that when page.mergePage
is called the text field pdf is automatically roated 90 degrees to match the base pdf and leaves the text fields 90 degrees with sideways text
WHAT I'VE TRIED
I have tried replacing page.mergePage
with page.mergeRotatedTranslatedPage
to no luck, I have also tried setting annotationFlags ="norotate"
which according to reportlab docs should allow the text field to ignore canvas rotation but that did not work. lastly i tried
can.saveState()
can.rotate(90)
can.acroForm.textfield(name='fname', tooltip='First Name',
x=500, y=20, borderStyle='inset',
borderColor=blue, fillColor=blue,
width=79, height=24,
textColor=black, forceBorder=False, annotationFlags ="")
can.restoreState()
in the hopes of rotating the text field 90 degrees offset of the page so it will be 0 when the page is rotated to 90 but that seemed to have no affect
I believe the solution will lie in either finding a way to nullify the rotation on the text field, applying an initial rotation to the text field, or merging the two pdfs without matching the rotation. However, any other solutions / libraries are apreciated.
I am also open to creating the pdf in another program and just merging them using python. Or using a different language if python isnt the best language for the job
try this
text_field_page.mergeRotatedTranslatedPage(page , -90, page .mediaBox.getWidth() / 2, page .mediaBox.getWidth() / 2)