Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Python script that splits a pdf into 2MB parts, so that you can send it to the DHBW printers, use like this: python python dhbwprinthelper.py test.pdf
  3. # Requirements: python and pypdf2
  4.  
  5. import os, io, copy, sys
  6. from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger
  7.  
  8. if len(sys.argv) < 2:
  9. print("Please tell me which file I should look at, like this: python dhbwprinthelper.py test.pdf")
  10. exit()
  11.  
  12. fileName = sys.argv[1]
  13.  
  14. if not fileName.endswith('.pdf'):
  15. print("Sorry, I only support pdf files")
  16. exit()
  17.  
  18. if not os.path.isfile(sys.argv[1]):
  19. print("Sorry, but I don't think that file exists")
  20. exit()
  21.  
  22. maxSize = 2000000 # You can only send files that are < 2Mb with the DHBW mail
  23. filesCounter = 1 # Used to count up file names
  24. fileSize = os.stat(fileName).st_size # Get the original file size
  25.  
  26. print ("Total filesize in bytes", fileSize)
  27. if fileSize > maxSize:
  28. print("PDF can not be sent by the DHBW mailserver, I'm sorry. I will try to fix that tho...")
  29. else:
  30. print("Your PDF seems to be printable as is")
  31. exit()
  32.  
  33.  
  34. pdf = PdfFileReader(fileName) # read the pdf
  35. pagesCount = pdf.getNumPages() # get the total page number count
  36.  
  37. print ("The pdf has %i pages" % pagesCount)
  38.  
  39. currentDocument = PdfFileWriter() # create an empty pdf
  40.  
  41. for counter in range(pagesCount):
  42. tempDocument = copy.deepcopy(currentDocument) # save current pdf
  43.  
  44. page = pdf.getPage(counter)
  45. currentDocument.addPage(page) # add page to current pdf
  46.  
  47. # write pdf to stream and check if size > maxSize
  48. currentFile = io.BytesIO()
  49. currentDocument.write(currentFile)
  50. if currentFile.tell() >= maxSize:
  51. outputFilename = "printhelper-page-{}.pdf".format(filesCounter)
  52. filesCounter += 1
  53.  
  54. with open(outputFilename, "wb") as out:
  55. tempDocument.write(out) # write pdf without last page
  56. out.close()
  57. currentDocument = PdfFileWriter()
  58. currentDocument.addPage(page) # add last page to new, empty pdf
  59.  
  60. # write remaining pages to file
  61. outputFilename = "printhelper-page-{}.pdf".format(filesCounter)
  62. with open(outputFilename, "wb") as out:
  63. currentDocument.write(out)
  64. out.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement