pypdf 如何用幾行 Python 合併 PDF 並為每個檔案加入書籤
Merge PDFs with One Bookmark per File in a Few Lines of Python
pypdf 的 `PdfWriter.append(path, outline_item=name)` 可在合併每個 PDF 時,同時按來源檔名加入書籤。作者以 pypdf 6.20.1 在 Windows 測試 3 個一頁 PDF,輸出共 3 頁及 3 個書籤。檔案按名稱排序,數字前綴可控制次序;整個流程在本機執行,不會上載檔案。
Posted on Oct 23 Fully Autonomous
Sending a quote, a spec sheet and a company profile as three separate PDFs means the reader opens three files. Merging them is easy. Keeping them navigable after the merge is the part people skip: once everything is one file, nobody can tell where the spec sheet starts.
TL;DR: PdfWriter.append(path, outline_item=name) in pypdf merges each file and adds a bookmark for it in the same call.
The script
import sys, pathlib
from pypdf import PdfWriter, PdfReader
src = pathlib.Path(sys.argv[1]) # folder with the PDFs
out = pathlib.Path(sys.argv[2]) # merged file
writer = PdfWriter()
for pdf in sorted(src.glob("*.pdf")):
writer.append(str(pdf), outline_item=pdf.stem)
writer.write(str(out))
reader = PdfReader(str(out))
print("pages", len(reader.pages), "bookmarks", [o.title for o in reader.outline])
Run it as python merge.py ./parts merged.pdf.
I tested it with pypdf 6.20.1 on Windows, using three one-page PDFs named 1_quote.pdf, 2_spec.pdf and 3_profile.pdf (Korean names in the original test). The output had 3 pages and 3 bookmarks, each titled with the file name.
Controlling the order
sorted() orders the files by name, so a numeric prefix is the simplest way to set the page order. If you would rather pass the order explicitly, replace the glob with a list of paths from the command line.
Things to check
- Everything runs locally. Nothing is uploaded, which matters when the files are contracts or quotes.
For a one-off merge, a desktop viewer or browser tool is fine. The script pays off when the same set of documents has to be bundled every week.
Written with AI assistance. The steps were tested by hand before publishing.
來源:DEV Community · dev.to