示例#1
0
def _create_pdf_attachment(attachment, url_fetcher):
    """
    Create an attachment to the PDF stream

    :return:
        the object representing the ``/Filespec`` object or :obj:`None` if the
        attachment couldn't be read.
    """
    try:
        # Attachments from document links like <link> or <a> can only be URLs.
        # They're passed in as tuples
        if isinstance(attachment, tuple):
            url, description = attachment
            attachment = Attachment(url=url,
                                    url_fetcher=url_fetcher,
                                    description=description)
        elif not isinstance(attachment, Attachment):
            attachment = Attachment(guess=attachment, url_fetcher=url_fetcher)

        with attachment.source as (source_type, source, url, _):
            if isinstance(source, bytes):
                source = io.BytesIO(source)
            pdf_file_object = _create_compressed_file_object(source)
    except URLFetchingError as exc:
        LOGGER.error('Failed to load attachment: %s', exc)
        return None

    # TODO: Use the result object from a URL fetch operation to provide more
    # details on the possible filename
    return PdfDict(Type=PdfName('Filespec'),
                   F=PdfString.encode(''),
                   UF=PdfString.encode(_get_filename_from_result(url, None)),
                   EF=PdfDict(F=pdf_file_object),
                   Desc=PdfString.encode(attachment.description or ''))
示例#2
0
def popup_bg_links(show_ocmd, ocgs):
    from pdfrw import PdfDict, PdfArray, PdfName
    if not pdf_popup_config['backgroundlink']: return
    if pdf_popup_config['backgroundlink'] not in ('front', 'back'):
        raise ValueError(
            "pdf_popup_config['backgroundlink'] must be front or back or None")

    for page in popup_pdf.pages:
        rect = page.MediaBox
        if pdf_popup_config['backgroundlink-debug']: rect = [90, 800, 180, 200]
        link = PdfDict(
            indirect=True,
            Type=PdfName.Annot,
            H=PdfName.N,
            Subtype=PdfName.Link,
            Rect=rect,
            #F=2, # Link is hidden
            Border=[0, 0, 10]
            if pdf_popup_config['backgroundlink-debug'] else [0, 0, 0],
            C=[1, 0, 0] if pdf_popup_config['backgroundlink-debug'] else None,
            OC=show_ocmd,
            A=PdfDict(S=PdfName.SetOCGState,
                      State=PdfArray([PdfName.OFF] + ocgs)),
        )

        if page.Annots == None: page.Annots = PdfArray()
        if pdf_popup_config['backgroundlink'] == 'back':
            page.Annots.insert(0, link)
        elif pdf_popup_config['backgroundlink'] == 'front':
            page.Annots.append(link)
        else:
            raise RuntimeException("Unexpected value")
示例#3
0
def _create_compressed_file_object(source):
    """
    Create a file like object as ``/EmbeddedFile`` compressing it with deflate.

    :return:
        the object representing the compressed file stream object
    """
    md5 = hashlib.md5()
    compress = zlib.compressobj()

    pdf_file_object = PdfDict(Type=PdfName('EmbeddedFile'),
                              Filter=PdfName('FlateDecode'))

    # pdfrw needs Latin-1-decoded unicode strings in object.stream
    pdf_file_object.stream = ''
    size = 0
    for data in iter(lambda: source.read(4096), b''):
        size += len(data)
        md5.update(data)
        pdf_file_object.stream += compress.compress(data).decode('latin-1')
    pdf_file_object.stream += compress.flush(zlib.Z_FINISH).decode('latin-1')
    pdf_file_object.Params = PdfDict(CheckSum=PdfString('<{}>'.format(
        md5.hexdigest())),
                                     Size=size)
    return pdf_file_object
