4

I have many PDF files that have repetitions of the same slide (or variations thereof) per section. (ie: each section has near-identical copies of the same slide). I'd like to reduce the PDF and strip the extra copies, leaving only 1 page per section.

Here's an example of a PDF. Basically I'd like to automate what he's doing.

Is there any tool, like pdftk or pdfcrop or ghostscript that I could use to only keep the last page of each section in a PDF? A command-line tool would be best!

Edit: uploaded my own example. Here's an image showcasing the problem. See how there are 3 pages that have the "label" set to 2. We have 3 pages that have page index 2, and 3 pages that have page index 3. I'd like to keep the last page that has page index 2, and the last page that has page index 3. I'd like to do that for all PDF "sections" which is what Acrobat calls it!

  • @dessert just edited the question! – nickT May 3 at 12:43
  • 1
    For anybody working on this: pdftk Test.pdf dump_data 2>/dev/null | sed -E '/Index:/!d;s/.*: ([0-9]+)[0-9]/\1/' prints the first page of each section. – dessert May 3 at 13:14
2

I solved my own problem. Wrote python code to deal with it. Retrieving the PageLabels retrieves the Label itself which may or may not be numeric and the corresponding index where said Label starts. I extract the start indices of the labels, and assume that the end of a section or label occurs immediately 1 page before the next label/section starts.

#!/usr/bin/python

from PyPDF2 import PdfFileWriter, PdfFileReader
import numpy as np

def printf(format, *values):
    print(format % values )

with open("in.pdf", "rb") as in_f:
    input1 = PdfFileReader(in_f)
    output = PdfFileWriter()

    numPages = input1.getNumPages()

    # The label indices occur @ even locations - generate array of form [0, 2, 4, 6, ...]
    indices = np.array(np.arange(0,np.shape(input1.trailer["/Root"]["/PageLabels"]["/Nums"])[0],2))

    # Assume end of preceding label = start of next label - 1
    pageIndices = np.array(input1.trailer["/Root"]["/PageLabels"]["/Nums"])[indices] - 1 

    # ignore the first index which is now a -1
    pageIndices = pageIndices[1:] 

    # there may be extra pages right after the start of the last label - add them
    pageIndices = np.append(pageIndices, np.arange(pageIndices[-1]+1, numPages))


    for _, v in enumerate(pageIndices):
        page = input1.getPage(v)
        output.addPage(page)

    with open("out.pdf", "wb") as out_f:
        output.write(out_f)
  • 1
    @dessert Added comments to the code! – nickT May 3 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.