Skip to content

Instantly share code, notes, and snippets.

@mazulo
Last active May 31, 2020 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mazulo/30b8778166897e2722d5ec4bd81f9f2e to your computer and use it in GitHub Desktop.
Save mazulo/30b8778166897e2722d5ec4bd81f9f2e to your computer and use it in GitHub Desktop.
Exemplo de código que consegue escrever informações em um PDF editável.
import os
from pathlib import Path
import pdfrw
TEMPLATE_PATH = '/path/to/invoice_template.pdf'
OUTPUT_PATH = '/path/to/invoice.pdf'
ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'
def write_pdf(input_pdf, output_pdf, data_dict):
template_pdf = pdfrw.PdfReader(os.path.join(Path.home(), input_pdf))
annotations = template_pdf.pages[0][ANNOT_KEY]
for annotation in annotations:
if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
if annotation[ANNOT_FIELD_KEY]:
key = annotation[ANNOT_FIELD_KEY][1:-1]
if key in data_dict.keys():
update = {
'V': data_dict[key],
}
annotation.update(pdfrw.PdfDict(**update))
annotation.update(pdfrw.PdfDict(Ff=1))
template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
pdfrw.PdfWriter().write(os.path.join(Path.home(), output_pdf), template_pdf)
data_dict = {
'business_email_address': 'contato@dunderlabs.com',
'business_name_1': 'Dunderlabs',
'business_name_2': 'Dunderlabs',
'business_phone_number': '(34) 2222-2222',
'customer_email': 'mazulo@dunderlabs.com',
'customer_name': 'Patrick Mazulo',
'due_date': '30/05/2020',
'invoice_number': '5786878',
'item_1_amount': 'R$8000',
'item_1_price': 'R$200/hr',
'item_1_quantity': '40 hours',
'item_1': 'Criação de blog',
'note_contents': 'Muito obrigado por realizar essa compra!',
'send_date': '29/05/2020',
'subtotal': 'R$8000',
'total': 'R$8000',
}
if __name__ == '__main__':
write_pdf(TEMPLATE_PATH, OUTPUT_PATH, data_dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment