如何用实用脚本自动合并PDF文件?

wen 实用脚本 5

本文目录导读:

如何用实用脚本自动合并PDF文件?

  1. Python脚本(跨平台,推荐)
  2. Windows PowerShell脚本
  3. Linux/Unix Bash脚本
  4. macOS AppleScript
  5. 使用说明
  6. 安装依赖

我为您提供几种实用的PDF合并脚本方案,覆盖不同操作系统和使用场景。

Python脚本(跨平台,推荐)

安装依赖

pip install PyPDF2
# 或
pip install pypdf

基础合并脚本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF合并工具 - 自动合并指定目录下的所有PDF文件
"""
import os
import sys
from PyPDF2 import PdfMerger
def merge_pdfs(input_dir, output_file="merged.pdf", sort=True):
    """
    合并指定目录下的所有PDF文件
    Args:
        input_dir: PDF文件所在目录
        output_file: 输出文件名
        sort: 是否按文件名排序
    """
    # 获取所有PDF文件
    pdf_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.pdf')]
    if not pdf_files:
        print("错误: 未找到PDF文件!")
        return False
    if sort:
        pdf_files.sort()
    print(f"找到 {len(pdf_files)} 个PDF文件:")
    for f in pdf_files:
        print(f"  - {f}")
    # 合并文件
    merger = PdfMerger()
    try:
        for pdf in pdf_files:
            filepath = os.path.join(input_dir, pdf)
            merger.append(filepath)
            print(f"已添加: {pdf}")
        # 保存合并后的文件
        output_path = os.path.join(input_dir, output_file)
        merger.write(output_path)
        merger.close()
        print(f"\n合并完成! 输出文件: {output_path}")
        print(f"总页数: 请手动查看或使用其他工具")
        return True
    except Exception as e:
        print(f"合并过程中出错: {e}")
        return False
if __name__ == "__main__":
    # 使用当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 支持命令行参数
    input_path = sys.argv[1] if len(sys.argv) > 1 else current_dir
    output_name = sys.argv[2] if len(sys.argv) > 2 else "merged.pdf"
    merge_pdfs(input_path, output_name)

高级版本(带GUI选择界面)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PDF合并工具 - 带文件选择功能
"""
import tkinter as tk
from tkinter import filedialog, messagebox
import os
from PyPDF2 import PdfMerger
class PDFMergerGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("PDF合并工具")
        self.root.geometry("500x400")
        self.pdf_files = []
        # 创建界面
        self.create_widgets()
    def create_widgets(self):
        # 选择文件按钮
        tk.Button(self.root, text="选择PDF文件", 
                 command=self.select_files, width=20).pack(pady=10)
        # 文件列表
        self.listbox = tk.Listbox(self.root, height=10, width=60)
        self.listbox.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
        # 操作按钮
        frame = tk.Frame(self.root)
        frame.pack(pady=10)
        tk.Button(frame, text="上移", command=self.move_up, width=10).pack(side=tk.LEFT, padx=5)
        tk.Button(frame, text="下移", command=self.move_down, width=10).pack(side=tk.LEFT, padx=5)
        tk.Button(frame, text="移除", command=self.remove_file, width=10).pack(side=tk.LEFT, padx=5)
        # 合并按钮
        tk.Button(self.root, text="合并PDF", command=self.merge_files, 
                 bg="green", fg="white", width=20).pack(pady=10)
    def select_files(self):
        files = filedialog.askopenfilenames(
            title="选择PDF文件",
            filetypes=[("PDF文件", "*.pdf")]
        )
        for file in files:
            if file not in self.pdf_files:
                self.pdf_files.append(file)
                self.listbox.insert(tk.END, os.path.basename(file))
    def move_up(self):
        selection = self.listbox.curselection()
        if selection and selection[0] > 0:
            index = selection[0]
            self._swap_items(index, index-1)
    def move_down(self):
        selection = self.listbox.curselection()
        if selection and selection[0] < self.listbox.size() - 1:
            index = selection[0]
            self._swap_items(index, index+1)
    def _swap_items(self, i, j):
        self.pdf_files[i], self.pdf_files[j] = self.pdf_files[j], self.pdf_files[i]
        self.listbox.delete(i)
        self.listbox.delete(j)
        self.listbox.insert(j, os.path.basename(self.pdf_files[j]))
        self.listbox.insert(i, os.path.basename(self.pdf_files[i]))
        self.listbox.selection_set(j)
    def remove_file(self):
        selection = self.listbox.curselection()
        if selection:
            index = selection[0]
            self.listbox.delete(index)
            self.pdf_files.pop(index)
    def merge_files(self):
        if not self.pdf_files:
            messagebox.showwarning("警告", "请先选择PDF文件!")
            return
        output_file = filedialog.asksaveasfilename(
            defaultextension=".pdf",
            filetypes=[("PDF文件", "*.pdf")],
            title="保存合并后的PDF"
        )
        if not output_file:
            return
        merger = PdfMerger()
        try:
            for pdf in self.pdf_files:
                merger.append(pdf)
            merger.write(output_file)
            merger.close()
            messagebox.showinfo("完成", f"合并成功!\n输出文件: {output_file}")
        except Exception as e:
            messagebox.showerror("错误", f"合并失败: {e}")
