basic_features.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from PyPDF2 import PdfFileWriter, PdfFileReader
  2. output = PdfFileWriter()
  3. input1 = PdfFileReader(open("document1.pdf", "rb"))
  4. # print how many pages input1 has:
  5. print("document1.pdf has %d pages." % input1.getNumPages())
  6. # print how many pages input1 has in python3:
  7. # print("This chart has {} pages.".format(input1.getNumPages()))
  8. # add page 1 from input1 to output document, unchanged:
  9. output.addPage(input1.getPage(0))
  10. # add page 2 from input1, but rotated clockwise 90 degrees:
  11. output.addPage(input1.getPage(1).rotateClockwise(90))
  12. # add page 3 from input1, rotated the other way:
  13. output.addPage(input1.getPage(2).rotateCounterClockwise(90))
  14. # alt: output.addPage(input1.getPage(2).rotateClockwise(270))
  15. # add page 4 from input1, but first add a watermark from another PDF:
  16. page4 = input1.getPage(3)
  17. watermark = PdfFileReader(open("watermark.pdf", "rb"))
  18. page4.mergePage(watermark.getPage(0))
  19. output.addPage(page4)
  20. # add page 5 from input1, but crop it to half size:
  21. page5 = input1.getPage(4)
  22. page5.mediaBox.upperRight = (
  23. page5.mediaBox.getUpperRight_x() / 2,
  24. page5.mediaBox.getUpperRight_y() / 2
  25. )
  26. output.addPage(page5)
  27. # add some Javascript to launch the print window on opening this PDF.
  28. # the password dialog may prevent the print dialog from being shown,
  29. # comment the the encription lines, if that's the case, to try this out:
  30. output.addJS("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
  31. # encrypt your new PDF and add a password:
  32. password = "secret"
  33. output.encrypt(password)
  34. # add a title to your new PDF's metadata:
  35. output.addMetadata({'/Title': 'PDF Metadata Title'})
  36. # finally, write "output" to document-output.pdf
  37. with open("PyPDF2-output.pdf", "wb") as outputStream:
  38. output.write(outputStream)