示例#4
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)
示例#5
0
def fixpage(page, watermark):

    # Find the page's resource dictionary. Create if none
    resources = page.inheritable.Resources
    if resources is None:
        resources = page.Resources = PdfDict()

    # Find or create the parent's xobject dictionary
    xobjdict = resources.XObject
    if xobjdict is None:
        xobjdict = resources.XObject = PdfDict()

    # Allow for an infinite number of cascaded watermarks
    index = 0
    while 1:
        watermark_name = '/Watermark.%d' % index
        if watermark_name not in xobjdict:
            break
        index += 1
    xobjdict[watermark_name] = watermark

    # Turn the contents into an array if it is not already one
    contents = page.Contents
    if not isinstance(contents, PdfArray):
        contents = page.Contents = PdfArray([contents])

    # Save initial state before executing page
    contents.insert(0, IndirectPdfDict(stream='q\n'))

    # Restore initial state and append the watermark
    contents.append(IndirectPdfDict(stream='Q %s Do\n' % watermark_name))
    return page
示例#6
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)
示例#7
0
def fixpage(*pages):
    pages = [pagexobj(x) for x in pages]

    class PageStuff(tuple):
        pass

    x = y = 0
    for i, page in enumerate(pages):
        index = '/P%s' % i
        shift_right = x and '1 0 0 1 %s 0 cm ' % x or ''
        stuff = PageStuff((index, page))
        stuff.stream = 'q %s%s Do Q\n' % (shift_right, index)
        x += page.BBox[2]
        y = max(y, page.BBox[3])
        pages[i] = stuff

    # Multiple copies of first page used as a placeholder to
    # get blank page on back.
    for p1, p2 in zip(pages, pages[1:]):
        if p1[1] is p2[1]:
            pages.remove(p1)

    return IndirectPdfDict(
        Type=PdfName.Page,
        Contents=PdfDict(stream=''.join(page.stream for page in pages)),
        MediaBox=PdfArray([0, 0, x, y]),
        Resources=PdfDict(XObject=PdfDict(pages), ),
    )
示例#8
0
def generate_pdf_outline(pdf, contents, parent=None):
    if parent is None:
        parent = PdfDict(indirect=True)
    if not contents:
        return parent
    first = prev = None
    for k, row in enumerate(contents):
        page = pdf.writer.pagearray[int(row['pnum'])-1]
        bookmark = PdfDict(
            Parent=parent,
            Title=row['label'],
            A=PdfDict(
                D=[page, PdfName.Fit],
                S=PdfName.GoTo
            ),
            indirect=True
        )
        children = row.get('children')
        if children:
            bookmark = generate_pdf_outline(pdf, children, bookmark)
        if first:
            bookmark[PdfName.Prev] = prev
            prev[PdfName.Next] = bookmark
        else:
            first = bookmark
        prev = bookmark
    parent[PdfName.Count] = k + 1
    parent[PdfName.First] = first
    parent[PdfName.Last] = prev
    return parent
示例#9
0
 def pdfobjs(self):
     """Returns a tuple of two elements to insert in the PageLabels.Nums
     entry of a pdf"""
     page_num = 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 page_num, opts
