Split pdf based on outline

I would like to use pyPdf to split a PDF file based on a path, where each destination in the path links to another page in pdf.

Example circuit:

main -> points to page 1
  sect1 -> points to page 1
  sect2 -> points to page 15
  sect3 -> points to page 22

in pyPdf, it is easy to cut through every page of a document or each recipient in the outline of a document; however, I cannot figure out how to get the page number where the destination points are.

Does anyone know how to find the page reference number for each destination in the outline?

+5
source share
4 answers

I understood:

    class Darrell (pyPdf.PdfFileReader):

        def getDestinationPageNumbers(self):
            def _setup_outline_page_ids(outline, _result=None):
                if _result is None:
                    _result = {}
                for obj in outline:
                    if isinstance(obj, pyPdf.pdf.Destination):
                        _result[(id(obj), obj.title)] = obj.page.idnum
                    elif isinstance(obj, list):
                        _setup_outline_page_ids(obj, _result)
                return _result

            def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None):
                if _result is None:
                    _result = {}
                if pages is None:
                    _num_pages = []
                    pages = self.trailer["/Root"].getObject()["/Pages"].getObject()
                t = pages["/Type"]
                if t == "/Pages":
                    for page in pages["/Kids"]:
                        _result[page.idnum] = len(_num_pages)
                        _setup_page_id_to_num(page.getObject(), _result, _num_pages)
                elif t == "/Page":
                    _num_pages.append(1)
                return _result

            outline_page_ids = _setup_outline_page_ids(self.getOutlines())
            page_id_to_page_numbers = _setup_page_id_to_num()

            result = {}
            for (_, title), page_idnum in outline_page_ids.iteritems():
                result[title] = page_id_to_page_numbers.get(page_idnum, '???')
            return result

    pdf = Darrell(open(PATH-TO-PDF, 'rb'))
    template = '%-5s  %s'
    print template % ('page', 'title')
    for p,t in sorted([(v,k) for k,v in pdf.getDestinationPageNumbers().iteritems()]):
        print template % (p+1,t)
+6

Darrell pdf ( pdftoc pdftk.)

_setup_page_id_to_num, "", 1. . , , . .

"PDF Hacks" , LaTeX, .. , pdftk , python.

+1

, . PdfFileReader PyPDF2.

, PyPDF2 sejda-console PDF . 1, . script .

import operator
import os
import subprocess
import sys
import time

import PyPDF2 as pyPdf

# need to have sejda-console installed
# change this to point to your installation
sejda = 'C:\\sejda-console-1.0.0.M2\\bin\\sejda-console.bat'

class Darrell(pyPdf.PdfFileReader):
    ...

if __name__ == '__main__':
    t0= time.time()

    # get the name of the file to split as a command line arg
    pdfname = sys.argv[1]

    # open up the pdf
    pdf = Darrell(open(pdfname, 'rb'))

    # build list of (pagenumbers, newFileNames)
    splitlist = [(1,'FrontMatter')] # Customize name of first section

    template = '%-5s  %s'
    print template % ('Page', 'Title')
    print '-'*72
    for t,p in sorted(pdf.getDestinationPageNumbers().iteritems(),
                      key=operator.itemgetter(1)):

        # Customize this to get it to split where you want
        if t.startswith('Chapter') or \
           t.startswith('Preface') or \
           t.startswith('References'):

            print template % (p+1, t)

            # this customizes how files are renamed
            new = t.replace('Chapter ', 'Chapter')\
                   .replace(':  ', '-')\
                   .replace(': ', '-')\
                   .replace(' ', '_')
            splitlist.append((p+1, new))

    # call sejda tools and split document
    call = sejda
    call += ' splitbypages'
    call += ' -f "%s"'%pdfname
    call += ' -o ./'
    call += ' -n '
    call += ' '.join([str(p) for p,t in splitlist[1:]])
    print '\n', call
    subprocess.call(call)
    print '\nsejda-console has completed.\n\n'

    # rename the split files
    for p,t in splitlist:
        old ='./%i_'%p + pdfname
        new = './' + t + '.pdf'
        print 'renaming "%s"\n      to "%s"...'%(old, new),

        try:
            os.remove(new)
        except OSError:
            pass

        try:
            os.rename(old, new)
            print' succeeded.\n'
        except:
            print' failed.\n'

    print '\ndone. Spliting took %.2f seconds'%(time.time() - t0)
0

@darrell, UTF-8, , .

pyPdf.pdf.Destination.title, :

  • pyPdf.generic.TextStringObject
  • pyPdf.generic.ByteStringObject

so the output from the function _setup_outline_page_ids()also returns two different types for the object titlethat fails with UnicodeDecodeErrorif the header header contains anything other than ASCII.

I added this code to solve the problem:

if isinstance(title, pyPdf.generic.TextStringObject):
    title = title.encode('utf-8')

whole class:

class PdfOutline(pyPdf.PdfFileReader):

    def getDestinationPageNumbers(self):

        def _setup_outline_page_ids(outline, _result=None):
            if _result is None:
                _result = {}
            for obj in outline:
                if isinstance(obj, pyPdf.pdf.Destination):
                    _result[(id(obj), obj.title)] = obj.page.idnum
                elif isinstance(obj, list):
                    _setup_outline_page_ids(obj, _result)
            return _result

        def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None):
            if _result is None:
                _result = {}
            if pages is None:
                _num_pages = []
                pages = self.trailer["/Root"].getObject()["/Pages"].getObject()
            t = pages["/Type"]
            if t == "/Pages":
                for page in pages["/Kids"]:
                    _result[page.idnum] = len(_num_pages)
                    _setup_page_id_to_num(page.getObject(), _result, _num_pages)
            elif t == "/Page":
                _num_pages.append(1)
            return _result

        outline_page_ids = _setup_outline_page_ids(self.getOutlines())
        page_id_to_page_numbers = _setup_page_id_to_num()

        result = {}
        for (_, title), page_idnum in outline_page_ids.iteritems():
            if isinstance(title, pyPdf.generic.TextStringObject):
                title = title.encode('utf-8')
            result[title] = page_id_to_page_numbers.get(page_idnum, '???')
        return result
0
source

All Articles