Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # 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
- # Requirements: python and pypdf2
- import os, io, copy, sys
- from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger
- if len(sys.argv) < 2:
- print("Please tell me which file I should look at, like this: python dhbwprinthelper.py test.pdf")
- exit()
- fileName = sys.argv[1]
- if not fileName.endswith('.pdf'):
- print("Sorry, I only support pdf files")
- exit()
- if not os.path.isfile(sys.argv[1]):
- print("Sorry, but I don't think that file exists")
- exit()
- maxSize = 2000000 # You can only send files that are < 2Mb with the DHBW mail
- filesCounter = 1 # Used to count up file names
- fileSize = os.stat(fileName).st_size # Get the original file size
- print ("Total filesize in bytes", fileSize)
- if fileSize > maxSize:
- print("PDF can not be sent by the DHBW mailserver, I'm sorry. I will try to fix that tho...")
- else:
- print("Your PDF seems to be printable as is")
- exit()
- pdf = PdfFileReader(fileName) # read the pdf
- pagesCount = pdf.getNumPages() # get the total page number count
- print ("The pdf has %i pages" % pagesCount)
- currentDocument = PdfFileWriter() # create an empty pdf
- for counter in range(pagesCount):
- tempDocument = copy.deepcopy(currentDocument) # save current pdf
- page = pdf.getPage(counter)
- currentDocument.addPage(page) # add page to current pdf
- # write pdf to stream and check if size > maxSize
- currentFile = io.BytesIO()
- currentDocument.write(currentFile)
- if currentFile.tell() >= maxSize:
- outputFilename = "printhelper-page-{}.pdf".format(filesCounter)
- filesCounter += 1
- with open(outputFilename, "wb") as out:
- tempDocument.write(out) # write pdf without last page
- out.close()
- currentDocument = PdfFileWriter()
- currentDocument.addPage(page) # add last page to new, empty pdf
- # write remaining pages to file
- outputFilename = "printhelper-page-{}.pdf".format(filesCounter)
- with open(outputFilename, "wb") as out:
- currentDocument.write(out)
- out.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement