Example #1
0
def test_add_named_destination():
    reader = PdfReader(os.path.join(RESOURCE_ROOT, "pdflatex-outline.pdf"))
    writer = PdfWriter()

    for page in reader.pages:
        writer.add_page(page)

    from PyPDF2.generic import NameObject

    writer.add_named_destination(NameObject("A named dest"), 2)
    writer.add_named_destination(NameObject("A named dest2"), 2)

    from PyPDF2.generic import IndirectObject

    assert writer.get_named_dest_root() == [
        "A named dest",
        IndirectObject(7, 0, writer),
        "A named dest2",
        IndirectObject(10, 0, writer),
    ]

    # write "output" to PyPDF2-output.pdf
    tmp_filename = "dont_commit_named_destination.pdf"
    with open(tmp_filename, "wb") as output_stream:
        writer.write(output_stream)

    # Cleanup
    os.remove(tmp_filename)
Example #2
0
def set_need_appearances_writer(writer):
    """
    Helper para escribir el pdf
    :param writer: el pdf
    :return:
    """
    # See 12.7.2 and 7.7.2 for more information:
    # http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
    try:
        catalog = writer._root_object
        # get the AcroForm tree and add "/NeedAppearances attribute
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"):
                IndirectObject(len(writer._objects), 0, writer)
            })

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
            True)
        return writer

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))
        return writer
Example #3
0
    def _set_appearances_to_writer(self, writer: PdfFileWriter) -> None:
        catalog = writer._root_object
        # get the AcroForm tree
        if "/AcroForm" not in catalog:
            writer._root_object.update({NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)})

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
Example #4
0
def set_need_appearances_writer(writer):
    try:
        catalog = writer._root_object
        # get the AcroForm tree and add "/NeedAppearances attribute
        if "/AcroForm" not in catalog:
            writer._root_object.update({NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)})
        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))

    return writer
Example #5
0
def updateFormProperlyWriter(writer: PdfFileWriter):
    try:
        catalog = writer._root_object
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"):
                IndirectObject(len(writer._objects), 0, writer)
            })

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
            True)
        return writer

    except Exception as e:
        print('updateFormProperlyWriter() catch : ', repr(e))
        return writer
Example #6
0
    def _setNeedAppearanceWriter(self):
        # See 12.7.2 and 7.7.2 for more information: http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
        try:
            catalog = self._root_object
            # get the AcroForm tree
            if "/AcroForm" not in catalog:
                self._root_object.update({
                    NameObject("/AcroForm"):
                    IndirectObject(len(self._objects), 0, self)
                })

            need_appearances = NameObject("/NeedAppearances")
            self._root_object["/AcroForm"][need_appearances] = BooleanObject(
                True)
        except Exception as e:
            print('setNeedAppearanceWriter() catch : ', repr(e))
        finally:
            return self
Example #7
0
def set_need_appearances_writer(writer):
    # basically used to ensured there are not
    # overlapping form fields, which makes printing hard
    try:
        catalog = writer._root_object
        # get the AcroForm tree and add "/NeedAppearances attribute
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"): IndirectObject(len(writer._objects),
                                                        0, writer)})

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))

    return writer
def set_need_appearances_writer(writer: PdfFileWriter):
    # See 12.7.2 and 7.7.2 for more information: http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
    try:
        catalog = writer._root_object
        # get the AcroForm tree
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"):
                IndirectObject(len(writer._objects), 0, writer)
            })

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
            True)
        # del writer._root_object["/AcroForm"]['NeedAppearances']
        return writer

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))
        return writer
Example #9
0
    def set_need_appearances_writer(self, writer):
        """
        Funzione usata dalla get_export_pdf per generare il report
        precompilato dell'AdE liquidazione periodica IVA
        """
        try:
            catalog = writer._root_object
            # get the AcroForm tree
            if "/AcroForm" not in catalog:
                writer._root_object.update({
                    NameObject("/AcroForm"):
                    IndirectObject(len(writer._objects), 0, writer)
                })

            need_appearances = NameObject("/NeedAppearances")
            writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
                True)
            return writer

        except Exception as e:
            print('set_need_appearances_writer() catch : ', repr(e))
            return writer
