Python - Split pdf by pages
<p>I am using <code>PyPdf2</code> to split large <code>PDF</code> to pages. The problem is that this process is very slow.</p>

<p>This is the code i use:</p>

<pre><code>import os
from PyPDF2 import PdfFileWriter, PdfFileReader

with open(input_pdf_path, "rb") as input_file:
    input_pdf = PdfFileReader(input_file)
    directory = "%s/paging/" % os.path.dirname(input_pdf_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

    page_files = []
    for i in range(0, input_pdf.numPages):
        output = PdfFileWriter()
        output.addPage(input_pdf.getPage(i))
        file_name = "%s/#*#*#*##-%s.pdf" % (directory, i)
        page_files.append(file_name)
        with open(file_name, "wb") as outputStream:
            output.write(outputStream)
</code></pre>

<p>Using this code it takes about 35 to 55 seconds to split a 177 pages pdf. Is there a way i can improve this code? Is there any other library that is more suitable for this job?</p>

<p>Any optimization couldn't really make a real improvement. I ended up using <code>pdftk</code>. I came across with this <a href="http://linuxcommando.blogspot.co.il/2013/02/splitting-up-is-easy-for-pdf-file.html" rel="nofollow">page</a> which explains really nice how to split pages fast. </p>

<p><code>pdftk</code> is a command line tool(and a graphical one) with some very nice options.</p>

<p>Installation:</p>

<pre><code> sudo apt-get update
 sudo apt-get install pdftk
</code></pre>

<p>Usage with python3:</p>

<pre><code> process = Popen(['pdftk',
                     input_pdf_path,
                     'burst',
                     'output',
                     PdfSplitter.FILE_FORMAT + '%d.pdf'],
                     stdout=PIPE,
                     stderr=PIPE)
 stdout, stderr = process.communicate()
</code></pre>

<p>With this tool i managed to split up the 177 pages pdf within <strong>2 seconds</strong>.</p>

python python-3.x pdf pypdf pypdf2