Last active
January 29, 2018 11:21
-
-
Save quickgrid/d2c120a857a7c36acd016cd7ced71097 to your computer and use it in GitHub Desktop.
PyPDF2 pdf manipulating and writing example beginner working sample.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a PyPDF2 example found in sample_code directory. | |
# I removed some parts which may cause problems for beginners. | |
# Also fixed code to work with python 3+. | |
from PyPDF2 import PdfFileWriter, PdfFileReader | |
output = PdfFileWriter() | |
input1 = PdfFileReader(open("sample.pdf", "rb")) | |
# print how many pages input1 has: | |
print("document1.pdf has %d pages." % input1.getNumPages()) | |
# add page 1 from input1 to output document, unchanged | |
output.addPage(input1.getPage(0)) | |
# add page 2 from input1, but rotated clockwise 90 degrees | |
output.addPage(input1.getPage(1).rotateClockwise(90)) | |
# add page 3 from input1, rotated the other way: | |
output.addPage(input1.getPage(2).rotateCounterClockwise(90)) | |
# alt: output.addPage(input1.getPage(2).rotateClockwise(270)) | |
# add page 5 from input1, but crop it to half size: | |
page5 = input1.getPage(4) | |
page5.mediaBox.upperRight = ( | |
page5.mediaBox.getUpperRight_x() / 2, | |
page5.mediaBox.getUpperRight_y() / 2 | |
) | |
output.addPage(page5) | |
# finally, write "output" to document-output.pdf | |
outputStream = open("PyPDF2-output.pdf", "wb") | |
output.write(outputStream) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks quickgrid for wonderful explanation. Only thing that got missed at the end is :
outputStream.close()