Example #10
0
def test_indirect_object_premature(value):
    stream = BytesIO(value)
    with pytest.raises(PdfStreamError) as exc:
        IndirectObject.read_from_stream(stream, None)
    assert exc.value.args[0] == "Stream has ended unexpectedly"
Example #11
0
reader = PdfFileReader(pdf)

for key in reader.getFormTextFields().keys():
    print(key)

values = {
    'Last, First, Middle': 'Testerson, Testy, S',
    'Service Branch': 'Air Force',
    'Trusted Agent Name': 'Another Person',
}

writer = PdfFileWriter()
if "/AcroForm" not in writer._root_object:
    writer._root_object.update({
        NameObject("/AcroForm"):
        IndirectObject(len(writer._objects), 0, writer)
    })
writer._root_object["/AcroForm"].update(
    {NameObject("/NeedAppearances"): BooleanObject(True)})


def update_fields(page):
    if '/Annots' in page:
        writer.updatePageFormFieldValues(page, values)


writer.appendPagesFromReader(reader, update_fields)

out = open(sys.argv[2], "wb")
writer.write(out)
out.close()
Example #12
0
    def cloneDocumentFromReader(self, reader: PdfFileReader, *args) -> None:
        """Create a copy (clone) of a document from a PDF file reader.

        :param reader: PDF file reader instance from which the clone
            should be created.
        :callback after_page_append (function): Callback function that is invoked after
            each page is appended to the writer. Signature includes a reference to the
            appended page (delegates to appendPagesFromReader). Callback signature:

            :param writer_pageref (PDF page reference): Reference to the page just
                appended to the document.
        """
        mustAddTogether = False
        newInfoRef = self._info
        oldPagesRef = self._pages
        oldPages = self.getObject(self._pages)

        # If there have already been any number of pages added

        if oldPages[NameObject("/Count")] > 0:
            # Keep them
            mustAddTogether = True
        else:
            # Through the page object out
            if oldPages in self._objects:
                newInfoRef = self._pages
                self._objects.remove(oldPages)

        # Clone the reader's root document
        self.cloneReaderDocumentRoot(reader)
        if not self._root:
            self._root = self._addObject(self._root_object)

        # Sweep for all indirect references
        externalReferenceMap = {}
        self.stack = []
        newRootRef = self._sweepIndirectReferences(externalReferenceMap,
                                                   self._root)

        # Delete the stack to reset
        del self.stack

        # Clean-Up Time!!!
        # Get the new root of the PDF
        realRoot = self.getObject(newRootRef)

        # Get the new pages tree root and its ID Number
        tmpPages = realRoot[NameObject("/Pages")]
        newIdNumForPages = 1 + self._objects.index(tmpPages)

        # Make an IndirectObject just for the new Pages
        self._pages = IndirectObject(newIdNumForPages, 0, self)

        # If there are any pages to add back in
        if mustAddTogether:
            # Set the new page's root's parent to the old
            # page's root's reference
            tmpPages[NameObject("/Parent")] = oldPagesRef
            # Add the reference to the new page's root in
            # the old page's kids array

            newPagesRef = self._pages
            oldPages[NameObject("/Kids")].append(newPagesRef)
            # Set all references to the root of the old/new
            # page's root
            self._pages = oldPagesRef
            realRoot[NameObject("/Pages")] = oldPagesRef
            # Update the count attribute of the page's root
            oldPages[NameObject("/Count")] = \
                NumberObject(oldPages[NameObject("/Count")] + tmpPages[NameObject("/Count")])
        else:
            # Bump up the info's reference b/c the old
            # page's tree was bumped off
            self._info = newInfoRef