Esempio n. 1
0
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)
Esempio n. 2
0
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)
Esempio n. 3
0
def fillPDFsession(userInfoDict, name):
    exportname = 'website/static/pdf/' + name
    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
    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)
Esempio n. 5
0
def write_fields_in_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    template_pdf.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    acros = template_pdf.Root.AcroForm

    for field in acros["/Fields"]:
        if field[FIELD_TYPE_KEY] == TEXT_KEY and field[ANNOT_FIELD_KEY]:
            key = field[ANNOT_FIELD_KEY][1:-1]
            if key in data_dict.keys():
                field.update(
                    pdfrw.PdfDict(**{
                        "V": data_dict[key],
                        "AS": data_dict[key]
                    }))
        elif (field[FIELD_TYPE_KEY] == BUTTON_KEY and field[ANNOT_FIELD_KEY]
              and field[KIDS_KEY]):
            key = field[ANNOT_FIELD_KEY][1:-1]
            try:
                int(data_dict[key][-1])
            except Exception:
                continue
            if key in data_dict.keys():
                choice_nr = int(data_dict[key][-1])
                field[KIDS_KEY][choice_nr - 1].update(
                    pdfrw.PdfDict(AS=data_dict[key]))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Esempio n. 6
0
def fill_pdf_from_keys(file, out_file, d):
    # file is the pdf file
    # d is the dictionary mapping the annotation fields to values
    template_pdf = pdfrw.PdfReader(file)

    for annotations in template_pdf.pages:
        for annotation in annotations[ANNOT_KEY]:
            if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                if annotation[ANNOT_FIELD_KEY]:
                    key = annotation[ANNOT_FIELD_KEY][1:-1]
                    if key in d.keys():
                        if annotation[
                                ANNOT_FIELD_TYPE_KEY] == ANNOT_FIELD_TYPE_BTN:
                            if d[key]:
                                annotation.update(
                                    pdfrw.PdfDict(AS=next(
                                        iter(annotation['/AP']['/N']))))
                            else:
                                annotation.update(pdfrw.PdfDict(AS='Off'))
                        elif annotation[
                                ANNOT_FIELD_TYPE_KEY] == ANNOT_FIELD_TYPE_TXT:
                            r = d[key]
                            if isinstance(r, float) and r == round(r):
                                r = int(r)
                            elif isinstance(r, float) and r != round(r, 2):
                                r = f'{r:.2f}'
                            annotation.update(pdfrw.PdfDict(V=f'{r}'))
    try:
        pdfrw.PdfWriter().write(out_file, template_pdf)
        logger.info("Exporting PDF file %s succeeded", out_file)
    except OSError as e:
        logger.error("File must be open %s -- %s", out_file, e)
Esempio n. 7
0
    def _assign_uuid(self, output_stream: bytes, editable: bool) -> bytes:
        """Append UUIDs to all elements of the PDF form."""

        _uuid = self._uuid

        generated_pdf = pdfrw.PdfReader(fdata=output_stream)

        for element in self._iterate_elements(generated_pdf):
            if editable:
                update_obj = pdfrw.PdfDict(T="{}_{}".format(
                    element[self._ANNOT_FIELD_KEY][1:-1],
                    _uuid,
                ), )
            else:
                update_obj = pdfrw.PdfDict(
                    T="{}_{}".format(
                        element[self._ANNOT_FIELD_KEY][1:-1],
                        _uuid,
                    ),
                    Ff=pdfrw.PdfObject(1),
                )

            element.update(update_obj)

        result_stream = BytesIO()
        pdfrw.PdfWriter().write(result_stream, generated_pdf)
        result_stream.seek(0)

        result = result_stream.read()
        result_stream.close()

        return result
