如何用脚本批量裁剪PDF页面?

wen 实用脚本 2

本文目录导读:

如何用脚本批量裁剪PDF页面?

  1. 使用 Python + PyMuPDF (推荐)
  2. 使用命令行工具 pdfcrop
  3. 使用 Ghostscript (跨平台)
  4. 更灵活的 Python 版本 (支持不同页面不同裁剪)
  5. 安装依赖
  6. 使用建议

可以使用多种脚本方法批量裁剪PDF页面,以下是几种常用的解决方案:

使用 Python + PyMuPDF (推荐)

import fitz  # PyMuPDF
import os
from pathlib import Path
def crop_pdf_pages(input_pdf, output_pdf, crop_box):
    """
    裁剪PDF页面
    crop_box: (left, top, right, bottom) 矩形裁剪区域
    """
    doc = fitz.open(input_pdf)
    new_doc = fitz.open()
    for page_num in range(len(doc)):
        page = doc[page_num]
        # 获取当前页面尺寸
        rect = page.rect
        # 计算裁剪区域(相对于页面)
        clip_rect = fitz.Rect(
            crop_box[0],
            crop_box[1],
            rect.width - crop_box[2],
            rect.height - crop_box[3]
        )
        # 复制页面并裁剪
        new_page = new_doc.new_page(width=clip_rect.width, height=clip_rect.height)
        new_page.show_pdf_page(new_page.rect, doc, page_num, clip=clip_rect)
    new_doc.save(output_pdf)
    new_doc.close()
    doc.close()
def batch_crop_pdfs(input_folder, output_folder, crop_box):
    """批量处理文件夹中的所有PDF"""
    input_path = Path(input_folder)
    output_path = Path(output_folder)
    output_path.mkdir(parents=True, exist_ok=True)
    for pdf_file in input_path.glob("*.pdf"):
        input_file = str(pdf_file)
        output_file = str(output_path / pdf_file.name)
        crop_pdf_pages(input_file, output_file, crop_box)
        print(f"已处理: {pdf_file.name}")
# 使用示例
if __name__ == "__main__":
    # 定义裁剪区域(左、上、右、下)单位:点(1英寸=72点)
    crop_box = (50, 50, 50, 50)  # 四周各裁剪50点
    batch_crop_pdfs(
        input_folder="./input_pdfs",
        output_folder="./output_pdfs",
        crop_box=crop_box
    )

使用命令行工具 pdfcrop

Linux/Mac 环境:

#!/bin/bash
# batch_crop_pdfs.sh
INPUT_DIR="./input"
OUTPUT_DIR="./output"
MARGINS="10"  # 裁剪边距(单位:点)
mkdir -p "$OUTPUT_DIR"
for pdf in "$INPUT_DIR"/*.pdf; do
    filename=$(basename "$pdf")
    echo "处理: $filename"
    pdfcrop --margins "$MARGINS" "$pdf" "$OUTPUT_DIR/$filename"
done
echo "批量裁剪完成!"

Windows (PowerShell):

# batch_crop_pdfs.ps1
$inputDir = ".\input"
$outputDir = ".\output"
$margins = "10"
# 创建输出目录
New-Item -ItemType Directory -Force -Path $outputDir
Get-ChildItem -Path $inputDir -Filter "*.pdf" | ForEach-Object {
    $inputFile = $_.FullName
    $outputFile = Join-Path -Path $outputDir -ChildPath $_.Name
    Write-Host "处理: $($_.Name)"
    # 调用 pdfcrop
    & pdfcrop --margins $margins $inputFile $outputFile
}
Write-Host "批量裁剪完成!"

使用 Ghostscript (跨平台)

#!/bin/bash
# gs_crop_pdfs.sh
INPUT_DIR="./input"
OUTPUT_DIR="./output"
# Ghostscript裁剪参数
CROP_BOX="50 50 550 750"  # 左 下 右 上(单位:点)
mkdir -p "$OUTPUT_DIR"
for pdf in "$INPUT_DIR"/*.pdf; do
    filename=$(basename "$pdf")
    echo "处理: $filename"
    gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite \
       -dUseCropBox=true \
       -c "[/CropBox [$CROP_BOX] /PAGES pdfmark" \
       -sOutputFile="$OUTPUT_DIR/$filename" \
       -f "$pdf"
done
echo "批量裁剪完成!"

更灵活的 Python 版本 (支持不同页面不同裁剪)

import fitz
from pathlib import Path
import json
def smart_crop_pdf(input_pdf, output_pdf, crop_config):
    """
    智能裁剪PDF
    crop_config 可以是:
    - 元组: 所有页面使用相同的裁剪 (left, top, right, bottom)
    - 字典: 按页面范围裁剪 {range: (left, top, right, bottom)}
    """
    doc = fitz.open(input_pdf)
    new_doc = fitz.open()
    for page_num in range(len(doc)):
        page = doc[page_num]
        rect = page.rect
        # 确定该页的裁剪参数
        if isinstance(crop_config, tuple):
            crop = crop_config
        elif isinstance(crop_config, dict):
            crop = get_crop_for_page(crop_config, page_num)
        else:
            raise ValueError("无效的裁剪配置")
        # 计算裁剪区域
        clip_rect = fitz.Rect(
            crop[0],
            crop[1],
            rect.width - crop[2],
            rect.height - crop[3]
        )
        # 创建新页面并复制内容
        new_page = new_doc.new_page(width=clip_rect.width, height=clip_rect.height)
        new_page.show_pdf_page(new_page.rect, doc, page_num, clip=clip_rect)
    new_doc.save(output_pdf)
    new_doc.close()
    doc.close()
def get_crop_for_page(config, page_num):
    """根据页面范围获取裁剪参数"""
    for page_range, crop_values in config.items():
        if '-' in page_range:
            start, end = map(int, page_range.split('-'))
            if start <= page_num + 1 <= end:
                return crop_values
        elif page_range == str(page_num + 1):
            return crop_values
    # 默认裁剪
    return config.get('default', (0, 0, 0, 0))
# 使用示例
if __name__ == "__main__":
    # 配置所有页面裁剪
    crop_all = (50, 50, 50, 50)  # 四周各50点
    # 或者按页面范围配置
    crop_by_range = {
        "1-5": (30, 30, 30, 30),  # 第1-5页裁剪30点
        "6-10": (50, 50, 50, 50), # 第6-10页裁剪50点
        "default": (10, 10, 10, 10) # 其他页面裁剪10点
    }
    # 批量处理
    input_dir = Path("./input")
    output_dir = Path("./output")
    output_dir.mkdir(exist_ok=True)
    for pdf_file in input_dir.glob("*.pdf"):
        smart_crop_pdf(
            str(pdf_file),
            str(output_dir / pdf_file.name),
            crop_all  # 或 crop_by_range
        )
        print(f"已完成: {pdf_file.name}")

安装依赖

Python 环境:

pip install PyMuPDF

pdfcrop (通常已包含在 TeX Live 中):

  • Linux: sudo apt-get install texlive-extra-utils
  • Mac: brew install texlive
  • Windows: 安装 MiKTeX 或 TeX Live

Ghostscript:

  • Linux: sudo apt-get install ghostscript
  • Mac: brew install ghostscript
  • Windows: 从官网下载安装

使用建议

  1. 测试先行:先处理单个PDF文件测试裁剪效果
  2. 备份原文件:始终保留原始PDF文件
  3. 单位说明:PDF单位是"点"(point),1英寸=72点,1毫米≈2.83点
  4. 批量处理:建议使用Python脚本,灵活性更好

选择哪种方法取决于你的具体需求和操作系统环境,Python方案最为灵活,支持复杂的裁剪逻辑。

抱歉,评论功能暂时关闭!