Reputation: 485
System OS: Windows 10
First of, I have python in PATH
, so that is not the problem. Other scripts work fine from the console.
Read parameters from a .csv
file, and fill respective annotation fields in a .PDF
When the script is executed in Python's IDLE, the output pdf file is created. However, the pdf file is not created when the script is opened from the console.
I think it must have something to do with the Current Working Directory
and my relative paths. That's why I added the line:
os.chdir(os.getcwd().replace(os.sep, '/'))
However, that did not seem to help.
Full Python script:
#! /usr/bin/python
import os , pdfrw , csv
INPUT_CSV_PATH = 'Tested_parameters.csv'
INVOICE_TEMPLATE_PATH = 'Input_template.pdf'
INVOICE_OUTPUT_PATH = 'output_document.pdf'
ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_FIELD_NAME = '/TU'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
template_pdf = pdfrw.PdfReader(input_pdf_path)
annotations = template_pdf.pages[1][ANNOT_KEY]
for annotation in annotations:
if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY: # '/Subtype': '/Widget'
if annotation[ANNOT_FIELD_KEY]: # '/T'
key = annotation[ANNOT_FIELD_KEY][1:-1]
if key in data_dict.keys():
if (key[0:4] == 'check'):
annotation.update( pdfrw.PdfDict( V=data_dict[key], AS=data_dict[key]) )
else:
annotation.update( pdfrw.PdfDict(AP=data_dict[key], V=data_dict[key], F=0) )
pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def Inport_csv_to_dict(input_pdf_path):
with open(input_pdf_path,encoding="utf-8-sig") as fh:
rd = csv.DictReader(fh, delimiter=',')
for row in rd:
data_dict = row
return data_dict
if __name__ == '__main__':
os.chdir(os.getcwd().replace(os.sep, '/'))
data_dict = Inport_csv_to_dict(INPUT_CSV_PATH)
write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)
Upvotes: 1
Views: 72
Reputation: 485
Ok, this was kind of stupid from my part, but it works now.
I had the #! /usr/bin/python
on the first line of my script. So the console run the script with python 2.
I removed the first line, and it worked as it should (with Python 3)
Upvotes: 1