Saturday, May 13, 2017
PyPDF2 PDF Manipulating and Writing Fixed Beginner Working Example
May 13, 2017
beginner example
,
PyPDF2
,
python pdf library
First Install PyPDF2 with pip from cmd,
pip install PyPDF2
pip install PyPDF2
Code:
This file contains 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) |
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment