[Python] How to correctly crop PDF with Python?

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    There are a few similar post here on SO, but they do not cover my issue. I am using the following script to crop a PDF to its visible content.

    ### 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


    This works fine for text:

    original:

    [​IMG]

    cropped:

    [​IMG]

    However, apparently, for music symbols this doesn't seem to work correctly.

    original:

    [​IMG]

    cropped:

    [​IMG]

    My suspicion is that the shapes close to the borders might be described as curves with control points and the file might be cropped at the control points, but not including the full shape. I cannot tell in advance how much space is needed, so, to add an additional fixed "safety" margin would not help and other files would then get a too wide margin.

    Any ideas how to work around this?

    Continue reading...

Compartilhe esta Página