Exemple #1
0
def write_withholdingtax(filename, datadict):
    # Read withholdingtax form
    pdf = pdfrw.PdfReader(WITHHOLDINGTAX_FORM_NAME)

    # Display text in fill form
    pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))

    # -- write data to pdf ------
    for d in datadict:
        pdf.Root.Pages.Kids[0].Annots[PDF_DICT[d]].update(
            pdfrw.PdfDict(V='{}'.format(datadict[d]))
        )
        # print(pdf.Root.Pages.Kids[0].Annots[PDF_DICT[d]])

    # Click Checkbox : Format '/V': '/Yes'
    # ภงด 2
    pdf.Root.Pages.Kids[0].Annots[PDF_DICT["pnd2_chkbox"]].update(
        pdfrw.PdfDict(V=pdfrw.PdfObject('/Yes'))
    )
    pdf.Root.Pages.Kids[0].Annots[PDF_DICT["pnd2_chkbox"]].update(
        pdfrw.PdfDict(AS=pdfrw.PdfObject('/Yes'))
    )

    # หัก ณ ที่ จ่าย
    pdf.Root.Pages.Kids[0].Annots[PDF_DICT["withholding_chkbox"]].update(
        pdfrw.PdfDict(V=pdfrw.PdfObject('/Yes'))
    )

    pdf.Root.Pages.Kids[0].Annots[PDF_DICT["withholding_chkbox"]].update(
        pdfrw.PdfDict(AS=pdfrw.PdfObject('/Yes'))
    )

    # Save new pdf
    pdfrw.PdfWriter().write(filename, pdf)
Exemple #2
0
def test_fill_with_radiobutton(template_with_radiobutton_stream, data_dict):
    elements = TemplateMiddleware().build_elements(
        template_with_radiobutton_stream)

    data_dict["radio_1"] = 0
    data_dict["radio_2"] = 1
    data_dict["radio_3"] = 2

    radio_button_tracker = {}

    for k, v in data_dict.items():
        if k in elements:
            elements[k].value = v

            if elements[k].type == ElementType.text:
                elements[k].font = TextConstants().global_font
                elements[k].font_size = TextConstants().global_font_size
                elements[k].font_color = TextConstants().global_font_color
                elements[k].text_x_offset = TextConstants(
                ).global_text_x_offset
                elements[k].text_y_offset = TextConstants(
                ).global_text_y_offset
                elements[k].text_wrap_length = TextConstants(
                ).global_text_wrap_length
            elements[k].validate_constants()
            elements[k].validate_value()
            elements[k].validate_text_attributes()

    result_stream = Filler().fill(template_with_radiobutton_stream, elements)

    assert result_stream != template_with_radiobutton_stream

    for element in TemplateCore().iterate_elements(result_stream):
        key = TemplateCore().get_element_key(element)

        if isinstance(data_dict[key], bool) or isinstance(data_dict[key], str):
            assert element[
                TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)
        else:
            assert element[TemplateConstants().parent_key][
                TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)

        if isinstance(data_dict[key], bool):
            assert element[TemplateConstants().checkbox_field_value_key] == (
                pdfrw.PdfName.Yes if data_dict[key] else pdfrw.PdfName.Off)
        elif isinstance(data_dict[key], int):
            if key not in radio_button_tracker:
                radio_button_tracker[key] = 0
            radio_button_tracker[key] += 1

            if data_dict[key] == radio_button_tracker[key] - 1:
                assert element[TemplateConstants().
                               checkbox_field_value_key] == BasePdfName(
                                   "/" + str(data_dict[key]), False)
            else:
                assert (element[TemplateConstants().checkbox_field_value_key]
                        == pdfrw.PdfName.Off)
Exemple #3
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())
Exemple #4
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
Exemple #5
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)
Exemple #6
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)
    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)
Exemple #8
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)
Exemple #9
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
Exemple #10
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"
    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 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)