示例#10
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)
示例#11
0
    def make_image_xobject(image):
        """Construct a PdfDict representing the Image XObject, for inserting
        into the AP Resources dict.

        PNGs and GIFs are treated equally - the raw sample values are included
        using PDF's FlateDecode compression format. JPEGs can be included in
        their original form using the DCTDecode filter.

        PNGs with transparency have the alpha channel split out and included as
        an SMask, since PDFs don't natively support transparent PNGs.

        Details about file formats and allowed modes can be found at
        https://pillow.readthedocs.io/en/5.3.x/handbook/image-file-formats.html

        :param str|ImageFile image: Either a str representing the path to the
            image filename, or a PIL.ImageFile.ImageFile object representing
            the image loaded using the PIL library.
        :returns PdfDict: Image XObject
        """
        image = Image.resolve_image(image)
        # PILImage.convert drops the format attribute
        image_format = image.format
        width, height = image.size

        # Normalize images to RGB or grayscale color spaces, and split out the
        # alpha layer into a PDF smask XObject
        image, smask_xobj = Image.convert_to_compatible_image(
            image,
            image_format,
        )

        if image_format in ('PNG', 'GIF'):
            content = Image.make_compressed_image_content(image)
            filter_type = 'FlateDecode'  # TODO use a predictor
        elif image_format == 'JPEG':
            content = Image.make_jpeg_image_content(image)
            filter_type = 'DCTDecode'
        else:
            raise ValueError(
                'Unsupported image format: {}. Supported formats are '
                'PNG, JPEG, and GIF'.format(image.format))

        xobj = PdfDict(
            stream=content,
            BitsPerComponent=8,
            Filter=PdfName(filter_type),
            ColorSpace=Image._get_color_space_name(image),
            Width=width,
            Height=height,
            Subtype=PdfName('Image'),
            Type=PdfName('XObject'),
        )
        if smask_xobj is not None:
            xobj.SMask = smask_xobj
        return xobj
示例#12
0
def create_bookmarks(bookmarks, pages, parent=None):
    count = len(bookmarks)
    bookmark_objects = []
    for label, target, children in bookmarks:
        destination = (pages[target[0]].indirect, PdfName('XYZ'), target[1],
                       target[2], 0)
        bookmark_object = PdfDict(Title=PdfString.encode(label),
                                  A=PdfDict(Type=PdfName('Action'),
                                            S=PdfName('GoTo'),
                                            D=PdfArray(destination)))
        bookmark_object.indirect = True
        children_objects, children_count = create_bookmarks(
            children, pages, parent=bookmark_object)
        bookmark_object.Count = 1 + children_count
        if bookmark_objects:
            bookmark_object.Prev = bookmark_objects[-1]
            bookmark_objects[-1].Next = bookmark_object
        if children_objects:
            bookmark_object.First = children_objects[0]
            bookmark_object.Last = children_objects[-1]
        if parent is not None:
            bookmark_object.Parent = parent
        count += children_count
        bookmark_objects.append(bookmark_object)
    return bookmark_objects, count
示例#13
0
 def test_indirect_set_get(self):
     io = PdfIndirect((1,2,3))
     io.value = 42
     d = PdfDict()
     d.Name = io
     test, = (x for x in dict.values(d))
     self.assertEqual(test, io)
     v = d['/Name']
     self.assertEqual(v, io.value)
     test, = d
     self.assertEqual(type(test), type(PdfName.Name))
示例#14
0
def add_payload(name, output, path):
    print('[*] Reading PDF file: %s' % name)
    reader = PdfReader(name)
    print('[*] Injecting the payload in the PDF file...')
    reader.pages[0].AA = PdfDict(
        O=PdfDict(F=r'%s' % path, D=[0, PdfName('Fit')], S=PdfName('GoToE')))
    writer = PdfWriter()
    writer.addpages(reader.pages)
    print('[*] Saving modified PDF as: %s' % output)
    writer.write(output)
    print('[*] Done!')
示例#15
0
 def test_indirect_set_get(self):
     io = PdfIndirect((1, 2, 3))
     io.value = 42
     d = PdfDict()
     d.Name = io
     test, = (x for x in dict.values(d))
     self.assertEqual(test, io)
     v = d['/Name']
     self.assertEqual(v, io.value)
     test, = d
     self.assertEqual(type(test), type(PdfName.Name))
示例#16
0
文件: horas.py 项目: avicarioe/horas
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)
示例#17
0
 def get_png_smask(image):
     width, height = image.size
     smask = Image.make_compressed_image_content(image.getchannel('A'))
     smask_xobj = PdfDict(
         stream=smask,
         Width=width,
         Height=height,
         BitsPerComponent=8,
         Filter=PdfName('FlateDecode'),
         ColorSpace=PdfName('DeviceGray'),
         Subtype=PdfName('Image'),
         Type=PdfName('XObject'),
     )
     smask_xobj.indirect = True
     return smask_xobj
def _fill_pdf_metadata(out_file, issuer, issuer_address, columns, data):
    # create metadata objest (json)
    metadata_object = {}
    metadata_fields = columns.split(",")
    for md in metadata_fields:
        if md in data:
            metadata_object[md] = data[md]

    # issuer and issuer_address used to go as separate metadata fields
    # but now go to the metadata_object. They are still compulsory!
    # The validator that reads metadata requires to look for issuer and
    # issuer_address both in the metadata_object and if not fount it has
    # to look for them as separate metadata fields for backwards
    # compatibility (certificates issued with v0.9.3 and before)
    metadata_object['issuer'] = issuer
    metadata_object['issuer_address'] = issuer_address

    # add the metadata
    metadata = PdfDict(metadata_object=json.dumps(metadata_object),
                       chainpoint_proof='')
    pdf = PdfReader(out_file)
    pdf.Info.update(metadata)
    PdfWriter().write(out_file, pdf)

    # print progress
    print('.', end="", flush=True)
示例#19
0
def aggr_pdf(pdfname, pdfpaths, origin_directory):
    params = setup()
    (G, o, g1, g2, e) = params

    # 从多个文件中读出所有签名
    sigs = []
    for path in pdfpaths:
        pdf = PdfReader(path + os.path.sep + pdfname)
        try:
            sig_str:str =  pdf.Info.signature
            sig_str = sig_str[1:-1]
            sig_bytes = base64.b64decode( sig_str.encode("utf-8") )
            sig_g1elem = G1Elem.from_bytes(sig_bytes,G)
        except:
            sig_g1elem = None
        sigs.append(sig_g1elem)

    print('all_sigs:',sigs)

    # 聚合所有签名
    sigma = aggregate_sigma(params, sigs)
    print('type sigma:',type(sigma))
    sigma_bytes = sigma.export()
    sigma_str = base64.b64encode(sigma_bytes).decode()

    # 将聚合后的签名写回运行路径中新建的以blockstackid命名的pdf中
    pdf = PdfReader(origin_directory + os.path.sep + pdfname)
    metadata_new = PdfDict(signature = sigma_str)
    pdf.Info.update(metadata_new)
    PdfWriter().write(pdfname, pdf)
示例#20
0
def get_form_fields_from_fdf(pdf_file_path):
    try:
        pdf_reader = PdfReader(pdf_file_path)
    except errors.PdfParseError:
        print(f'File \'{pdf_file_path}\' not found please specify full path')
        return None
    try:
        # Check if PDF has Form Fields and if we can read them
        pdf_form_fields = pdf_reader.Root.AcroForm.Fields
    except AttributeError:
        print(f'File \'{pdf_file_path}\' no Form Fields')
        return None

    # Create an empty PdfDict to collect Form Fields and Values
    pdf_metadata = PdfDict()

    # Define list of Form Fields to be ignored from transfer to PdfDict
    # For example: field Sig
    ignore_fields = ('/Sig',)

    # Load Form Fields into PdfDict
    for field in pdf_form_fields:
        if field.FT not in ignore_fields:
            field_name = field.T
            if field_name is not None:
                key_name = PdfName(field_name.decode())
                pdf_metadata[key_name] = field.V
    return pdf_metadata
示例#21
0
def apply_updated_text(document, text_tokens, page_tokens):
    # Create a new content stream for each page by concatenating the
    # tokens in the page_tokens lists.
    from pdfrw import PdfArray
    for i, page in enumerate(document.pages):
        if page.Contents is None: continue  # nothing was here

        # Replace the page's content stream with our updated tokens.
        # The content stream may have been an array of streams before,
        # so replace the whole thing with a single new stream. Unfortunately
        # the str on PdfArray and PdfDict doesn't work right.
        def tok_str(tok):
            if isinstance(tok, PdfArray):
                return "[ " + " ".join(tok_str(x) for x in tok) + "] "
            if isinstance(tok, InlineImage):
                return "BI " + " ".join(
                    tok_str(x) + " " + tok_str(y)
                    for x, y in tok.items()) + " ID " + tok.stream + " EI "
            if isinstance(tok, PdfDict):
                return "<< " + " ".join(
                    tok_str(x) + " " + tok_str(y)
                    for x, y in tok.items()) + ">> "
            return str(tok)

        page.Contents = PdfDict()
        page.Contents.stream = "\n".join(
            tok_str(tok) for tok in page_tokens[i])
        page.Contents.Length = len(page.Contents.stream)  # reset
def remove_chainpoint_proof_and_hash(pdf_file):
    filename = os.path.basename(pdf_file)
    tmp_filename = '__' + filename
    shutil.copy(pdf_file, tmp_filename)

    # get txid and target hash from proof
    pdf = PdfReader(tmp_filename)
    try:
        proof = json.loads(pdf.Info.chainpoint_proof.decode())
    except AttributeError:
        # TODO: log error
        return None, None
    except json.decoder.JSONDecodeError:
        # TODO: log error
        return None, None

    txid = proof['anchors'][0]['sourceId']
    targetHash = proof['targetHash']

    # remove the proof and get the hash
    metadata = PdfDict(chainpoint_proof='')
    pdf.Info.update(metadata)
    PdfWriter().write(tmp_filename, pdf)

    cert_hash = None
    with open(tmp_filename, 'rb') as cert:
        # note that the cert_hash is a hash object -- can use hexdigest() to debug
        cert_hash = hashlib.sha256(cert.read())
    os.remove(tmp_filename)

    if targetHash == cert_hash.hexdigest():
        return cert_hash.digest(), txid
    else:
        return None, None
def insert_proof_to_certificates(conf, cp, txid, cert_files):
    print('')
    for ind, val in enumerate(cert_files):
        proof = json.dumps(cp.get_receipt(ind, txid))
        metadata = PdfDict(chainpoint_proof=proof)
        pdf = PdfReader(val)
        pdf.Info.update(metadata)
        PdfWriter().write(val, pdf)
示例#24
0
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)
示例#25
0
def getPages(allpages, x, y, gap):

    # Number of pages to combine
    count = x * y

    # Pull pages off the list
    pages = [pagexobj(p) for p in allpages[:count]]
    del allpages[:count]

    # Out page size
    width_max = max(page.BBox[2] for page in pages)
    height_max = max(page.BBox[3] for page in pages)

    stream = []
    xobjdict = PdfDict()

    line = y
    for index, page in enumerate(pages):

        width = (index % x) * width_max / x
        if not width:
            line = line - 1
        height = line * height_max / y

        # Page number
        index = '/P{}'.format(index)

        format_stream = {
            "x": 1. / x - gap,
            "y": 1. / y - gap,
            "w": width,
            "h": height,
            "i": index
        }
        stream.append(
            'q {x} 0 0 {y} {w} {h} cm {i} Do Q\n'.format(**format_stream))

        xobjdict[index] = page

    return PdfDict(
        Type=PdfName.Page,
        Contents=PdfDict(stream=''.join(stream)),
        MediaBox=PdfArray([-1000 * gap, -1000 * gap, width_max, height_max]),
        Resources=PdfDict(XObject=xobjdict),
    )
示例#26
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
def get_and_remove_chainpoint_proof(pdf_file):
    pdf = PdfReader(pdf_file)
    try:
        proof = json.loads(pdf.Info.chainpoint_proof.decode())
    except AttributeError:
        return None
    metadata = PdfDict(chainpoint_proof='')
    pdf.Info.update(metadata)
    PdfWriter().write(pdf_file, pdf)
    return proof