Esempio n. 8
0
def fill_pdf_detached():
    global data_dict, FORM_KEYS_DETACHED, url_to_scrape
    pdf_template = pdfrw.PdfReader(
        'pdf/services/Contract_Template_Detached_V2.pdf')
    for page_pdf in pdf_template.pages:
        annotations = page_pdf['/Annots']
        if annotations is None:
            continue
        for annotation in annotations:
            if annotation['/Subtype'] == '/Widget':
                if annotation['/T']:
                    key = annotation['/T'][1:-1]
                    if re.search(r'.-[0-9]+', key):
                        key = key[:-2]
                    if key in data_dict:
                        if FORM_KEYS_DETACHED[key] == CHECKBOX_PDF_TYPE:
                            annotation.update(
                                pdfrw.PdfDict(AS=encode_pdf_string(
                                    data_dict[key], CHECKBOX_PDF_TYPE)))
                        else:
                            annotation.update(
                                pdfrw.PdfDict(V=encode_pdf_string(
                                    data_dict[key], STRING_PDF_TYPE)))
                    annotation.update(pdfrw.PdfDict(Ff=1))
    pdf_template.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdf_name = 'files/' + data_dict['property_details'] + '__' + data_dict['buyer_name'] \
               + '__' + date.today().strftime("%m-%d-%y") + '.pdf'
    pdfrw.PdfWriter().write(pdf_name, pdf_template)
    return pdf_name
Esempio n. 9
0
def write_fillable_pdf(input_pdf_path, output_pdf_path, out_path, data_dict):
    ANNOT_KEY = '/Annots'
    ANNOT_FIELD_KEY = '/T'
    ANNOT_VAL_KEY = '/V'
    ANNOT_RECT_KEY = '/Rect'
    SUBTYPE_KEY = '/Subtype'
    WIDGET_SUBTYPE_KEY = '/Widget'
    try:
        template_pdf = pdfrw.PdfReader(input_pdf_path)
    except:
        try:
            template_path = out_path + 'template.pdf'
            req = requests.get(input_pdf_path, timeout=4)
            with open(template_path, 'wb') as f:
                f.write(req.content)
            template_pdf = pdfrw.PdfReader(template_path)
        except:
            femaSetProxies()
            template_path = out_path + 'template.pdf'
            template_pdf = pdfrw.PdfReader(template_path)
    try:
        template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    except:
        pass
    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]))
                    )
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def _make_pdf_pdfrw(fields: dict,
                    src_pdf: str,
                    basename: str,
                    flatten: bool = False):
    """Backup make_pdf function in case pdftk is not available."""
    template = pdfrw.PdfReader(src_pdf)
    # Different types of PDF fields
    BUTTON = "/Btn"
    # Names for entries in PDF annotation list
    # DEFAULT_VALUE = "/DV"
    # APPEARANCE = "/MK"
    FIELD = "/T"
    # PROPS = "/P"
    TYPE = "/FT"
    # FLAGS = "/Ff"
    # SUBTYPE = "/Subtype"
    # ALL_KEYS = [
    #     "/DV",
    #     "/F",
    #     "/FT",
    #     "/Ff",
    #     "/MK",
    #     "/P",
    #     "/Rect",
    #     "/Subtype",
    #     "/T",
    #     "/Type",
    # ]
    annots = template.pages[0]["/Annots"]
    # Update each annotation if it's in the requested dictionary
    for annot in annots:
        this_field = annot[FIELD][1:-1]
        # Check if the field has a new value passed
        if this_field in fields.keys():
            val = fields[this_field]
            # Convert integers to strings
            if isinstance(val, int):
                val = str(val)
            log.debug(f"Set field '{this_field}' "
                      f"({annot[TYPE]}) "
                      f"to `{val}` ({val.__class__}) "
                      f"in file '{basename}.pdf'")
            # Prepare a PDF dictionary based on the fields properties
            if annot[TYPE] == BUTTON:
                # Radio buttons require special appearance streams
                if val == CHECKBOX_ON:
                    val = bytes(val, "utf-8")
                    pdf_dict = pdfrw.PdfDict(V=val, AS=val)
                else:
                    continue
            else:
                # All other widget types
                pdf_dict = pdfrw.PdfDict(V=val)
            annot.update(pdf_dict)
        else:
            log.debug(
                f"Skipping unused field '{this_field}' in file '{basename}.pdf'"
            )
    # Now write the PDF to the new pdf file
    pdfrw.PdfWriter().write(f"{basename}.pdf", template)
Esempio n. 11
0
def fill_forms(prefix, data):
    global status
    global index
    global output_path
        
    progress_bar.update(visible=True)
    window['file_update'].update('生成中~~~')
    temp_ = pdfrw.PdfReader('./template.pdf')

    for filename, formdata in data.items():
        if not formdata:
            continue
        # yield filename
        filepath = filename + '.pdf'
        output_path = make_path(prefix, filepath)
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        temp_.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
        for n, d in formdata.items():
            if d is not None:
                temp_.Root.Pages.Kids[0].Annots[int(n)].update(pdfrw.PdfDict(V=d))
        pdfrw.PdfWriter().write(output_path, temp_)

        index += 1
        progress_bar.update_bar(index, max_row)

    status = 5
    index = 0
Esempio n. 12
0
    def add_data_to_pdf(self, template_path, data):
        print('\nAdding data to pdf...')
        template = pdfrw.PdfReader(template_path)

        for page in template.pages:
            annotations = page['/Annots']
            if annotations is None:
                continue

            for annotation in annotations:
                #if annotation['/Subtype'] == ['/Widget']:
                if annotation['/T']:
                    key = annotation['/T'][1:-1]
                    print('Key: "{}"'.format(key))
                    if re.search(r'.-[0-9]+', key):
                        key = key[:-2]

                    if key in data:
                        print('Found Key: {}'.format(key))
                        annotation.update(
                            pdfrw.PdfDict(
                                V=self.encode_pdf_string(data[key], 'string')))
                    annotation.update(pdfrw.PdfDict(Ff=1))

        template.Root.AcroForm.update(
            pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
        pdfrw.PdfWriter().write(self.temp_directory + "data.pdf", template)
        print('Pdf saved')

        return self.temp_directory + "data.pdf"
Esempio n. 13
0
 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
Esempio n. 14
0
def pdf_fields_modify(template_pdf):
    for page in template_pdf.pages:
        annotations = page[ANNOT_KEY]
        for annotation in annotations:
            print("annotation={}".format(annotation))
            if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                if annotation[ANNOT_FIELD_KEY]:
                    key = annotation[ANNOT_FIELD_KEY][1:-1]
                    print("key={0}".format(key, ))
                    # if key == 'Bild':
                    #         annotation.update(
                    #             pdfrw.PdfDict(MK='{}')
                    #         )
                    height = float(annotation['/Rect'][3]) - float(
                        annotation['/Rect'][1])
                    print("height of rect={}".format(height))

                    if key == 'Titel':
                        type_of_value = type(annotation['/Rect'])
                        print("type_of_value={}".format(type_of_value))
                        new_base = 440.0
                        new_top = annotation['/Rect'][3]
                        a_value = [66.3714, new_base, 529.284, new_top]
                        annotation.update(
                            # was ['66.3714', '419.512', '529.284', '475.445']
                            pdfrw.PdfDict(Rect=pdfrw.objects.pdfarray.PdfArray(
                                [66.3714, new_base, 529.284, new_top])))

                    if key == 'Underrubrik':
                        type_of_value = type(annotation['/Rect'])
                        print("type_of_value={}".format(type_of_value))
                        new_base = 370.0
                        new_top = new_base + height
                        a_value = [66.3714, new_base, 529.284, new_top]
                        annotation.update(
                            # was ['66.3714', '419.512', '529.284', '475.445']
                            pdfrw.PdfDict(Rect=pdfrw.objects.pdfarray.PdfArray(
                                [66.3714, new_base, 529.284, new_top])))

                    if key == 'Namn på författare':
                        type_of_value = type(annotation['/Rect'])
                        print("type_of_value={}".format(type_of_value))
                        new_base = 300.0
                        new_top = new_base + height
                        a_value = [66.3714, new_base, 529.284, new_top]
                        annotation.update(
                            # was ['66.3714', '419.512', '529.284', '475.445']
                            pdfrw.PdfDict(Rect=pdfrw.objects.pdfarray.PdfArray(
                                [66.3714, new_base, 529.284, new_top])))

                    if key == 'Bild':
                        type_of_value = type(annotation['/Rect'])
                        print("type_of_value={}".format(type_of_value))
                        new_base = 35.0
                        new_top = new_base + 10.0
                        a_value = [66.3714, new_base, 529.284, new_top]
                        annotation.update(
                            # was ['66.3714', '419.512', '529.284', '475.445']
                            pdfrw.PdfDict(Rect=pdfrw.objects.pdfarray.PdfArray(
                                [66.3714, new_base, 529.284, new_top])))
Esempio n. 15
0
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)
Esempio n. 16
0
def fill_pdf():
    global data_dict, FORM_KEYS, url_to_scrape
    pdf_template = pdfrw.PdfReader('services/CAR-Condo-Contract_Template.pdf')
    for page_pdf in pdf_template.pages:
        annotations = page_pdf['/Annots']
        if annotations is None:
            continue
        for annotation in annotations:
            if annotation['/Subtype'] == '/Widget':
                if annotation['/T']:
                    key = annotation['/T'][1:-1]
                    if re.search(r'.-[0-9]+', key):
                        key = key[:-2]
                    if key in data_dict:
                        if FORM_KEYS[key] == CHECKBOX_PDF_TYPE:
                            annotation.update(
                                pdfrw.PdfDict(AS=encode_pdf_string(
                                    data_dict[key], CHECKBOX_PDF_TYPE)))
                        else:
                            annotation.update(
                                pdfrw.PdfDict(V=encode_pdf_string(
                                    data_dict[key], STRING_PDF_TYPE)))
                    annotation.update(pdfrw.PdfDict(Ff=1))
    pdf_template.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdfrw.PdfWriter().write(
        'Contract_' + url_to_scrape.split(sep='/')[-1] + '.pdf', pdf_template)
Esempio n. 17
0
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 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]
    print("Annotations : " + str(annotations))
    for annotation in annotations:
        print("\n\n")
        if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
            print("Required Annotation subtype key: " +
                  str(annotation[SUBTYPE_KEY]))
            if annotation[ANNOT_FIELD_KEY]:
                print("RRRRRR required annot field key ::: " +
                      annotation[ANNOT_FIELD_KEY])
                key = annotation[ANNOT_FIELD_KEY][1:-1]
                print("KEY::: " + str(key))
                if key in data_dict.keys():
                    print("UPdate ME")
                    print(str(pdfrw.PdfDict(V='{}'.format(data_dict[key]))))
                    annotation.update(
                        pdfrw.PdfDict(V='{}'.format(data_dict[key])))
            else:
                print("%%%%%NOT required annot field key ::: " +
                      annotation[ANNOT_FIELD_KEY])
        else:
            print("****Not required annotation subtype key: " +
                  str(annotation[SUBTYPE_KEY]))
    print(str(pdfrw.PdfDict(V='{}'.format(data_dict[key]))))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Esempio n. 19
0
    def action_submitted(self):
        for record in self:
            record.state = 'request'
            now = datetime.datetime.now()
            current_dir = os.path.dirname(os.path.abspath(__file__))
            transcript_path = os.path.join(current_dir, 'transcript_form.pdf')
            transcript_path_output = os.path.join(current_dir,
                                                  'transcript_output.pdf')
            education_lv = True if record.education_level == "master" else False
            data = {
                'date': now.day,
                'month': now.month,
                'year': now.year,
                'full_name': record.full_name,
                'student_id': record.student_id,
                'education_level': education_lv,
                'school': record.study_school,
                'mobile': record.student_no.mobile,
                'email': record.student_no.email,
            }

            template_pdf = pdfrw.PdfReader(transcript_path)
            template_pdf.Root.AcroForm.update(
                pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
            annotations = template_pdf.pages[0]['/Annots']
            for annotation in annotations:
                if annotation['/Subtype'] == '/Widget':
                    if annotation['/T']:
                        key = annotation['/T'][1:-1]
                        if key in data.keys():
                            annotation.update(
                                pdfrw.PdfDict(V='{}'.format(data[key])))
            pdfrw.PdfWriter().write(transcript_path_output, template_pdf)
            self.report_transcript = base64.b64encode(
                open(transcript_path_output, "rb").read())
    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,
        )
Esempio n. 21
0
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
Esempio n. 22
0
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')
Esempio n. 23
0
def write_pdf(outfile, voucherNumber):
    template_pdf = pdfrw.PdfReader(TEMPLATE_PATH)

    # fill in the form field
    template_pdf.Root.Pages.Kids[0].Annots[0].update(
        pdfrw.PdfDict(V=voucherNumber))

    # write the file
    template_pdf.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdfrw.PdfWriter().write(outfile, template_pdf)
Esempio n. 24
0
def pdf_file_write(form_path, applicant_data):
    """
    根据传入的表格文件路径以及数据,尝试将匹配的数据写入到表格文件中并保存
    :param form_path: 表格文件
    :param applicant_data: 要填写的数据
    :return: None
    """
    if "decrypted" not in form_path:
        try:
            decrypted_file_path = pdf_decryption(form_path)
            pdf_template = PdfReader(decrypted_file_path)
        except Exception as err:
            print(err)
            return
    else:
        pdf_template = PdfReader(form_path)

    if pdf_template:
        data = {}
        if applicant_data and len(applicant_data) != 0:
            for key in applicant_data.keys():
                if applicant_data[key] and applicant_data[key] != '':  # 过滤掉数据中值为0的情况
                    data[key] = applicant_data[key]

        # 解决写入值后在 adobe中不显示,在浏览器预览中可以显示值的问题,但是在adobe中打开,大部分显示不全
        # 使用浏览器打开可以显示,存在的问题:日期、checkbox、大段文本展示效果较差
        # https://github.com/pmaupin/pdfrw/issues/84
        pdf_template.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))

        for i in range(len(pdf_template.pages)):
            this_page = pdf_template.pages[i]
            if ANNOT_KEY in this_page.keys():
                annotations = this_page[ANNOT_KEY]
                for annotation in annotations:
                    if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                        if ANNOT_FIELD_KEY in annotation.keys():
                            key = annotation[ANNOT_FIELD_KEY][1:-1]
                            if key in data.keys() and data[key] != 'None':
                                annotation.update(pdfrw.PdfDict(AP=''))  # 解决在浏览器预览中不显示的问题
                                annotation.update(
                                    pdfrw.PdfDict(V='{}'.format(data[key]))
                                )
        # flatten the pdf  https://stackoverflow.com/questions/14454387/pdfbox-how-to-flatten-a-pdf-form
        # 不起作用
        # pdf_template.Root.AcroForm.update(pdfrw.PdfDict(Ff=1))

        dst_name = get_out_pdf_file_name(form_path, applicant_data)
        pdfrw.PdfWriter().write(dst_name, pdf_template)

        # https://github.com/mikehaertl/php-pdftk/issues/62 尚未解决
        pypdftk.fill_form("1022_Zhang_Lingyun.pdf",
                          out_file='out.pdf',
                          flatten=True)
Esempio n. 25
0
def set_fields(template: pdfrw.PdfReader, data: dict):
    annotations = template.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]
                #print(key)
                if key in data.keys() and data[key] is not None:
                    print('Set {} to {}'.format(key, data[key]))
                    annotation.update(pdfrw.PdfDict(V='{}'.format(data[key])))

    template.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
Esempio n. 26
0
 def fill_form(data_dict):
     template_pdf = pdfrw.PdfReader(INPUT_PDF_PATH)
     for page in range(len(template_pdf.pages)):
         annotations = template_pdf.pages[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():
                         annotation.update(
                             pdfrw.PdfDict(V="{}".format(data_dict[key])))
                         annotation.update(pdfrw.PdfDict(Ff=1))
     return template_pdf
Esempio n. 27
0
 def fill(self, template, output):
     template_pdf = pdfrw.PdfReader(template)
     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 self.form.keys():
                     annotation.update(
                         pdfrw.PdfDict(V='{}'.format(self.form[key])))
     template_pdf.Root.AcroForm.update(
         pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
     pdfrw.PdfWriter().write(output, template_pdf)
Esempio n. 28
0
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    keys = []
    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]
                keys.append(key)
                if key in data_dict.keys():
                    annotation.update(
                        pdfrw.PdfDict(V='{}'.format(data_dict[key])))
        annotation.update(pdfrw.PdfDict(AP=''))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Esempio n. 29
0
    def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
        template_pdf = pdfrw.PdfReader(input_pdf_path)
        template_pdf.Root.AcroForm.update(
            pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))

        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])))
        pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Esempio n. 30
0
    def form_valid(self, form):
        template_pdf = pdfrw.PdfReader(os.path.abspath(os.path.join(os.path.dirname(__file__), "templates/AOC-175.pdf")))

        plaintiff_name = (
            f"{self.request.user.first_name} {self.request.user.first_name}"
            if (self.request.user.first_name and self.request.user.first_name)
            else f"{form.cleaned_data['sender_first_name']} {form.cleaned_data['sender_last_name']}"
        )

        data_dict = {
            "county": form.cleaned_data["county"],
            "plaintiff_full_name": plaintiff_name,
            "plaintiff_full_name_2": plaintiff_name,
            "plaintiff_address_1": form.cleaned_data["sender_address_1"],
            "plaintiff_address_2": form.cleaned_data["sender_address_2"],
            "plaintiff_city_state_zip": f"{form.cleaned_data['sender_city']}, {form.cleaned_data['sender_state']} {form.cleaned_data['sender_zip_code']}",
            "defendant_full_name": form.cleaned_data["unit"].landlord_name,
            "defendant_address_1": form.cleaned_data["unit"].landlord_address_1,
            "defendant_address_2": form.cleaned_data["unit"].landlord_address_2,
            "defendant_city_state_zip": f"{form.cleaned_data['unit'].landlord_city}, {form.cleaned_data['unit'].landlord_state} {form.cleaned_data['unit'].landlord_zip_code}",
            "claims_sum": "${0:.2f}".format(form.cleaned_data["claims_sum"]),
            "court_costs": "${0:.2f}".format(form.cleaned_data["court_costs"]),
            "claims": form.cleaned_data["claims"],
        }

        if form.cleaned_data["is_landlord_company"]:
            data_dict["defendant_company"] = "X"
        else:
            data_dict["defendant_individual"] = "X"

        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():
                            annotation.update(pdfrw.PdfDict(V="{}".format(data_dict[key])))

        template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject("true")))
        with tempfile.TemporaryFile() as fp:
            pdfrw.PdfWriter().write(fp, template_pdf)

            fp.seek(0)

            response = HttpResponse(fp.read(), content_type="application/pdf")
            response["Content-Disposition"] = "attachment; filename=SmallClaims.pdf"
            messages.add_message(self.request, messages.SUCCESS, _("File downloaded."))
            return response