2013-08-01

Add password to a PDF with PyPDF

PyPDF is a pure python module to manipulate PDF.

Examples:

# add password to a pdf
# add_password.py input.pdf password output.pdf


import sys
from pyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input = PdfFileReader(file(sys.argv[1], "rb"))
for i in range(0, input.getNumPages()):
    output.addPage(input.getPage(i))
outputStream = file(sys.argv[3], "wb")
output.encrypt(sys.argv[2], use_128bit=True)
output.write(outputStream)
outputStream.close()


# extract pages from a pdf
# extract_page.py input.pdf start_page end_page out.pdf
# page starts from 1


import sys
from pyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input = PdfFileReader(file(sys.argv[1], "rb"))
for i in range(int(sys.argv[2]), int(sys.argv[3])+1):
    output.addPage(input.getPage(i-1))
outputStream = file(sys.argv[4], "wb")
output.write(outputStream)
outputStream.close()


# rotate all pages clockwise
# rotate.py input.pdf degrees output.pdf

# degrees must be multiple of 90 

import sys
from pyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input = PdfFileReader(file(sys.argv[1], "rb"))
for i in range(0, input.getNumPages()):
    output.addPage(input.getPage(i).rotateClockwise(int(sys.argv[2])))
outputStream = file(sys.argv[3], "wb")
output.write(outputStream)
outputStream.close()