Exemple #1
0
 def pdfobjs(self):
     """Returns a tuple of two elements to insert in the PageLabels.Nums
     entry of a pdf"""
     pagenum = PdfObject(self.startpage)
     opts = PdfDict(S=styles[self.style])
     if self.prefix != defaults["prefix"]:
         opts.P = PdfString.encode(self.prefix)
     if self.firstpagenum != defaults["firstpagenum"]:
         opts.St = PdfObject(self.firstpagenum)
     return (pagenum, opts)
Exemple #2
0
def fill_form(input_file, output_file, data):
    """input_file can be file object or path name
    output_file can be file object or path name
    data is dictionary with keys corresponding to the form fields"""

    the_pdf = PdfReader(input_file)
    for page in the_pdf.pages:
        annotations = page[ANNOT_KEY]
        for annotation in annotations:
            if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                key = annotation[ANNOT_FIELD_KEY][1:-1]
                if key in data.keys():
                    val = data[key]
                    if val == None:
                        # skip nulls
                        continue
                    if val == True:
                        # treat booleans as checkboxes
                        annotation.update(PdfDict(V=PdfName("On")))
                    else:
                        # set annotation value
                        annotation.update(PdfDict(V="{}".format(val)))
                        # and empty appearance to make field visible in Apple Preview
                        annotation.update(PdfDict(AP=""))
                    # mark the fields as un-editable
                    annotation.update(PdfDict(Ff=1))

    # set NeedAppearances to ensure the fields are visible in Adobe Reader
    if the_pdf.Root.AcroForm:
        the_pdf.Root.AcroForm.update(
            PdfDict(NeedAppearances=PdfObject("true")))

    PdfWriter().write(output_file, the_pdf)
Exemple #3
0
    def write_fillable_pdf(self, input_pdf_path, output_pdf_path, data_dict):
        template_pdf = PdfReader(input_pdf_path)

        for index, _ in enumerate(template_pdf.pages):
            annotations = template_pdf.pages[index][self.ANNOT_KEY]
            if hasattr(annotations, "__len__"):
                for annotation in annotations:
                    if annotation[self.SUBTYPE_KEY] == self.WIDGET_SUBTYPE_KEY:

                        if self.ANNOT_FIELD_KEY in annotation:
                            key = annotation[self.ANNOT_FIELD_KEY][1:-1]

                            if key in data_dict.keys():
                                value = data_dict[key]
                                if annotation["/FT"] == "/Tx":
                                    if value != "-":
                                        annotation.update(
                                            PdfDict(
                                                V='{}'.format(value.upper())))
                                elif annotation[
                                        "/FT"] == "/Btn" and value == "Yes":
                                    annotation.update(
                                        PdfDict(V=objects.pdfname.BasePdfName(
                                            '/Yes')))
                    annotation.update(PdfDict(Ff=1))

        template_pdf.Root.AcroForm.update(
            PdfDict(NeedAppearances=PdfObject('true')))
        PdfWriter().write(output_pdf_path, template_pdf)
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict,
                       camposCheckBox):

    template_pdf = PdfReader(input_pdf_path)
    #Necesario para que se vean cambios
    template_pdf.Root.AcroForm.update(
        PdfDict(NeedAppearances=PdfObject('true')))

    #Por cada pagina del PDF
    for page in template_pdf.pages:
        annotations = page[ANNOT_KEY]

        #Para cada anotacion de la pagina
        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():

                        #HACK PARA LOS CHECK. Si es true, se marcan, sino no
                        if key in camposCheckBox:
                            if (data_dict[key] == 'true'):
                                annotation.update(
                                    PdfDict(V='{}'.format(data_dict[key]),
                                            AS=PdfName('Yes')))
                            #Si no se pone nada, por defecto no se marcan
                            continue

                    #Objeto necesario para que al rellenar se vean los campos
                        rct = annotation.Rect
                        hight = round(float(rct[3]) - float(rct[1]), 2)
                        width = (round(float(rct[2]) - float(rct[0]), 2))

                        xobj = PdfDict(
                            BBox=[0, 0, width, hight],
                            FormType=1,
                            Resources=PdfDict(
                                ProcSet=[PdfName.PDF, PdfName.Text]),
                            Subtype=PdfName.Form,
                            Type=PdfName.XObject)
                        #assign a stream to it
                        xobj.stream = '''/Tx BMC
                        BT
                        /Helvetica 8.0 Tf
                        1.0 5.0 Td
                        0 g
                        (''' + data_dict[key] + ''') Tj
                        ET EMC'''

                        #Actualizamos la anotacion en el PDF
                        annotation.update(
                            PdfDict(AP=PdfDict(N=xobj),
                                    V='{}'.format(data_dict[key])))

    #Escribimos el PDF ya anotado al PATH de salida
    PdfWriter().write(output_pdf_path, template_pdf)
Exemple #5
0
def populateSheet(character, context, options=default_options):
    pdfPath = Path(context.function_directory)
    pdf = PdfReader(pdfPath / options['template'])
    pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true')))

    populateFields(character, pdf.Root.AcroForm.Fields)

    output = BytesIO()
    PdfWriter().write(output, pdf)
    output.seek(0)
    return output.read()
Exemple #6
0
def fillPDF(pdf_file, fields, workId):
	pdf = PdfReader(pdf_file)
	anns = pdf.pages[0]['/Annots']
	for ann in anns:
		key = ann['/T'][1:-1]
		if key in fields:
			ann.update(PdfDict(V='{}'.format(fields[key])))

	filename = 'registro{}_s{}-{}{}.pdf'.format(workId, fields['Semana'], fields['Mes'], fields['Anio'])
	pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true')))
	PdfWriter().write(filename, pdf) 
	print(filename)
Exemple #7
0
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):

    template_pdf = PdfReader(input_pdf_path)
    # Para que se vean los campos rellenados
    template_pdf.Root.AcroForm.update(
        PdfDict(NeedAppearances=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.keys():

                        #HACK PARA LOS CHECK - Guardar documento a mano con los checks que sean. Y aquí si es un check, evitarlo y no cambiar
                        if key == "untitled6" or key == "untitled21" or key == "untitled22" or key == "untitled23" or key == "untitled24" or key == "untitled25":

                            continue

                    #this depends on page orientation
                        rct = annotation.Rect
                        hight = round(float(rct[3]) - float(rct[1]), 2)
                        width = (round(float(rct[2]) - float(rct[0]), 2))

                        xobj = PdfDict(
                            BBox=[0, 0, width, hight],
                            FormType=1,
                            Resources=PdfDict(
                                ProcSet=[PdfName.PDF, PdfName.Text]),
                            Subtype=PdfName.Form,
                            Type=PdfName.XObject)
                        #assign a stream to it
                        xobj.stream = '''/Tx BMC
                        BT
                        /Helvetica 8.0 Tf
                        1.0 5.0 Td
                        0 g
                        (''' + data_dict[key] + ''') Tj
                        ET EMC'''
                        annotation.update(
                            PdfDict(AP=PdfDict(N=xobj),
                                    V='{}'.format(data_dict[key])))
                        #annotation.update(pdfrw.PdfDict(V='{}'.format(data_dict[key]),AP='{}'.format(data_dict[key])))

    PdfWriter().write(output_pdf_path, template_pdf)
def ast_to_pdf(asdl_ast):
    constructor_name = asdl_ast.production.constructor.name

    if constructor_name == 'PdfDict':
        pdict = {}
        for arg in asdl_ast['args'].value:
            # apply
            name = BasePdfName(asdl_ast['name'].value)
            if name in ['/Parent', '/P', '/Dest', '/Prev']:
                pass
            op = ast_to_pdf(asdl_ast['op'].value)

            pdict[name] = op

        x = PdfDict(pdict)

    elif constructor_name == 'PdfArray':
        parray = []
        for arg in asdl_ast['args'].value:
            args.append(ast_to_pdf(arg))

        x = PdfArray(pdfarray)

    elif constructor_name == 'PdfList':
        var = asdl_ast['value'].value

        x = PdfArray(list(var))

    elif constructor_name == 'PdfObject':
        var = asdl_ast['value'].value
        
        x = PdfObject(var)

    elif constructor_name == 'PdfStr':
        var = asdl_ast['value'].value
        
        x = PdfStr(var)

    elif constructor_name == 'BasePdfName':
        var = asdl_ast['value'].value
        
        x = BasePdfName(var)

    return x
Exemple #9
0
 def _build_certificate_of_mailing_pdf(
         user_information: Dict[str, str]) -> PdfReader:
     form = from_dict(data_class=CertificateFormData, data=user_information)
     pdf_path = path.join(
         Path(__file__).parent, "files", f"certificate_of_mailing.pdf")
     pdf = PdfReader(pdf_path)
     for field in pdf.Root.AcroForm.Fields:
         field_name = field.T.lower().replace(" ", "_").replace("(",
                                                                "").replace(
                                                                    ")", "")
         field_value = getattr(form, field_name)
         field.V = field_value
     for page in pdf.pages:
         annotations = page.get("/Annots")
         if annotations:
             for annotation in annotations:
                 annotation.update(PdfDict(AP=""))
     pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject("true")))
     return pdf
Exemple #10
0
from pdfrw import PdfObject, PdfReader, PdfWriter
import os

files = os.listdir('files')
for file in files:
	trailer = PdfReader('files\\'+file)
	#trailer.Root.MarkInfo.Marked = 'true'
	#trailer.Root.MarkInfo = PdfObject({'/Marked': 'true'})
	trailer.Root.MarkInfo = PdfObject('<</Marked true>>')
	PdfWriter('out\\'+file, trailer=trailer).write()
Exemple #11
0
        form = from_dict(data_class=FormData, data=form_data_dict)
        pdf_path = FormFilling.build_pdf_path(case, convictions)
        pdf = PdfReader(pdf_path)
        for field in pdf.Root.AcroForm.Fields:
            field_name = field.T.lower().replace(" ", "_").replace("(",
                                                                   "").replace(
                                                                       ")", "")
            field_value = getattr(form, field_name)
            field.V = field_value
            FormFilling._set_font(field, field_value)
        for page in pdf.pages:
            annotations = page.get("/Annots")
            if annotations:
                for annotation in annotations:
                    annotation.update(PdfDict(AP=""))
        pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject("true")))
        return pdf

    @staticmethod
    def _set_font(field, field_value):
        if field["/Kids"]:
            for kid in field["/Kids"]:
                font_string = FormFilling._build_font_string(kid, field_value)
                kid.DA = font_string
        else:
            font_string = FormFilling._build_font_string(field, field_value)
            field.DA = font_string

    @staticmethod
    def _build_font_string(field, field_value):
        max_length = FormFilling._compute_field_max_length(field)