Saturday, August 27, 2016

Today we (my family and I) will fly back home. I wanted a paper copy of our boarding passes, but without the lower part which contains only publicity. I installed PyPDF2 and wrote the following script:

from __future__ import print_function

from PyPDF2 import PdfFileWriter, PdfFileReader
from argh import dispatch_command, arg, CommandError

     help="The pdf files to crop.")
@arg('--bottom', default=None, 
     help='Height of bottom area to crop. Default is half of page.')
def main(bottom=None, *filenames):
    output = PdfFileWriter()
    for filename in filenames:
        pdfin = PdfFileReader(open(filename, "rb"))

        # print how many pages pdfin has:
        print("{} has {} pages.".format(filename, pdfin.getNumPages()))
        for p in pdfin.pages:
            mb = p.mediaBox
            # print(mb)
            b = bottom or (mb.getUpperRight_y() / 2)
            # p.mediaBox.upperRight = (
            mb.lowerRight = (mb.getLowerRight_x(), b)
            mb.lowerLeft = (mb.getLowerLeft_x(), b)
    output.write(file("output.pdf", "wb"))

The script produced appearently what I want, but in the printout the cropped area then showed up again. IOW it needs more work, but I won’t do this now since I have my paper copies for this time.