if __name__ == "__main__":
    root = tk.Tk()
    app = PDFMergerGUI(root)
    root.mainloop()

Windows PowerShell脚本

# merge_pdfs.ps1
# Windows系统使用
# 安装模块(首次运行需要)
# Install-Module -Name PSWritePDF -Force
param(
    [string]$InputPath = ".",
    [string]$OutputFile = "merged.pdf"
)
function Merge-PDFs {
    param(
        [string]$inputPath,
        [string]$outputFile
    )
    # 获取所有PDF文件
    $pdfFiles = Get-ChildItem -Path $inputPath -Filter *.pdf | Sort-Object Name
    if ($pdfFiles.Count -eq 0) {
        Write-Host "错误: 未找到PDF文件!" -ForegroundColor Red
        return
    }
    Write-Host "找到 $($pdfFiles.Count) 个PDF文件:" -ForegroundColor Green
    $pdfFiles | ForEach-Object { Write-Host "  - $($_.Name)" }
    # 使用PDFtk工具合并(需要先安装)
    $pdftkPath = "C:\Program Files\PDFtk\bin\pdftk.exe"
    if (Test-Path $pdftkPath) {
        # 方法1: 使用PDFtk
        $inputFiles = $pdfFiles.FullName -join " "
        $outputPath = Join-Path $inputPath $outputFile
        & $pdftkPath $inputFiles cat output $outputPath
        if ($LASTEXITCODE -eq 0) {
            Write-Host "合并完成! 输出文件: $outputPath" -ForegroundColor Green
        } else {
            Write-Host "合并失败!" -ForegroundColor Red
        }
    } else {
        # 方法2: 使用PowerShell脚本(仅适用于文本PDF)
        Write-Host "PDFtk未安装,尝试使用PowerShell方法..." -ForegroundColor Yellow
        Write-Host "建议安装PDFtk: https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/" -ForegroundColor Yellow
    }
}
Merge-PDFs -inputPath $InputPath -outputFile $OutputFile

Linux/Unix Bash脚本

#!/bin/bash
# merge_pdfs.sh
# Linux/Unix系统使用
# 检查依赖
check_dependencies() {
    if command -v pdfunite &> /dev/null; then
        MERGE_TOOL="pdfunite"
    elif command -v pdftk &> /dev/null; then
        MERGE_TOOL="pdftk"
    elif command -v ghostscript &> /dev/null; then
        MERGE_TOOL="ghostscript"
    else
        echo "错误: 未找到PDF合并工具!"
        echo "请安装以下任一工具:"
        echo "  - poppler-utils (提供pdfunite)"
        echo "  - pdftk"
        echo "  - ghostscript"
        exit 1
    fi
}
# 主函数
merge_pdfs() {
    local input_dir="${1:-.}"
    local output_file="${2:-merged.pdf}"
    local output_path="$input_dir/$output_file"
    # 获取PDF文件列表
    local pdf_files=($(ls "$input_dir"/*.pdf 2>/dev/null | sort))
    if [ ${#pdf_files[@]} -eq 0 ]; then
        echo "错误: 未找到PDF文件!"
        exit 1
    fi
    echo "找到 ${#pdf_files[@]} 个PDF文件:"
    for f in "${pdf_files[@]}"; do
        echo "  - $(basename "$f")"
    done
    case $MERGE_TOOL in
        pdfunite)
            echo "使用 pdfunite 合并..."
            pdfunite "${pdf_files[@]}" "$output_path"
            ;;
        pdftk)
            echo "使用 pdftk 合并..."
            pdftk "${pdf_files[@]}" cat output "$output_path"
            ;;
        ghostscript)
            echo "使用 ghostscript 合并..."
            gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite \
               -sOutputFile="$output_path" \
               "${pdf_files[@]}"
            ;;
    esac
    if [ $? -eq 0 ]; then
        echo "合并完成! 输出文件: $output_path"
    else
        echo "合并失败!"
        exit 1
    fi
}
# 检查依赖
check_dependencies
# 处理命令行参数
INPUT_DIR="${1:-.}"
OUTPUT_FILE="${2:-merged.pdf}"
merge_pdfs "$INPUT_DIR" "$OUTPUT_FILE"

macOS AppleScript

-- merge_pdfs.applescript
-- macOS系统使用
on merge_pdfs()
    -- 选择PDF文件
    set pdfFiles to choose file with prompt "选择要合并的PDF文件" of type {"pdf"} with multiple selections allowed
    if pdfFiles is {} then return
    -- 选择保存位置
    set outputFile to choose file name with prompt "保存合并后的PDF" default name "merged.pdf"
    -- 使用Automator或AppleScript合并PDF
    set filePaths to ""
    repeat with pdfFile in pdfFiles
        set filePaths to filePaths & " " & quoted form of POSIX path of pdfFile
    end repeat
    -- 使用系统自带的合并功能
    do shell script "/System/Library/Automator/Combine PDF Pages.action/Contents/MacOS/Combine PDF Pages " & filePaths & " " & quoted form of POSIX path of outputFile
    display dialog "合并完成!" buttons {"确定"} default button 1
end merge_pdfs
-- 运行
merge_pdfs()

使用说明

Python脚本使用

# 基础用法(合并当前目录)
python merge_pdfs.py
# 指定目录
python merge_pdfs.py /path/to/pdf/files
# 指定输出文件名
python merge_pdfs.py . output.pdf

Windows PowerShell使用

# 运行脚本(允许执行策略)
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.\merge_pdfs.ps1
# 或指定参数
.\merge_pdfs.ps1 -InputPath "C:\PDFs" -OutputFile "result.pdf"

Linux Bash使用

# 赋予执行权限
chmod +x merge_pdfs.sh
# 运行
./merge_pdfs.sh
# 或指定参数
./merge_pdfs.sh /path/to/pdfs output.pdf

安装依赖

Python

pip install PyPDF2
# 或
pip install pypdf

Windows (PDFtk)

下载并安装: https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

Linux

# Ubuntu/Debian
sudo apt-get install poppler-utils pdftk ghostscript
# CentOS/RHEL
sudo yum install poppler-utils pdftk ghostscript
# macOS
brew install poppler pdftk ghostscript

这些脚本都能实现自动合并PDF文件的功能,您可以根据自己的操作系统和需求选择最适合的方案。

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