Created
July 1, 2021 22:06
-
-
Save mosolovsa/0dc5dbfab39c76c6c010f1e10165fac6 to your computer and use it in GitHub Desktop.
manual duplex printing chunk generate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
from PyPDF2 import PdfFileReader, PdfFileWriter | |
# chunk_size, path = sys.argv[1], sys.argv[2] | |
chunk_size, path = 50, '/home/serg/print/auto/fluent.pdf' # '/home/serg/Documents/sicp.pdf' | |
pdf = PdfFileReader(str(path)) | |
cnt = pdf.getNumPages() | |
ranges = [range(i, i+chunk_size) for i in range(0, cnt, chunk_size)] | |
print(ranges) | |
if cnt % chunk_size != 0: | |
ranges[-1] = range(ranges[-1].start, ranges[-1].start + cnt % chunk_size) | |
print(ranges) | |
remove_last_page_warning = False | |
chunked = [] | |
for chunk in ranges: | |
chunked.append(range(chunk.start, chunk.stop, 2)) | |
chunked.append(range(chunk.stop-1, chunk.start, -2)) | |
if cnt % chunk_size % 2: | |
remove_last_page_warning = True | |
chunked[-1] = range(chunked[-1].start-1, chunked[-1].stop, chunked[-1].step) | |
print(chunked) | |
path_dir, filename = os.path.dirname(path), os.path.basename(path)[:-4] | |
print(path_dir, filename) | |
for i, chunk in enumerate(chunked): | |
if i == len(chunked) - 1 and remove_last_page_warning: | |
saved_chunk = f'{i}-REMOVE-LAST-PAGE-{filename}-{chunk.start}-{chunk.stop}.pdf' | |
else: | |
saved_chunk = f'{i}-{filename}-{chunk.start}-{chunk.stop}.pdf' | |
pdf_writer = PdfFileWriter() | |
with open(os.path.join(path_dir, 'dumped'+filename, saved_chunk), 'wb') as output_file: | |
# with Path().open(mode="w") as output_file: | |
for p in chunk: | |
pdf_writer.addPage(pdf.getPage(p)) | |
pdf_writer.write(output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment