Пример #1
0
def every_other(vouch_list: str, sign: io.BytesIO) -> io.BytesIO:
    v = pdfrw.PdfReader(vouch_list)
    pages = v.pages
    sign_page = pdfrw.PdfReader(sign).pages[0]
    writer = pdfrw.PdfWriter()

    for page in range(len(pages)):
        writer.addpage(pages[page])
        writer.addpage(sign_page)

    form = io.BytesIO()
    writer.write(form)
    form.seek(0)
    return form
Пример #2
0
def write_fillable_pdf2(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    for i in range(0, len(template_pdf.pages)):
        annotations = template_pdf.pages[i][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 key == 'FTEstart3':
                            print("hi")
                        annotation.update(
                            pdfrw.PdfDict(V='{}'.format(data_dict[key])))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #3
0
def make_referee_sheets(df, template):
    # Robot Game sheets
    rg_tables = pd.concat([df['Table1'],
                           df['Table2'],
                           df['Table3']]).unique()
    rg_tables.sort()
    print('Robot Game: ', end='', flush=True)
    for table in rg_tables:
        rg_writer = pdfrw.PdfWriter()
        rg_template_pdf = pdfrw.PdfReader(template)
        pdf = 'Robot Game {0}.pdf'.format(table)
        print('{0} '.format(table), end='', flush=True)
        # For each 8 tables and 48 teams, this probably comes down to:
        # 3x Round 1, 3x Round 2, 3x Round 1, 3x Round 2, 6x Round 3, but this
        # method should be generic for any 3-round tournament setup
#        teams_on_table = df[(df['Table1'] == table) |
#                            (df['Table2'] == table) |
#                            (df['Table3'] == table)]
        table_round_1 = df[df['Table1'] == table].sort_values('Time1')
        table_round_2 = df[df['Table2'] == table].sort_values('Time2')
        table_round_3 = df[df['Table3'] == table].sort_values('Time3')
        teams_on_table = pd.concat([table_round_1[['Team', 'Time1']],
                                    table_round_2[['Team', 'Time2']],
                                    table_round_3[['Team', 'Time3']]],
                                    sort=True)
        teams_on_table['Round'] = teams_on_table.apply(
                lambda row: which_round(row, table), axis=1)
        teams_on_table['Time'] = teams_on_table.apply(
                lambda row: which_time(row), axis=1)
        # Make a bunch of empty sheets for the merge
        print("({0} teams), ".format(len(teams_on_table)), end='', flush=True)
        for i in range(len(teams_on_table)):
            rg_writer.addpage(rg_template_pdf.pages[0])
        rg_writer.write(pdf)

        # This is a bit heavy on the reading/writing, but at 144 total pages,
        # it's not too bad so far.
        page_number = 0
        for index, row in teams_on_table.sort_values('Time').iterrows():
            print("{0} ".format(row['Team'].astype(int)), end='', flush=True)
            # base_pdf = pdfrw.PdfReader(pdf)
            canvas_data = rg_get_overlay_canvas(row['Round'].astype(int),
                                                row['Team'].astype(int),
                                                table)
            form = merge(canvas_data, template_path=pdf, page=page_number)
            page_number = page_number + 1
            save(form, filename=pdf)
        print(". ")
    print('')
Пример #4
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
Пример #5
0
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    annotations = template_pdf.pages[1][ANNOT_KEY]
    for annotation in annotations:
        if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
            if annotation[ANNOT_FIELD_KEY]:
                key = annotation[ANNOT_FIELD_KEY][1:-1]
                if key in data_dict.keys():
                    print("Matched: ", key)
                    annotation.update(
                        pdfrw.PdfDict(V='{}'.format(data_dict[key])))
        # Hack to change appearance so filled up text fields show in Preview
        annotation.update(pdfrw.PdfDict(AP=''))

    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #6
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]
	#print(annotations)
	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():
					annotation.update(
						pdfrw.PdfDict(AP=data_dict[key], V=data_dict[key])
					)
	pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #7
0
def populate_fields(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]
                    key_main = KEY_MATCH.search(key).group(
                        1) if KEY_MATCH.search(key) else key
                    print(key_main)
                    if key_main in data_dict.keys():
                        annotation.update(
                            pdfrw.PdfDict(V='{}'.format(data_dict[key_main])))
            pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    '''
    This function will fill in pdf's forms based on a form pdf
    '''

    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])))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #9
