Last active
September 28, 2024 15:03
-
-
Save waylan/36535feae946810bcdce5dfb8c6bdcf8 to your computer and use it in GitHub Desktop.
A PDF fillable textfield which flows with text on a page using Reportlab.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from reportlab.platypus import SimpleDocTemplate, Flowable, Paragraph | |
from reportlab.lib.styles import getSampleStyleSheet | |
style = getSampleStyleSheet()['BodyText'] | |
class TextField(Flowable): | |
def __init__(self, **options): | |
Flowable.__init__(self) | |
self.options = options | |
# Use Reportlab's default size if not user provided | |
self.width = options.get('width', 120) | |
self.height = options.get('height', 36) | |
def draw(self): | |
self.canv.saveState() | |
form = self.canv.acroForm | |
form.textfieldRelative(**self.options) | |
self.canv.restoreState() | |
class ChoiceField(Flowable): | |
def __init__(self, **options): | |
Flowable.__init__(self) | |
options['relative'] = True | |
self.options = options | |
# Use Reportlab's default size if not user provided | |
self.width = options.get('width', 120) | |
self.height = options.get('height', 36) | |
def draw(self): | |
self.canv.saveState() | |
form = self.canv.acroForm | |
form.choice(**self.options) | |
self.canv.restoreState() | |
doc = SimpleDocTemplate('textfield.pdf') | |
Story = [ | |
Paragraph('First Name', style=style), | |
TextField(name='first_name', value='John', tooltip='First name', height=18), | |
Paragraph('Last Name', style=style), | |
TextField(name='last_name', value='Doe', tooltip='Last name', height=18), | |
Paragraph('Gender', style=style), | |
ChoiceField(name='gender', tooltip='Gender', value='male', options=['', 'male', 'female'], height=18) | |
] | |
doc.build(Story) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you all for the above! FYI, I found that you can control the x position of the form item in the frame by using an indenter flowable which indents otherflowables after it's used. You add the indenter to the story before your flowables you want to indent, then add a indenter at the end with a negative value to dedent.