def write_fillable_pdf(self): template_pdf = pdfrw.PdfReader(self.conf["BLANK_CHAR_SHEET"]) data_dict = self.create_character_data_dict() annotations = template_pdf.pages[0][self.conf["ANNOT_KEY"]] for annotation in annotations: if annotation["/Subtype"] == self.conf["WIDGET_SUBTYPE_KEY"]: if annotation[self.conf["ANNOT_KEY_field"]]: key = annotation[ self.conf["ANNOT_KEY_field"]][1:-1].strip() if key in data_dict.keys(): if (annotation[self.conf["ANNOT_FORM_type"]] == self.conf["ANNOT_FORM_button"]): # button field i.e. a checkbox annotation.update( pdfrw.PdfDict( V=pdfrw.PdfName(data_dict[key]), AS=pdfrw.PdfName(data_dict[key]), )) elif (annotation[self.conf["ANNOT_FORM_type"]] == self.conf["ANNOT_FORM_text"]): annotation.update( pdfrw.PdfDict(V="{}".format(data_dict[key]))) template_pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject("true"))) new_pdf_name = ( f"{data_dict['CharacterName']}_{data_dict['Race'].replace(' ', '-')}" f"_{data_dict['ClassLevel'][:-3].replace(' ', '-')}" f"_{data_dict['Background'].replace(' ', '-')}") pdfrw.PdfWriter().write( f"pdfs/{new_pdf_name}.pdf", template_pdf, )
def set_field_names(self): page = self.pdf_as_template.pages[0] annotations = page[self.ANNOT_KEY] character_pdf_map = self.character.to_pdf_map() for i, annotation in enumerate(annotations): if annotation[self.SUBTYPE_KEY] == self.WIDGET_SUBTYPE_KEY: if annotation[self.ANNOT_FIELD_KEY]: key = annotation[self.ANNOT_FIELD_KEY][1:-1].strip() if key not in character_pdf_map: print(key) continue value = character_pdf_map[key] value = value if value is not None else '' if annotation[ self.ANNOT_FORM_type] == self.ANNOT_FORM_button: # button field i.e. a checkbox annotation.update( pdfrw.PdfDict( V=pdfrw.PdfName('Yes' if value else 'Off'), AS=pdfrw.PdfName('Yes' if value else 'Off'))) elif annotation[ self.ANNOT_FORM_type] == self.ANNOT_FORM_text: # regular text field annotation.update(pdfrw.PdfDict(V='{}'.format(value))) annotation.update(pdfrw.PdfDict(AP='')) self.pdf_as_template.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) # NEW pdfrw.PdfWriter().write('output.pdf', self.pdf_as_template)
def fill_form(targetfile, outputfile, row_data, mapping): ''' Fill up form based on map data :param targetfile: Path to pdf file that needs to be filled :param outputfile: Path to output :param row_data: Row data from excel file :param mapping: Dictionary that maps excel row with form field in pdf ''' logger = logging.getLogger(__name__ + '.fill_form') template = pdfrw.PdfFileReader(targetfile) for page in range(len(template.pages)): annotations = template.pages[page]['/Annots'] for item in annotations: if item['/Subtype'] == '/Widget': if item['/T']: key = item['/T'][1:-1] if key in mapping.keys(): if 'Check Box' in key: if row_data[mapping[key]] == 'yes': item.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) elif row_data[mapping[key]] == 'no': item.update( pdfrw.PdfDict(AS=pdfrw.PdfName('No'))) else: logger.debug('Textbox= {0} Value= {1}'.format( str(key), str(row_data[mapping[key]]))) item.update( pdfrw.PdfDict(V=str(row_data[mapping[key]]))) logger.info('Writing to {}'.format(path.join(OUTPUT_FOLDER, outputfile))) pdfrw.PdfWriter().write(path.join(OUTPUT_FOLDER, outputfile), template)
def update_form(row_data, mapping, targetfile=None, template=None): ''' Fills up form and returns a pdfrw PdfileWriter object. Works with an existing object if specified. If not, creates new :param row_data: Row data from excel file :param mapping: Dictionary that maps excel row with form field in pdf :param targetfile: Path to pdf file that needs to be filled :param template: :return: ''' logger = logging.getLogger(__name__ + '.update_form') if template is None: if targetfile is not None: template = pdfrw.PdfReader(targetfile) else: raise Exception('Target file not included. Cannot create template') for page in range(len(template.pages)): annotations = template.pages[page]['/Annots'] for item in annotations: if item['/Subtype'] == '/Widget': if item['/T']: key = item['/T'][1:-1] if key in mapping.keys(): if 'Check Box' in key: if row_data[mapping[key]] == 'yes': item.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) elif row_data[mapping[key]] == 'no': item.update( pdfrw.PdfDict(AS=pdfrw.PdfName('No'))) else: logger.debug('Textbox= {0} Value= {1}'.format( str(key), str(row_data[mapping[key]]))) item.update( pdfrw.PdfDict(V=str(row_data[mapping[key]]))) return template
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict, signature_path): pdf = pdfrw.PdfReader(input_pdf_path) annotations = 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(): if data_dict[key] == '/YES': annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('On'), V=pdfrw.PdfName('On'))) else: annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key]))) sgn = pdfrw.PageMerge().add(pdfrw.PdfReader(signature_path).pages[0])[0] sgn.scale(0.3) sgn.y += 100 sgn.x += 380 pdfrw.PageMerge(pdf.pages[0]).add(sgn, prepend='underneath').render() pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) pdfrw.PdfWriter().write(output_pdf_path, pdf)
def make_output(self): # generate the output string ostr = libxmp.core._remove_trailing_whitespace( self.md.serialize_to_str().replace("\ufeff", "")) # assemble the output dictionary output_dict = pdfrw.IndirectPdfDict(Type=pdfrw.PdfName("Metadata"), Subtype=pdfrw.PdfName("XML")) output_dict.stream = ostr.encode("utf-8").decode("latin-1") return output_dict
def encode_pdf_string(value, type_pdf): if type_pdf == STRING_PDF_TYPE: if value: return pdfrw.objects.pdfstring.PdfString.encode(value) else: return pdfrw.objects.pdfstring.PdfString.encode('') elif type_pdf == CHECKBOX_PDF_TYPE: if value == 'True' or value is True: return pdfrw.PdfName('Yes') else: return pdfrw.PdfName('No') return ''
def writeFillablePDF(input_pdf_path, output_pdf_path, data_dict): # Read Input PDF template_pdf = pdfrw.PdfReader(input_pdf_path) # Set Apparences ( Make Text field visible ) template_pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) # Loop all Annotations for annotation in template_pdf.pages[0]['/Annots']: # Custome/Fields and Checkboxes if annotation['/Subtype'] == '/Widget' and ('/Parent' in annotation): key = annotation['/Parent']['/T'][1:-1] # Remove parentheses if key in data_dict.keys(): # custom fields if '/V' in annotation['/Parent']: annotation['/Parent'].update( pdfrw.PdfDict(V=f'{data_dict[key]}')) #print(annotation) # checkbox elif '/AS' in annotation: annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) #if data_dict[key] in annotation['/AP']['/N']: # annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'), V=pdfrw.PdfName('On'))) # Text fields if annotation['/Subtype'] == '/Widget' and annotation['/T']: key = annotation['/T'][1:-1] # Remove parentheses #print(key) if key in data_dict.keys(): annotation.update(pdfrw.PdfDict(V=f'{data_dict[key]}')) #print(f'={key}={data_dict[key]}=') pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def fill_pdf(input_pdf_path, data_dict): ANNOT_KEY = '/Annots' ANNOT_FIELD_KEY = '/T' SUBTYPE_KEY = '/Subtype' WIDGET_SUBTYPE_KEY = '/Widget' template_pdf = pdfrw.PdfReader(input_pdf_path) template_pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) for page in template_pdf.pages: annotations = page[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: if type(data_dict[key]) == bool: if data_dict[key] == True: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('On'))) else: annotation.update( pdfrw.PdfDict( V='{}'.format(data_dict[key]))) annotation.update(pdfrw.PdfDict(AP='')) pdf_buffer = io.BytesIO() pdfrw.PdfWriter().write(pdf_buffer, template_pdf) pdf_buffer.seek(0) return pdf_buffer
def fill_pdf(input_pdf_path, output_pdf_path, data_dict): """ reads and writes into the pdf template modified from "https://akdux.com/python/2020/10/31/python-fill-pdf-files.html" """ template_pdf = pdfrw.PdfReader(input_pdf_path) for page in template_pdf.pages: if page[ANNOT_KEY] != None: annotations = page[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] for i in data_dict: if key in data_dict[i].keys(): if type(data_dict[i][key]) == bool: if data_dict[i][key] == True: annotation.update( pdfrw.PdfDict( AS=pdfrw.PdfName("Yes"))) else: annotation.update( pdfrw.PdfDict( V="{}".format(data_dict[i][key]))) annotation.update(pdfrw.PdfDict(AP="")) pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def verify_signature(reader, filename): signature = reader["/Root"]["/Perms"][pdfrw.PdfName("DocMDP")] if (signature["/Filter"] != "/Adobe.PPKLite" or signature["/SubFilter"] != "/adbe.pkcs7.detached"): raise NotImplementedError("Unsupported signature type") signature_string = signature["/Contents"] signature_hex = signature_string.replace("<", "").replace(">", "") signature_raw = binascii.unhexlify(signature_hex) # DER-encoded PKCS-7 sig pdf_file = open(filename, "rb") pdf_data = pdf_file.read() pdf_file.close() signature_offset = pdf_data.index(signature_string) signature_end = signature_offset + len(signature_string) byte_range = [ 0, signature_offset, signature_end, len(pdf_data) - signature_end ] for i in range(4): if int(signature["/ByteRange"][i]) != byte_range[i]: raise Exception("Byte range did not match expected position") script_dir = os.path.dirname(os.path.realpath(__file__)) adobe_root = os.path.join(script_dir, "..", "xfiles", "adoberoot.pem") signature_file = message_file = None try: signature_file = open(SIGNATURE_FILE_NAME, "wb") signature_file.write(signature_raw) signature_file.close() signature_file = None try: message_file = open(MESSAGE_FILE_NAME, "wb") message_file.write(pdf_data[:signature_offset]) message_file.write(pdf_data[signature_end:]) message_file.close() message_file = None process = subprocess.Popen([ "openssl", "smime", "-verify", "-in", SIGNATURE_FILE_NAME, "-inform", "der", "-content", MESSAGE_FILE_NAME, "-CAfile", adobe_root, "-purpose", "any", "-out", "/dev/null" ], stderr=subprocess.PIPE) text = process.communicate()[1] if process.returncode != 0 or text != "Verification successful\n": raise Exception("Signature verification failed:\n%s" % text) finally: if message_file: message_file.close() if os.path.isfile(MESSAGE_FILE_NAME): os.unlink(MESSAGE_FILE_NAME) finally: if signature_file: signature_file.close() if os.path.isfile(SIGNATURE_FILE_NAME): os.unlink(SIGNATURE_FILE_NAME)
def generatePdf(fields, document): """Load the pdf template for form 1040 and write out the fields.""" template=pdfrw.PdfReader("f1040_template.pdf") for i in range(2): for annotation in template.pages[i]['/Annots']: if annotation['/Subtype'] == '/Widget': if annotation['/T']: key = str() for each in annotation['/T'][1:-1]: if each != '\x00': key = key + each if key in fields.keys(): if 'check' in fields[key]: if fields[key]['check']: annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('On'), V=pdfrw.PdfName('On'))) else: annotation.update(pdfrw.PdfDict(V='{}'.format(fields[key]['V']))) pdfrw.PdfWriter().write("./f1040.pdf", template) font = ImageFont.truetype('./dancing_script/static/DancingScript-Regular.ttf', size=20) image = Image.new(mode='RGB', size=(250, 25), color='rgb(255,255,255)') draw = ImageDraw.Draw(image) text = nonePipe(document.demographic_user_info['given-name']) + ' ' + nonePipe(document.demographic_user_info['last-name']) draw.text((5, 0), text, fill='rgb(0, 0, 0)', font=font) image.save('signature_user.png') image = Image.new(mode='RGB', size=(250, 25), color='rgb(255,255,255)') draw = ImageDraw.Draw(image) text = nonePipe(document.demographic_spouse_info['spouse-given-name']) + ' ' + nonePipe(document.demographic_spouse_info['spouse-last-name']) draw.text((5, 0), text, fill='rgb(0, 0, 0)', font=font) image.save('signature_spouse.png') image = Image.new(mode='RGB', size=(250, 25), color='rgb(255,255,255)') draw = ImageDraw.Draw(image) text = "cpai" draw.text((5, 0), text, fill='rgb(0, 0, 0)', font=font) image.save('signature_cpai.png') image = Image.new(mode='RGB', size=(100, 25), color='rgb(255,255,255)') draw = ImageDraw.Draw(image) font = ImageFont.truetype('./dancing_script/static/DancingScript-Regular.ttf', size=14) draw.text((5, 0), datetime.date.today().isoformat(), fill='rgb(0, 0, 0)', font=font) image.save('date.png') pos_user_sig = fitz.Rect(100, 375, 250, 400) pos_user_date = fitz.Rect(275, 375, 325, 400) pos_spouse_sig = fitz.Rect(100, 405, 250, 430) pos_spouse_date = fitz.Rect(275, 405, 325, 430) pos_cpai_sig = fitz.Rect(220, 448, 370, 460) pos_cpai_date = fitz.Rect(390, 440, 440, 470) pdf_file = fitz.open('./f1040.pdf') pdf_file[1].insertImage(pos_user_sig, filename="signature_user.png") pdf_file[1].insertImage(pos_spouse_sig, filename="signature_spouse.png") pdf_file[1].insertImage(pos_cpai_sig, filename="signature_cpai.png") pdf_file[1].insertImage(pos_user_date, filename="date.png") pdf_file[1].insertImage(pos_spouse_date, filename="date.png") pdf_file[1].insertImage(pos_cpai_date, filename="date.png") pdf_file.save('./f1040_signed.pdf')
def __init__(self): # load the sRGB2014 ICC color profile iccpath = pathlib.Path( __file__).absolute().parent / "icc" / "sRGB2014.icc" srgb = ImageCms.getOpenProfile(str(iccpath)) # construct the correct pdf dict. first the output profile # N=3 is required for RGB colorspaces op = pdfrw.IndirectPdfDict(N=3, Alternate=pdfrw.PdfName("DeviceRGB")) op.stream = srgb.tobytes().decode("latin-1") # then the outputintents array oi = pdfrw.IndirectPdfDict( Type=pdfrw.PdfName("OutputIntent"), S=pdfrw.PdfName("GTS_PDFA1"), OutputConditionIdentifier="sRGB", DestOutputProfile=op, Info=srgb.profile.profile_description, # I am not sure whether this is correct, but it doesn't fail RegistryName="http://color.org/srgbprofiles.xalter") self.output_intent = [oi]
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) 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(): annotation.update( pdfrw.PdfDict(AP='', V='{}'.format(data_dict[key]), AS=pdfrw.PdfName("Yes"))) pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def clean(record): # make sure checkbox is checked on PDF checked_box = pdfrw.PdfName("Yes") if "General" in record.data and "District" in record.data["General"]: record.data["General"]["District"] = checked_box if "General" in record.data and "Superior" in record.data["General"]: record.data["General"]["Superior"] = checked_box clean_dob(record) clean_disposed_on_date(record) clean_offense_date(record) clean_arrest_date(record) clean_offenses(record) return record
def fill_template_with_annotation_fields(self, data): template = pdfrw.PdfReader(self.template_file) for field_name, value in data.items(): if field_name in self.annotations_by_name: idx = self.annotations_by_name[field_name]["annot_idx"] try: annot = template.pages[0].Annots[idx] if not annot: continue if isinstance(value, bool) and value: annot.update(pdfrw.PdfDict(AS=pdfrw.PdfName("Yes"))) else: annot.update(pdfrw.PdfDict(V="{}".format(value))) annot.update(pdfrw.PdfDict(AP="")) except Exception as e: print(idx, e) return template
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) 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(): annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key]))) annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName(str(data_dict[key])))) pdfrw.PdfWriter().write(output_pdf_path, template_pdf) #def main(): #write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict) '''charName = data_dict.get("CharacterName")
def annotate_pdf(template_pdf, data_dict): for page in template_pdf.pages: annotations = page[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] print(key) if key in data_dict.keys(): print(key, data_dict[key]) if data_dict[key] == 'Yes' or data_dict[ key] == 'No' or data_dict[key] == 'Off': annotation.update( pdfrw.PdfDict( AS=pdfrw.PdfName(data_dict[key]))) else: annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key])))
def fill_pdf(data_dict): template_pdf = pdfrw.PdfReader('5E_CharacterSheet_Fillable.pdf') for page in template_pdf.pages: annotations = page[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(): if type(data_dict[key]) == bool: if data_dict[key] == True: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) else: annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key]))) annotation.update(pdfrw.PdfDict(AP='')) pdfrw.PdfWriter().write('../Versao_final.pdf', template_pdf)
def fill_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) for page in template_pdf.pages: annotations = page[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(): if type(data_dict[key]) == bool: if data_dict[key] == True: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) else: annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key]))) annotation.update(pdfrw.PdfDict(AP='')) pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def fill_pdf(template_pdf, output_pdf_path, data_dict): for page in template_pdf.pages: annotations = page[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(): if type(data_dict[key]) == bool: if data_dict[key] == True: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) else: annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key]))) annotation.update(pdfrw.PdfDict(AP='')) template_pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def main(filename): reader = pdfrw.PdfReader(filename) verify_signature(reader, filename) embedded_files = reader["/Root"]["/Names"]["/EmbeddedFiles"] if embedded_files["/Names"][0] != ATTACHMENT_NAME: raise Exception("Unexpected attachment name %s" % embedded_files["/Names"][0]) file_spec = embedded_files["/Names"][1] embedded_file = file_spec["/EF"][pdfrw.PdfName("F")] if embedded_file["/Filter"] != "/FlateDecode": raise NotImplementedError("Unsupported compression algorithm %s" % embedded_file["/Filter"]) xml = zlib.decompress(embedded_file.stream) doc = lxml.etree.fromstring(xml) trusted_identities = doc[0] for identity in trusted_identities: import_action = identity.xpath("ImportAction/text()")[0] source = identity.xpath("Identification/Source/text()")[0] if import_action not in ("1", "2", "3"): # what is the difference? raise Exception("Unrecognized ImportAction %s" % import_action) if source != "AATL": raise Exception("Unrecognized source %s" % import_action) cert_pem = base64_to_pem(identity.xpath("Certificate/text()")[0]) process = subprocess.Popen( ["openssl", "x509", "-noout", "-fingerprint"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) fingerprint = process.communicate(input=cert_pem)[0] if process.returncode != 0: raise subprocess.CalledProcessError() fingerprint = fingerprint.replace("SHA1 Fingerprint=", "") fingerprint = fingerprint.replace(":", "") fingerprint = fingerprint.strip() f = open(fingerprint + ".pem", "w") f.write(cert_pem) f.close()
def make_isrf(self, person, folder_name): persons_pdf = pdf.PdfReader("ISRF_V1 (10).pdf") Annots = persons_pdf.Root.AcroForm.Fields dates = [] date = person.get_birthdate() # print(date) date = str(date) indeces = [5, 6, 8, 9, 0, 1, 2, 3] info = " " length = len(indeces) for i in range(length): info += date[indeces[i]] if i < length: info += " " Annots[3].update(pdf.PdfDict(V=info, MaxLen=40)) # bday Annots[0].update(pdf.PdfDict(V=person.get_fullname()[0])) # fname Annots[2].update(pdf.PdfDict(V=person.get_fullname()[1])) # lname address = person.get_address() # print(address) Annots[4].update(pdf.PdfDict(V=" " + " ".join(person.get_program_startdate()), MaxLen=40)) Annots[5].update(pdf.PdfDict(V=address[0])) # add Annots[6].update(pdf.PdfDict(V=self.clean_city(address[1]))) # city Annots[7].update(pdf.PdfDict(V=' N Y', MaxLen=8)) # state info = " " + " ".join(address[2]) info = info[:10] + " " + info[10:] Annots[8].update(pdf.PdfDict(V=info, MaxLen=30)) # zipcode Annots[15].update(pdf.PdfDict(V=person.get_email())) phones = person.get_phone_numbers() # writing mobile # print(phones) if phones[0] is not None and phones[0][0] is not None: Annots[12].update(pdf.PdfDict(V=" " + " ".join(phones[0][0]), MaxLen=15)) Annots[13].update(pdf.PdfDict(V=" " + " ".join(phones[0][1]), MaxLen=15)) Annots[14].update(pdf.PdfDict(V=" " + " ".join(phones[0][2]), MaxLen=15)) if phones[2] is not None and len(phones[2]) > 0: try: Annots[16].update(pdf.PdfDict(V=" " + " ".join(phones[2][0]), MaxLen=15)) Annots[17].update(pdf.PdfDict(V=" " + " ".join(phones[2][1]), MaxLen=15)) Annots[18].update(pdf.PdfDict(V=" " + " ".join(phones[2][2]), MaxLen=15)) except TypeError: pass if person.get_em_contact() is not None: Annots[19].update(pdf.PdfDict(V=person.get_em_contact())) if person.get_gender() == "MALE": Annots[75].update(pdf.PdfDict(AS=pdf.PdfName("Yes"))) elif person.get_gender() == 'FEMALE': Annots[76].update(pdf.PdfDict(AS=pdf.PdfName("Yes"))) else: Annots[77].update(pdf.PdfDict(AS=pdf.PdfName("Yes"))) tto = [] if person.get_latinoa(): tto.append(30) else: tto.append(31) ethnicities = person.get_ethnicities() # print(ethnicities) for x in ethnicities: Annots[ANNOTATIONKEYS[x]].update(pdf.PdfDict(AS=pdf.PdfName("On"))) work_declaration = person.get_working_declaration() if work_declaration == 'FT': tto.append(23) elif work_declaration == 'PT': tto.append(24) elif work_declaration == 'NT': tto.append(25) elif work_declaration == 'UE': tto.append(27) elif work_declaration == 'UA': tto.append(28) if person.get_studied_in_us(): CONUS = True # Annots[43].update(pdf.PdfDict(V=str(person.get_highest_us_grade()))) ny_grade = person.get_highest_ny_grade() try: ny_grade = int(ny_grade) Annots[44].update(pdf.PdfDict(V=str(ny_grade))) ny_school = person.get_ny_school() if ny_school is not None: Annots[45].update(pdf.PdfDict(V=str(ny_school))) except: print('Error on student\'s NY grade: could not parse: {}' \ ' for {}'.format(str(ny_grade), person.get_fullname())) else: CONUS = False country_hse = person.get_finished_hs() country_uni = person.get_finished_uni() if country_hse or country_uni: if CONUS: tto.append(46) else: tto.append(47) if country_uni: tto.append(51) elif country_hse: tto.append(50) country_years = person.get_country_years() if country_years is not None: Annots[52].update(pdf.PdfDict(V=str(country_years))) hasDependents = person.get_dependent_status() if not hasDependents: tto.append(96) tto.append(98) else: tto.append(95) if person.single_parent(): tto.append(97) else: tto.append(98) dependents = person.get_dependents() for i in range(len(dependents)): if dependents[i] is not None: Annots[53 + i].update(pdf.PdfDict(V=str(dependents[i]))) learning_barriers = person.get_learning_barriers() tto_y = [] if learning_barriers.__contains__('HOME'): tto_y.append(78) else: tto_y.append(57) if learning_barriers.__contains__('HM'): tto_y.append(80) else: tto_y.append(59) if learning_barriers.__contains__('D'): tto_y.append(81) else: tto_y.append(60) if learning_barriers.__contains__('LI'): tto_y.append(82) else: tto_y.append(61) if learning_barriers.__contains__('MIG'): tto_y.append(83) else: tto_y.append(62) if learning_barriers.__contains__('LD'): tto_y.append(90) else: tto_y.append(63) if learning_barriers.__contains__('RA'): tto_y.append(91) else: tto_y.append(64) if learning_barriers.__contains__('ESL'): tto_y.append(89) else: tto_y.append(88) if learning_barriers.__contains__('EO'): tto_y.append(93) else: tto_y.append(66) if learning_barriers.__contains__('FC'): tto_y.append(94) else: tto_y.append(67) if learning_barriers.__contains__('CB'): tto_y.append(84) else: tto_y.append(68) if learning_barriers.__contains__('UE'): tto_y.append(85) else: tto_y.append(69) if learning_barriers.__contains__('TANF'): tto_y.append(86) else: tto_y.append(70) if learning_barriers.__contains__('SP') and person.single_parent(): # print('is a single parent' + str(person.get_fullname())) tto_y.append(87) else: tto_y.append(71) tto_y.extend([58, 65]) # Annots[72].update(pdf.PdfDict(V='Electronically Completed by CI worker: ' + 'LS')) name = person.get_fullname() old_path = os.getcwd() path = os.path.join(os.getcwd(), folder_name) os.chdir(path) # print(os.getcwd()) location = name[1] + ", " + name[0] + ' ISRF.pdf' for i in tto: Annots[i].update(pdf.PdfDict(AS=pdf.PdfName("On"))) for i in tto_y: Annots[i].update(pdf.PdfDict(AS=pdf.PdfName("On"), V='On')) try: # person.Root.AcroForm.update(pdf.PdfDict(NeedAppearances=pdf.PdfObject('true'))) persons_pdf.Root.AcroForm.update(pdf.PdfDict(NeedAppearances=pdf.PdfObject('true'))) except AttributeError: print(str(name) + " did not have the Root attribute") global NUM_WRITTEN print(str(NUM_WRITTEN) + " " + location) NUM_WRITTEN += 1 pdf.PdfWriter().write(location, persons_pdf) os.chdir(old_path)
def crearFormulario(reclamo_id=None): if reclamo_id is not None: data_dict = {'IMPORTEIMPORTE TOTAL': 0} RECLAMO = Reclamos.objects.filter(id=reclamo_id).annotate( nombrePersona=F('asociacion_id__id_persona__nombre'), apellidoPersona=F('asociacion_id__id_persona__apellido'), numPoliza=F('asociacion_id__id_poliza__nun_poliza')).values( 'nombrePersona', 'apellidoPersona', 'numPoliza', 'detalle_diagnostico')[0] RECLAMO['nombrePaciente'] = RECLAMO['nombrePersona'].strip( ) + " " + RECLAMO['apellidoPersona'].strip() data_dict.update(RECLAMO) SERVICIOS = Servicios.objects.filter(reclamo_id=reclamo_id).annotate( nombreGrupo=F('grupo_id__nombre_grupo')).values( 'id', 'nombreGrupo') cont = 1 for service in SERVICIOS: DETALLE_SERVICIO = DetallesServicios.objects.filter( servicio_id=service['id']).annotate(nombreProveedor=F( 'proveedor_id__nombre_proveedor')).values( 'id', 'servicio_id', 'detalle', 'pago', 'moneda', 'nombreProveedor') for detalle in DETALLE_SERVICIO: numdocs = [] monto = 0 DOCUMENTOS = Documentos.objects.filter( detalle_servicio_id=detalle['id']).values( 'numdoc', 'montodoc') print(DOCUMENTOS) for doc in DOCUMENTOS: numdocs.append(doc['numdoc']) monto += int(doc['montodoc']) numdocs = " - ".join(numdocs) data_dict.update({ 'detalle' + str(cont): "{} / {} / {} / {}".format(detalle['detalle'], detalle['nombreProveedor'], numdocs, detalle['pago']) }) data_dict.update( {'moneda' + str(cont): "{} ".format(detalle['moneda'])}) data_dict.update({'IMPORTERow' + str(cont): monto}) data_dict['IMPORTEIMPORTE TOTAL'] += monto cont += 1 INVOICE_TEMPLATE_PATH = settings.MEDIA_ROOT + '/form.pdf' INVOICE_OUTPUT_PATH = settings.MEDIA_ROOT + '/' + reclamo_id + '-' + data_dict[ 'numPoliza'] + '.pdf' template_pdf = pdfrw.PdfReader( INVOICE_TEMPLATE_PATH) # se llama a la ruta del pdf template_pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) for page in template_pdf.pages: annotations = page['/Annots'] for annotation in annotations: if annotation['/Subtype'] == '/Widget': if annotation['/T']: key = annotation['/T'][1:-1] if key in data_dict.keys(): if type(data_dict[key]) == bool: if data_dict[key] == True: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) else: annotation.update( pdfrw.PdfDict( V='{}'.format(data_dict[key]))) annotation.update(pdfrw.PdfDict(AP='')) pdfrw.PdfWriter().write(INVOICE_OUTPUT_PATH, template_pdf) message = { "pdf": settings.MEDIA_URL + reclamo_id + '-' + data_dict['numPoliza'] + '.pdf' } return message
def makepdf(self, zeros): root = self.prev.Root size = int(self.prev.Size, 10) while len(self.objects) < size - 1: self.objects.append(None) page0 = self.copydict(root.Pages.Kids[0]) page0ref = PdfIndirect(root.Pages.Kids[0].indirect) obj10 = pdf.PdfDict() obj10ref = self.addObject(obj10) obj11 = pdf.PdfDict() obj11ref = self.addObject(obj11) obj12 = pdf.PdfDict() obj12ref = self.addObject(obj12) obj13 = pdf.PdfDict() obj13ref = self.addObject(obj13) obj14 = pdf.PdfDict() obj14ref = self.addObject(obj14) obj10.update({ pdf.PdfName("Type"): pdf.PdfName("TransformParams"), pdf.PdfName("P"): PdfNumber(2), pdf.PdfName("V"): pdf.PdfName("1.2"), }) obj11.update({ pdf.PdfName("Type"): pdf.PdfName("SigRef"), pdf.PdfName("TransformMethod"): pdf.PdfName("DocMDP"), pdf.PdfName("DigestMethod"): pdf.PdfName("SHA1"), pdf.PdfName("TransformParams"): obj10ref, }) obj12.update({ pdf.PdfName("Type"): pdf.PdfName("Sig"), pdf.PdfName("Filter"): pdf.PdfName("Adobe.PPKLite"), pdf.PdfName("SubFilter"): pdf.PdfName("adbe.pkcs7.detached"), pdf.PdfName("Name"): pdf.PdfString.from_unicode("Example User"), pdf.PdfName("Location"): pdf.PdfString.from_unicode("Los Angeles, CA"), pdf.PdfName("Reason"): pdf.PdfString.from_unicode("Testing"), pdf.PdfName("M"): pdf.PdfString.from_unicode("D:20200317214832+01'00'"), pdf.PdfName("Reference"): pdf.PdfArray([obj11ref]), pdf.PdfName("Contents"): PdfHexBytes(zeros), pdf.PdfName("ByteRange"): pdf.PdfArray( [PdfNumberB(0), PdfNumberB(0), PdfNumberB(0), PdfNumberB(0)]), }) obj13.update({ pdf.PdfName("FT"): pdf.PdfName("Sig"), pdf.PdfName("Type"): pdf.PdfName("Annot"), pdf.PdfName("Subtype"): pdf.PdfName("Widget"), pdf.PdfName("F"): PdfNumber(132), pdf.PdfName("T"): pdf.PdfString.from_unicode("Signature1"), pdf.PdfName("V"): obj12ref, pdf.PdfName("P"): page0ref, pdf.PdfName("Rect"): pdf.PdfArray([ PdfNumberFloat(0.0), PdfNumberFloat(0.0), PdfNumberFloat(0.0), PdfNumberFloat(0.0), ]), }) obj14.update({pdf.PdfName("DocMDP"): obj12ref}) obj15 = pdf.PdfDict() obj15.update({ pdf.PdfName("Fields"): pdf.PdfArray([obj13ref]), pdf.PdfName("SigFlags"): PdfNumber(3), }) obj15ref = self.addObject(obj15) if self.annotbutton: from pdf_annotate.annotations.image import Image from pdf_annotate.annotations.text import FreeText from pdf_annotate.config.appearance import Appearance from pdf_annotate.config.location import Location from pdf_annotate.util.geometry import identity annotation = "User signature text" x1, y1, x2, y2 = (470, 0, 570, 100) annotation = FreeText( Location(x1=x1, y1=y1, x2=x2, y2=y2, page=0), Appearance( fill=[0, 0, 0], stroke_width=1, wrap_text=True, font_size=12, content=annotation, ), ) pdfa = annotation.as_pdf_object(identity(), page=None) objapn = self.extend(pdfa[pdf.PdfName("AP")][pdf.PdfName("N")]) objapnref = self.addObject(objapn) for name in ( "BS", "C", "Contents", "DA", "Rect", # "Subtype", ): key = pdf.PdfName(name) v = pdfa[key] if isinstance(v, str): v = v.replace("/", "//") v = pdf.PdfString.from_unicode(v) elif isinstance(v, list): v = pdf.PdfArray(v) obj13.update({key: v}) objap = pdf.PdfDict() objap.update({pdf.PdfName("N"): objapnref}) obj13.update({ pdf.PdfName("SM"): pdf.PdfString.from_unicode("TabletPOSinline"), pdf.PdfName("AP"): objap, }) self.objects[root.Pages.Kids[0].indirect[0] - 1] = page0 annots = pdf.PdfArray([obj13ref]) # if False and pdf.PdfName("Annots") in page0: if pdf.PdfName("Annots") in page0: page0annots = page0[pdf.PdfName("Annots")] if isinstance(page0annots, PdfIndirect): annots.insert(0, page0annots) elif isinstance(page0annots, pdf.PdfArray): annots = page0annots annots.append(obj13ref) page0.update({pdf.PdfName("Annots"): annots}) croot = self.copydict(root) croot.update({ pdf.PdfName("Perms"): obj14ref, pdf.PdfName("AcroForm"): obj15ref }) self.objects[root.indirect[0] - 1] = croot try: ID = self.prev.ID[0] except: b = hashlib.md5(self.datau).digest() ID = pdf.PdfString.from_bytes(b, bytes_encoding="hex") b = repr(random.random()).encode() b = hashlib.md5(b).digest() self.trailer = pdf.PdfDict( Size=len(self.objects), Root=PdfIndirect(root.indirect), Info=PdfIndirect(self.prev.Info.indirect), Prev=self.startprev, ID=pdf.PdfArray( [ID, pdf.PdfString.from_bytes(b, bytes_encoding="hex")]), ) if self.prev.private.pdfdict.encrypt: self.trailer.Encrypt = PdfIndirect( self.prev.private.pdfdict.encrypt.indirect)
def fillPDF(p_data, userInfoDict, name): if p_data != []: namesave = name exportname = 'website/static/pdf/undergraduate_reg_export-' + namesave + '.pdf' template_pdf = pdfrw.PdfReader( os.getenv("PATH4PDF")) # Path to PDF form (local) annotations = template_pdf.pages[0]['/Annots'] i = 0 totalCreditCount = 0 today = date.today() d1 = today.strftime("%m/%d/%Y") #Text Data for Personal AutoFill userInfoDict["'(Name)'"][1] = p_data[0] + ' ' + p_data[1] userInfoDict["'(Campus ID)'"][1] = p_data[2] userInfoDict["'(1)'"][1] = p_data[10] userInfoDict["'(2)'"][1] = p_data[11] userInfoDict["'(1_2)'"][1] = p_data[12] userInfoDict["'(2_2)'"][1] = p_data[13] if p_data[14] == 'Fall': userInfoDict["'(Text8)'"][1] = p_data[15] else: userInfoDict["'(Text9)'"][1] = p_data[15] userInfoDict["'(Month Year)'"][1] = p_data[17] + ' ' + p_data[18] userInfoDict["'(Date)'"][1] = d1 checkthisStudy = [] for i in range(4, 11): if p_data[i] is not None: num = i + 6 checkthisStudy.append(num) for annotation in annotations: pdfTag = repr(annotation['/T']) if pdfTag in x: if "Check Box" in pdfTag: #Check box for grade tempTag = "'(Check Box" + p_data[3] + ")'" if pdfTag == tempTag: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) continue newtag = pdfTag.replace("Check Box", "") if int(newtag.replace("'(", "").replace(")'", "")) in checkthisStudy: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) continue if not userInfoDict["'(Text8)'"][ 1] and pdfTag == "'(Check Box6)'": annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) continue if not userInfoDict["'(Text9)'"][ 1] and pdfTag == "'(Check Box7)'": annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName('Yes'))) continue else: if "Total Credits" in pdfTag: entry = str(totalCreditCount) annotation.update(pdfrw.PdfDict(AP=" ", V=entry)) continue elif 'CrRow' in pdfTag and len( userInfoDict[pdfTag][1]) > 0: creditValue = int(userInfoDict[repr( annotation['/T'])][1]) totalCreditCount += creditValue entry = userInfoDict[repr(annotation['/T'])][1] annotation.update(pdfrw.PdfDict(AP=" ", V=entry)) pdfrw.PdfWriter().write(exportname, template_pdf) return exportname, totalCreditCount else: namesave = name exportname = 'website/static/pdf/undergraduate_reg_export-' + namesave + '.pdf' template_pdf = pdfrw.PdfReader( os.getenv("PATH4PDF")) # Path to PDF form (local) annotations = template_pdf.pages[0]['/Annots'] i = 0 totalCreditCount = 0 for annotation in annotations: pdfTag = repr(annotation['/T']) if pdfTag in x: if "Check Box" in pdfTag: pass else: if "Total Credits" in pdfTag: entry = str(totalCreditCount) annotation.update(pdfrw.PdfDict(AP=" ", V=entry)) continue elif 'CrRow' in pdfTag and len( userInfoDict[pdfTag][1]) > 0: creditValue = int(userInfoDict[repr( annotation['/T'])][1]) totalCreditCount += creditValue entry = userInfoDict[repr(annotation['/T'])][1] annotation.update(pdfrw.PdfDict(AP=" ", V=entry)) pdfrw.PdfWriter().write(exportname, template_pdf) return exportname, totalCreditCount