Created
June 15, 2023 13:11
-
-
Save PARC6502/eb792704874dbc55d9114d1d666e7d20 to your computer and use it in GitHub Desktop.
Cuts cards out of a pdf page
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
from PyPDF2 import PdfWriter, PdfReader | |
from pdf2image import convert_from_bytes | |
from copy import deepcopy | |
import io | |
num = 1 | |
reader = PdfReader("cards_no-borders.pdf") | |
for iter_page in reader.pages: | |
for x in range(3): | |
for y in range(3): | |
writer = PdfWriter() | |
page = deepcopy(iter_page) | |
height = float(page.mediabox.height) | |
width = float(page.mediabox.width) | |
page.mediabox.upper_left = ( | |
float(page.mediabox.left) + x*width/3, | |
float(page.mediabox.top) - y*height/3 | |
) | |
page.mediabox.upper_right = ( | |
float(page.mediabox.left) + (width/3), | |
page.mediabox.top | |
) | |
page.mediabox.lower_right = ( | |
page.mediabox.right, | |
float(page.mediabox.bottom) + ((2-y)*(height/3)) | |
) | |
writer.add_page(page) | |
pdf_bytes = io.BytesIO() | |
writer.write(pdf_bytes) | |
pdf_bytes.seek(0) | |
images = convert_from_bytes(pdf_bytes.read()) | |
filename = "cards/card%d.png"%num | |
images[0].save(filename, 'PNG') | |
pdf_bytes.flush() | |
num+=1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment