Wednesday 12 October 2016

Modify a PDF file using Python code.

If we generated a pdf file with mistakes and we want to rectify them we can use this code.

Example-1:

Lets consider a pdf file : document1.pdf
and it has 6 pages in it.
Let the mistake we done be the order of paging i.e, 2nd and 4th page should be interchanged.
In this case we can use the python code to make modifications to our pdf file and we can generate a correct pdf file.

Solution:

from PyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input1 = PdfFileReader(open("document1.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 4 from input1 to output document, unchanged
output.addPage(input1.getPage(3))

# add page 3 from input1 to output document, unchanged
output.addPage(input1.getPage(2))

# add page 2 from input1 to output document, unchanged
output.addPage(input1.getPage(1))

# add page 5 from input1 to output document, unchanged
output.addPage(input1.getPage(4))

# add page 6 from input1 to output document, unchanged
output.addPage(input1.getPage(5))

# finally, write "output" to document-output.pdf
outputStream = file("PyPDF2-output.pdf", "wb")
output.write(outputStream)

# Dont forget to close the output pdf file.
outputStream.close()

# Finally the modified pdf file will be stored in the current working directory.

Note:

For more examples keep checking this blog.

No comments:

Post a Comment