Wie kann man PDF mit Python richtig erstellen?
Posted: 16 May 2025, 18:36
Hier gibt es ein paar ähnliche Posts, aber sie behandeln mein Problem nicht.
This works fine for text:
original:

cropped:
Anscheinend anscheinend für Musiksymbole, die dies nicht richtig zu funktionieren scheint. src = "https://i.sstatic.net/jp6czns2.png"/>
Krupte:
Code: Select all
### crop a PDF to visible objects
import fitz # PyMuPDF
def crop_pdf_to_visible_content(input_pdf, output_pdf):
# Open the input PDF
doc = fitz.open(input_pdf)
for page in doc:
# Get the text blocks to determine the visible content
text_blocks = page.get_text("dict")["blocks"]
if text_blocks:
# Initialize variables to store the minimum and maximum coordinates
min_x = float('inf')
min_y = float('inf')
max_x = 0
max_y = 0
for block in text_blocks:
if "bbox" in block:
x0, y0, x1, y1 = block["bbox"]
min_x = min(min_x, x0)
min_y = min(min_y, y0)
max_x = max(max_x, x1)
max_y = max(max_y, y1)
# Set the cropbox to the bounding box of the visible content
rect = fitz.Rect(min_x, min_y, max_x, max_y)
page.set_cropbox(rect)
# Save the output PDF
doc.save(output_pdf)
doc.close()
input_pdf = "Test.pdf"
output_pdf = input_pdf[:-4] + "_crop.pdf"
crop_pdf_to_visible_content(input_pdf, output_pdf)
### end of script
original:

cropped:
Anscheinend anscheinend für Musiksymbole, die dies nicht richtig zu funktionieren scheint. src = "https://i.sstatic.net/jp6czns2.png"/>
Krupte: