-
-
Save pwqw/5d7eee466ec38138c5e315b807bd7a16 to your computer and use it in GitHub Desktop.
Tomar un PDF vertical e imprimirlo para encuadernar
This file contains 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
#!/usr/bin/env python3 | |
import io | |
import math | |
import sys | |
import PyPDF2 | |
def main(src, dst, pliegues=6): | |
pliegues = int(pliegues) | |
src_f = open(src, 'r+b') | |
dst_f = open(dst, 'w+b') | |
input_crudo = PyPDF2.PdfFileReader(src_f) | |
output = PyPDF2.PdfFileWriter() | |
total_pages_crudo = input_crudo.getNumPages() | |
total_pages_blancas = 4 - (total_pages_crudo % 4) | |
print('Documento original, de', total_pages_crudo, 'páginas') | |
print('Páginas blancas a agregar', total_pages_blancas) | |
if total_pages_blancas == 0: | |
input = input_crudo | |
else: | |
writer = PyPDF2.PdfFileWriter() | |
writer.appendPagesFromReader(input_crudo) | |
page = PyPDF2._page.PageObject.createBlankPage(writer) | |
for i in range(total_pages_blancas): | |
writer.addPage(page) | |
inmemoryfile = io.BytesIO() | |
writer.write(inmemoryfile) | |
input = PyPDF2.PdfFileReader(inmemoryfile) | |
total_pages = input.getNumPages() | |
cant_ramillete = math.ceil(total_pages / (pliegues*4)) | |
print('Cantidad total de páginas', total_pages, 'y son', total_pages // 4 ,'hojas\n') | |
print('Cada "ramillete" lleva', pliegues, 'hojas plegadas') | |
print('Cantidad de "ramilletes"', cant_ramillete) | |
for ramillete in range(cant_ramillete): | |
if ramillete == cant_ramillete-1: | |
num_pages = total_pages % (pliegues*4) | |
else: | |
num_pages = pliegues * 4 | |
for i in range(num_pages // 2): | |
pag_offset = (ramillete * pliegues * 4) | |
pag = pag_offset + i | |
tope_pliegue = pag_offset + num_pages | |
if pag % 2 == 0: | |
primera = input.getPage(tope_pliegue-i-1) | |
segunda = input.getPage(pag) | |
else: | |
primera = input.getPage(pag) | |
segunda = input.getPage(tope_pliegue-i-1) | |
# dimensions for offset from loaded page (adding it to the right) | |
offset_x = primera.mediaBox[2] | |
offset_y = 0 | |
# add second page to first one | |
primera.mergeTranslatedPage(segunda, offset_x, offset_y, expand=True) | |
output.addPage(primera) | |
output.write(dst_f) | |
src_f.close() | |
dst_f.close() | |
if __name__ == '__main__': | |
main(*sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instalación
Uso
Ejemplo de uso