0
def merge_pdfs(form_pdf, overlay_pdf, output):
    """
    Merge the specified fillable form PDF with the 
    overlay PDF and save the output
    """
    form = pdfrw.PdfReader(form_pdf)
    olay = pdfrw.PdfReader(overlay_pdf)

    for form_page, overlay_page in zip(form.pages, olay.pages):
        merge_obj = pdfrw.PageMerge()
        overlay = merge_obj.add(overlay_page)[0]
        pdfrw.PageMerge(form_page).add(overlay).render()

    writer = pdfrw.PdfWriter()
    writer.write(output, form)
Пример #10
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']:
		# 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)
Пример #11
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)
Пример #12
0
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(T=data_dict[key]))

                    #annotation.update(
                    #    pdfrw.PdfDict(AS='{}'.format(data_dict[key]))
                    #    )

    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #13
0
    def merge_two_pdfs(pdf: bytes, other: bytes) -> bytes:
        """Merges two PDFs into one PDF."""

        writer = pdfrw.PdfWriter()

        writer.addpages(pdfrw.PdfReader(fdata=pdf).pages)
        writer.addpages(pdfrw.PdfReader(fdata=other).pages)

        result_stream = BytesIO()
        writer.write(result_stream)
        result_stream.seek(0)

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

        return result
Пример #14
0
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    annotations = template_pdf.pages[1][ANNOT_KEY]
    print(annotations)
    print('\n')
    print('LINE')
    print('\n')
    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():
                    annotation.update(
                        pdfrw.PdfDict(V='{}'.format(data_dict[key])))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #15
0
def merge(overlay, basename):
    '''
    Merge the overlay with the original form, and return the result.
    '''

    input_pdf_path = os.path.join('templates', basename)

    template_pdf = pdfrw.PdfReader(input_pdf_path)
    overlay_pdf = pdfrw.PdfReader(overlay)
    for page, data in zip(template_pdf.pages, overlay_pdf.pages):
        overlay = pdfrw.PageMerge().add(data)[0]
        pdfrw.PageMerge(page).add(overlay).render()
    form = io.BytesIO()
    pdfrw.PdfWriter().write(form, template_pdf)
    form.seek(0)
    return form
Пример #16
0
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path) #reads the file from the input_pdf_path that was passed in
    annotations = template_pdf.pages[1][ANNOT_KEY] #populating data onto the second page of the pdf 
    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) #populates the fields of the pdf with the corresponding data from data_dict and writes it to the output_pdf_path that was passed in
    data_dict = {
   'show': '11/7/2018',
   'judge': 'Bertha',
    } #hardcoded info to populate the pdf's "show" and 'judge' fields
Пример #17
0
def merge_pdfs(child, output):
    create_overlay(child)
    overlay_path = child.child_id + "_overlay.pdf"
    form_pdf = child.child_id + ".pdf"
    form = pdfrw.PdfReader("health_forms/" + form_pdf)
    olay = pdfrw.PdfReader(overlay_path)

    for form_page, overlay_page in zip(form.pages, olay.pages):
        merge_obj = pdfrw.PageMerge()
        overlay = merge_obj.add(overlay_page)[0]
        pdfrw.PageMerge(form_page).add(overlay).render()

    writer = pdfrw.PdfWriter()
    writer.write(output, form)

    if os.path.exists(overlay_path):
        os.remove(overlay_path)
Пример #18
0
def merge_pdfrw(filename1, filename2, ofilename):
    import pdfrw
    # PdfReader isn't usable as context-manager
    pdf1, pdf2 = (pdfrw.PdfReader(x) for x in (filename1, filename2))
    w = pdfrw.PdfWriter()
    for page1, page2 in zip(pdf1.pages, pdf2.pages):
        m = pdfrw.PageMerge(page1)
        m.add(page2)
        m.render()
        w.addpage(page1)
    # is sufficient if both files contain the same number of pages:
    # w.write(ofilename, pdf1)
    n1, n2 = len(pdf1.pages), len(pdf2.pages)
    if n1 != n2:
        for page in (pdf2.pages[n1:] if n1 < n2 else pdf1.pages[n2:]):
            w.addpage(page)
    w.write(ofilename)
Пример #19
0
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")
Пример #20
0
    def append_pdf(self):
        for item in self.results_buffer:
            # pull the new page out of the work item
            newpage = pdfrw.PdfReader(fdata=item.thing, verbose=False).pages[0]

            # if necessary, create the output pdf
            if self.pdf is None:
                self.pdf = pdfrw.PdfWriter(self.options.general.pdfname,
                                           version="1.4")

            # add the page to the output pdf
            self.pdf.addpage(newpage)
            self.write_pdf()

            # increase internal counter
            self.last_written = item.number
        self.results_buffer = []
Пример #21
0
def fill_pdf(data_dict):
    template_pdf = pdfrw.PdfReader(Defendant_Form_TEMPLATE_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]))
                        # pdfrw.PdfDict(V=data_dict[key])
                    )
    # print(template_pdf)
    output_filename = Filled_Form_OUTPUT_PATH  #+ str(random.randint(1000,9999))
    pdfrw.PdfWriter().write(output_filename, template_pdf)
    return output_filename
Пример #22
0
def writePDF(inputPath, outputPath, dataDict):
	"""Function to fill in the forms of a PDF with values from Dict.
	
	:param inputPath: Path of template PDF
	:param outputPath: Path to make new PDF at
	:param dataDict: Dictionary with keys with same name as form fields.
	"""
	templatePDF = pdfrw.PdfReader(inputPath)
	annotations = templatePDF.pages[0][annotMarker]
	for annotation in annotations:
		if annotation[subMarker] == widgetMarker:
			if annotation[fieldMarker]:
				key = annotation[fieldMarker][1:-1]
				if key in dataDict.keys():
					annotation.update(pdfrw.PdfDict(V='{}'.format(dataDict[key])))

	pdfrw.PdfWriter().write(outputPath, templatePDF)
Пример #23
0
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)
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    # reads the file from the input_pdf_path that was passed in
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    for i in range(1, 22):
        # populating data onto the second page of the pdf
        annotations = template_pdf.pages[i][ANNOT_KEY]
        for annotation in annotations:
            # print(annotation)
            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():
                        # print(key + ": " + data_dict[key])
                        annotation.update(
                            pdfrw.PdfDict(V='{}'.format(data_dict[key])))
        # populates the fields of the pdf with the corresponding data from data_dict and writes it to the output_pdf_path that was passed in
        pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #25
0
def read_fillable_pdf2(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    annotations = template_pdf.pages[0][ANNOT_KEY]
    i = 0
    for annotation in annotations:
        if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
            if annotation[ANNOT_FIELD_KEY]:
                key = annotation['/T'][1:-1]
                # if parsedKey=='death_year':
                # print('id=',i,'key=',key)
                if (i == 22):
                    print("before: ", annotation)
                    annotation.update(pdfrw.PdfDict(AS='/1'))
                    print('id=', i, 'key=', key)
                    print('after: ', annotation)
                    # annotation.update(pdfrw.PdfDict(V=pdfrw.PdfName('Y')))
        i += 1
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
Пример #26
0
def optimize_pdf(filename, output, encode_params, parallel=None):
    pdf = pdfrw.PdfReader(filename)
    parallel = parallel or os.cpu_count()
    with concurrent.futures.ThreadPoolExecutor(
            max_workers=parallel) as executor:
        futures = []
        completed = 0
        for page in pdf.pages:
            # _optimize_obj(page, encode_params)
            futures.append(executor.submit(_optimize_obj, page, encode_params))
        total = len(futures)
        for fut in concurrent.futures.as_completed(futures):
            completed += 1
            print('%d/%d %d%%\r' % (completed, total, 100 * completed / total),
                  end='')
        print('Completed. Writing pdf...')
    writer = pdfrw.PdfWriter(output, trailer=pdf)
    writer.write()
Пример #27
0
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)
Пример #28
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)
Пример #29
0
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)
Пример #30
0
def write_fillable_pdf2(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=pdfrw.PdfName.Yes,
                                      AS=pdfrw.PdfName.On,
                                      AP=pdfrw.PdfName.Yes))
                    print(
                        pdfrw.PdfDict(V=pdfrw.PdfName.Yes,
                                      AS=pdfrw.PdfName.On,
                                      AP=pdfrw.PdfName.On))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)