Exemple #13
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
Exemple #14
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
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)
Exemple #16
0
def test_fill_sejda(sejda_template, sejda_data):
    elements = TemplateMiddleware().build_elements(sejda_template, sejda=True)

    for k, v in elements.items():
        if k in sejda_data:
            v.value = sejda_data[k]

        if elements[k].type == ElementType.text:
            elements[k].font = TextConstants().global_font
            elements[k].font_size = TextConstants().global_font_size
            elements[k].font_color = TextConstants().global_font_color
            elements[k].text_x_offset = TextConstants().global_text_x_offset
            elements[k].text_y_offset = TextConstants().global_text_y_offset
            elements[k].text_wrap_length = TextConstants(
            ).global_text_wrap_length
        elements[k].validate_constants()
        elements[k].validate_value()
        elements[k].validate_text_attributes()

    result_stream = Filler().fill(sejda_template, elements, sejda=True)

    assert result_stream != template_stream

    for element in TemplateCore().iterate_elements(result_stream):
        assert element[TemplateConstants().parent_key][
            TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)
Exemple #17
0
def test_fill(template_stream, data_dict):
    elements = TemplateMiddleware().build_elements(template_stream)

    for k, v in data_dict.items():
        if k in elements:
            elements[k].value = v

            if elements[k].type == ElementType.text:
                elements[k].font = TextConstants().global_font
                elements[k].font_size = TextConstants().global_font_size
                elements[k].font_color = TextConstants().global_font_color
                elements[k].text_x_offset = TextConstants(
                ).global_text_x_offset
                elements[k].text_y_offset = TextConstants(
                ).global_text_y_offset
                elements[k].text_wrap_length = TextConstants(
                ).global_text_wrap_length
            elements[k].validate_constants()
            elements[k].validate_value()
            elements[k].validate_text_attributes()

    result_stream = Filler().fill(template_stream, elements)

    assert result_stream != template_stream

    for element in TemplateCore().iterate_elements(result_stream):
        key = TemplateCore().get_element_key(element)

        assert element[
            TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)

        if isinstance(data_dict[key], bool):
            assert element[TemplateConstants().checkbox_field_value_key] == (
                pdfrw.PdfName.Yes if data_dict[key] else pdfrw.PdfName.Off)
    def __init__(self, form_data, batch, template_path, output_path):
        def read_template(template_path):
            return pdfrw.PdfReader(template_path)

        self.data = map_data(form_data, batch)
        self.output_path = output_path
        self.template = read_template(template_path)
        self.template.Root.AcroForm.update(
            pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject("true")))
Exemple #19
0
def encode_xobj(im, xobj, name, img_format, **kwargs):
    N = pdfrw.PdfName
    buf = io.BytesIO()
    xobj_new = xobj.copy()
    width, height = im.size
    if name:
        xobj_new[N('Name')] = name
    xobj_new[N('Width')] = width
    xobj_new[N('Height')] = height
    xobj_new[N('BitsPerComponent')] = 8
    with contextlib.suppress(KeyError):
        del xobj_new['/DecodeParms']
    if im.mode in '1L':
        xobj_new[N('ColorSpace')] = N('DeviceGray')
    else:
        xobj_new[N('ColorSpace')] = N('DeviceRGB')
    if img_format == 'group4':
        im.save(buf, 'TIFF', compression='group4', **kwargs)
        out_im_load = Image.open(buf)
        strip_offsets = out_im_load.tag_v2[TiffImagePlugin.STRIPOFFSETS]
        strip_bytes = out_im_load.tag_v2[TiffImagePlugin.STRIPBYTECOUNTS]
        assert len(strip_offsets) == len(strip_bytes) == 1
        buf.seek(strip_offsets[0])
        xobj_new[N('BitsPerComponent')] = 1
        xobj_new[N('ImageMask')] = pdfrw.PdfObject('true')
        xobj_new[N('Filter')] = N('CCITTFaxDecode')
        xobj_new[N('DecodeParms')] = pdfrw.PdfDict(
            K=-1, Columns=width, Rows=height, BlackIs1=pdfrw.PdfObject("true"))
        xobj_new.stream = buf.read(strip_bytes[0]).decode('latin-1')
    elif img_format == 'jpg':
        im.save(buf, 'JPEG', **kwargs)
        xobj_new[N('Filter')] = N('DCTDecode')
        xobj_new.stream = buf.getvalue().decode('latin-1')
    elif img_format == 'jp2k':
        im.save(buf, 'JPEG2000', **kwargs)
        xobj_new[N('Filter')] = N('JPXDecode')
        xobj_new.stream = buf.getvalue().decode('latin-1')
    elif img_format == 'png':
        xobj_new[N('Filter')] = N('FlateDecode')
        data = zlib.compress(im.tobytes('raw'), 9)
        xobj_new.stream = data.decode('latin-1')
    else:
        raise NotImplementedError(img_format)
    return xobj_new
Exemple #20
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)
Exemple #21
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)
Exemple #22
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)
Exemple #23
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')))
    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)
    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
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']:
		# Custom/Fields
		if annotation['/Subtype'] == '/Widget' and ('/Parent' in annotation):
			key = annotation['/Parent']['/T'][1:-1] # Remove parentheses
			if key in data_dict.keys():
				annotation['/Parent'].update(pdfrw.PdfDict(V=f'{data_dict[key]}'))
				
	pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Exemple #27
0
def pdf_writer(input_pdf_path,
               output_pdf_path=None,
               data_dict=None,
               lock=None):
    ANNOT_KEY = '/Annots'
    ANNOT_FIELD_KEY = '/T'
    ANNOT_FORM_type = '/FT'  # Form type (e.g. text/button)
    ANNOT_FORM_button = '/Btn'  # ID for buttons, i.e. a checkbox
    ANNOT_FORM_text = '/Tx'  # ID for textbox
    ANNOT_VAL_KEY = '/V'
    ANNOT_RECT_KEY = '/Rect'
    SUBTYPE_KEY = '/Subtype'
    WIDGET_SUBTYPE_KEY = '/Widget'

    template_pdf = pdfrw.PdfReader(input_pdf_path)
    annotation_col = []
    for page in template_pdf.pages:
        annotation_col.append(page[ANNOT_KEY])
    if data_dict:
        data_dict = data_dict
    else:
        data_dict = {}  #creating empty dict, won't trigger later if statement

    for annotations in annotation_col:
        for annotation in annotations:
            if type(annotation) != None:
                if annotation[ANNOT_FIELD_KEY] and annotation[
                        SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                    key = annotation[ANNOT_FIELD_KEY][1:-1]
                    if key in data_dict.keys():
                        try:
                            annotation.update(
                                pdfrw.PdfDict(V='{}'.format(data_dict[key])))
                        except:
                            print("didn't work boss")
                    if lock:
                        if lock == False:
                            annotation.update(pdfrw.PdfDict(Ff=0))
                        if lock == True:
                            annotation.update(pdfrw.PdfDict(Ff=1))
    if output_pdf_path:
        output_pdf_path = output_pdf_path
    else:
        output_pdf_path = input_pdf_path

    template_pdf.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Exemple #28
0
def test_simple_fill(template_stream, data_dict):
    result_stream = Filler().simple_fill(template_stream, data_dict, False)

    assert result_stream != template_stream

    for element in TemplateCore().iterate_elements(result_stream):
        key = TemplateCore().get_element_key(element)

        if isinstance(data_dict[key], bool):
            assert element[TemplateConstants().checkbox_field_value_key] == (
                pdfrw.PdfName.Yes if data_dict[key] else pdfrw.PdfName.Off)
        else:
            assert (element[TemplateConstants().text_field_value_key][1:-1] ==
                    data_dict[key])
        assert element[
            TemplateConstants().field_editable_key] == pdfrw.PdfObject(1)
Exemple #29
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]
                if key in data.keys() and data[key] is not None:
                    kwargs = {'V': '{}'.format(data[key])}

                    if annotation.V in {'/Off', '/On', '/1', '/0'}:
                        kwargs['AS'] = pdfname.BasePdfName(data[key])
                        kwargs['V'] = pdfname.BasePdfName(data[key])

                    annotation.update(pdfrw.PdfDict(**kwargs))

    template.Root.AcroForm.update(
        pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
Exemple #30
0
    def _assign_uuid(self):
        generated_pdf = pdfrw.PdfReader(self._output_path)

        for i in range(len(generated_pdf.pages)):
            annotations = generated_pdf.pages[i][self._ANNOT_KEY]
            if annotations:
                for annotation in annotations:
                    if self._ANNOT_FIELD_KEY in annotation.keys():
                        annotation.update(
                            pdfrw.PdfDict(
                                T="{}_{}".format(
                                    annotation[self._ANNOT_FIELD_KEY][1:-1],
                                    self._uuid,
                                ),
                                Ff=pdfrw.PdfObject(1),
                            ))

        pdfrw.PdfWriter().write(self._final_path, generated_pdf)