示例#28
0
def popup_make_ocgs(num):
    from pdfrw import PdfDict, PdfArray, PdfName

    n = 2
    while choose(n, n / 2) < num:
        n += 1

    ocgs = []

    for i in range(n):
        ocg = PdfDict(Type=PdfName.OCG, Name="OCG {}".format(i), indirect=True)
        ocgs.append(ocg)

    if popup_pdf.Root.OCProperties:
        print "Root.OCProperties already exists"
    ocgs = PdfArray(ocgs)
    #ocgs.indirect = True
    popup_pdf.Root.OCProperties = PdfDict(OCGs=ocgs,
                                          D=PdfDict(Order=ocgs,
                                                    ON=[],
                                                    OFF=ocgs))

    code = [([], [])]
    for ocg in ocgs:
        code = [(c + [ocg], d) if take else (c, d + [ocg]) for c, d in code
                for take in (True, False)]
    code = [(c, d) for c, d in code if len(c) == n / 2]

    # code is now an array of all different pairs (c,d)
    # where c contains floor(n/2) OCGs and d the rest of the OCGs

    hide_ocmd = PdfDict(indirect=True,
                        Type=PdfName.OCMD,
                        OCGs=ocgs,
                        P=PdfName.AllOff)

    show_ocmd = PdfDict(indirect=True,
                        Type=PdfName.OCMD,
                        OCGs=ocgs,
                        P=PdfName.AnyOn)

    return code, ocgs, hide_ocmd, show_ocmd
示例#29
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()
示例#30
0
def _fill_pdf_metadata(out_file,
                       issuer,
                       issuer_address,
                       column_fields,
                       data,
                       global_columns,
                       verify_issuer,
                       interactive=False):

    # create version
    version = 1

    # create issuer object (json)
    issuer = {
        "name": issuer,
        "identity": {
            "address": issuer_address,
            "verification": json.loads(verify_issuer)['methods']
        }
    }

    # create metadata object (json) and add metadata
    metadata = {}

    # add custom metadata
    if column_fields:
        metadata_fields = json.loads(column_fields)['columns']
        for f in metadata_fields:
            key = list(f)[0]
            if key in data:
                field_properties = f[key]
                field_properties['value'] = data[key]
                metadata[key] = field_properties

    # add global field metadata
    if global_columns:
        global_fields = json.loads(global_columns)['fields']
        for g in global_fields:
            key = list(g)[0]
            # note that global fields override column data
            metadata[key] = g[key]

    # add the metadata
    pdf_metadata = PdfDict(version=version,
                           issuer=json.dumps(issuer),
                           metadata=json.dumps(metadata),
                           chainpoint_proof='')
    pdf = PdfReader(out_file)
    pdf.Info.update(pdf_metadata)
    PdfWriter().write(out_file, pdf)

    if interactive:
        # print progress
        print('.', end="", flush=True)
def insert_proof_to_certificates(conf, cp, txid, cert_files, interactive=False):
    if interactive:
        print('')
    for ind, val in enumerate(cert_files):
        proof = json.dumps( cp.get_receipt(ind, txid) )
        metadata = PdfDict(chainpoint_proof=proof)
        pdf = PdfReader(val)
        pdf.Info.update(metadata)
        PdfWriter().write(val, pdf)
        if interactive:
            # print progress
            print('.', end="", flush=True)
示例#32
0
文件: text.py 项目: ptwz/pdf-annotate
    def make_font_object():
        """Make a PDF Type1 font object for embedding in the annotation's
        Resources dict. Only Helvetica is supported as a base font.

        :returns PdfDict: Resources PdfDict object, ready to be included in the
            Resources 'Font' subdictionary.
        """
        return PdfDict(
            Type=PdfName('Font'),
            Subtype=PdfName('Type1'),
            BaseFont=PdfName(DEFAULT_BASE_FONT),
            Encoding=PdfName('WinAnsiEncoding'),
        )