test_basic_features.py 1.9 KB

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