PDF Editing: Merge, Split, Fill, Redact and Protect
skillMerge, split, rotate, fill, watermark, compress, password-protect or redact existing PDF files, then check the result. Use when a PDF must be changed.
agents that use this skill
instructions
Overview
Use this skill to change a PDF that already exists: merge, split, reorder, rotate, extract pages, fill form fields, add page numbers or a watermark, shrink the file, edit metadata, set or remove a password, redact. The deliverable is a new file plus proof that it is right: page count, extractable text, form values, and for redaction, proof that the removed content is gone.
Mental model
- A PDF is a set of objects: page content, a text layer, form fields, bookmarks (an outline), a structure tree that makes the file accessible ("tagged"), metadata and signatures. An operation touches some of these and silently skips others.
- What the eye sees and what a program extracts are different things. Anything drawn on top of text hides it from the eye only.
- Document-level objects such as bookmarks, form fields and tags belong to the document, not the page, and merging can leave them behind.
- A digital signature covers the original bytes of the file. Editing signed content invalidates it.
Rules
Work on a copy and verify each result
- Copy the input to a working name. Never write over the original, and keep the original until the user accepts the result.
- One operation per output file, named for the operation (
merged.pdf,redacted.pdf), so a failed step can be redone. - After each step run the checks below. A step that fails a check is redone, not patched later.
pdfinfo out.pdf # page count, Tagged, Encrypted
qpdf --check out.pdf; echo $? # structure; exit 0 = no errors found
pdftotext out.pdf - | head # text is still extractable
pdftoppm -r 50 -png -f 1 -l 1 out.pdf p # render a page, then look at itqpdf --check finds structural errors only; its own output says the file may still contain errors it cannot detect. Rendering and looking at a page is part of the check.
Pick the tool
| Operation | Tool | Notes |
|---|---|---|
| Merge, split, reorder, rotate, extract pages, encrypt, decrypt, check | qpdf (Apache-2.0) | Works on structure and leaves page content alone; not a content editor |
| Fill and flatten forms, stamps, page numbers, metadata, size reduction | pypdf (BSD-3-Clause), run with uv run --with pypdf python script.py | Pure Python; AES needs --with cryptography |
| Redaction | PyMuPDF, run with uv run --with pymupdf python script.py | AGPL v3 or a commercial Artifex licence: tell the user, and use pypdf or qpdf where they do the job |
| Checks and rendering | poppler tools | Different engine from the editors, so it does not repeat their mistakes |
Pages: merge, split, reorder, rotate
qpdf --empty --pages a.pdf b.pdf -- merged.pdf
qpdf a.pdf --pages . 3,1,2 -- reordered.pdf
qpdf a.pdf --pages . 2-3 -- extract.pdf
qpdf --split-pages a.pdf split.pdf
qpdf a.pdf --rotate=+90:1 -- rotated.pdf- Page ranges start at 1;
zis the last page andr1counts from the end; a descending range reverses order. - qpdf takes bookmarks, form fields and article tags from the primary (first) file only. With
--emptyas primary, a merge keeps no bookmarks; witha.pdfas primary it keeps a's and none fromb.pdf. pypdf'sappendimports each file's outline. Compare bookmark counts after a merge. - Merging files with forms: call pypdf's
add_form_topnameon each reader first so field names do not collide. --rotate=+90rotates clockwise relative to the current rotation;pdfinfo -f 1 -l 1shows the result asrot: 90.- In pypdf, removing a page from the page list leaves its content in the file, and cropping changes only the visible box (pypdf file size guide). Neither removes anything: use the redaction steps for content that must go.
Forms
from pypdf import PdfReader, PdfWriter
w = PdfWriter(clone_from="form.pdf")
w.update_page_form_field_values(w.pages[0], {"full_name": "Ada Lovelace"}, auto_regenerate=False)
w.write("filled.pdf")- Use
auto_regenerate=False; the default sets a flag that makes viewers redraw fields and ask to save on close (pypdf documentation). - To flatten, pass
flatten=Trueto the same call and thenw.remove_annotations(subtypes="/Widget"). This leaves no fields, and the value still prints in the page text. - Read fields back with
PdfReader("filled.pdf").get_fields(), or extract text after flattening. - An XFA form stores its fields in separate XML and a viewer that supports XFA draws that instead of the page. Look for
/XFAin the AcroForm dictionary. If it is present, fill and check in the viewer the recipient uses and say the result was not verified elsewhere.
Page numbers, watermarks, metadata, size
- Stamps and watermarks: build the stamp as a one-page PDF (reportlab, via
--with reportlab), clone the document into a writer, thenpage.merge_page(stamp, over=False)per page of the writer for a watermark behind the content,over=Truefor a stamp above it. The pages must already belong to the writer (pypdf 7 refuses otherwise). For "Page N of M", draw a new stamp per page. - Metadata: two stores exist, the info dictionary and XMP, and both can be present. Set or clear both when the title or author matters.
writer.add_metadata({"/Title": "New title"})sets the info dictionary; confirm the info dictionary withpdfinfoand the XMP withpdfinfo -meta. - Size:
compress_identical_objects(remove_duplicates=True, remove_unreferenced=True)just before writing, thenpage.compress_content_streams()per page. Lowering image quality is lossy: say so, compare sizes and render a page.
Passwords and restrictions
- Set or remove a password only on the owner's instruction or with the owner's authority. qpdf's manual says its decryption is not meant for bypassing copyright restrictions.
- Choose AES-256 explicitly; pypdf defaults to RC4, which its documentation calls insecure. qpdf:
qpdf --encrypt --user-password=U --owner-password=O --bits=256 -- in.pdf out.pdf; to remove a password the owner supplied,qpdf --password=U --decrypt in.pdf out.pdf; pypdf:w.encrypt(user_password="U", owner_password="O", algorithm="AES-256"). Verify that the user password opens the file and that no password fails. - Restrictions (no printing, no copying) are enforced only by the reading software, which can ignore them (qpdf manual). Do not describe them as protection.
- Keep passwords out of the log and file names.
Signed PDFs
A signature covers specific bytes. Appended updates such as form filling or comments may be accepted if the signer's permission level allows them; other changes invalidate it (pyHanko documentation), and these recipes rewrite the file, which invalidates a signature. qpdf's --remove-restrictions invalidates signatures outright. Before editing a signed PDF, tell the user the signature will not survive, work on a copy and have the signer sign again.
Accessibility and structure
Tagged PDFs set the reading order for screen readers (W3C technique PDF3). Merging can lose the structure tree: the PyMuPDF maintainer states its page-by-page insert ignores it, and a pypdf discussion reports tags lost unless the writer is cloned. After any page operation, compare Tagged: in pdfinfo before and after. If a tagged input becomes untagged, say so; repair is work for an accessibility tool.
Redaction
Covering text with a black box hides it from the eye and leaves it in the file and in pdftotext output. Real redaction removes the content:
import pymupdf
doc = pymupdf.open("in.pdf")
for page in doc:
for rect in page.search_for("SECRET123"):
page.add_redact_annot(rect, fill=(0, 0, 0))
page.apply_redactions()
doc.set_metadata({})
doc.scrub()
doc.save("redacted.pdf", garbage=4, deflate=True)apply_redactions removes the content under each rectangle; by default it blanks overlapping image pixels and removes overlapping vector graphics, and the text-removal option is the default one (PyMuPDF documentation). A character is removed whole when its box overlaps the rectangle, so neighbouring text can vanish: compare the extracted text around each redaction with the original. scrub() with defaults also removes links, attachments and embedded files, and resets form fields; to keep any that must survive, pass remove_links=False, attached_files=False, embedded_files=False or reset_fields=False.
Then prove it, per term. Run the same searches on the original first as a control:
pdftotext in.pdf - | grep -c "SECRET123"
pdftotext redacted.pdf - | grep -c "SECRET123"
qpdf --qdf --object-streams=disable in.pdf - | grep -a -c "SECRET123"
qpdf --qdf --object-streams=disable redacted.pdf - | grep -a -c "SECRET123"
pdfinfo redacted.pdf | grep -iE "author|title"
pdfinfo -meta redacted.pdf | grep -iE "author|title|creator"The proof is text extraction: the original returns more than 0 and the redacted copy returns 0, and a rendered page shows the area blank. The raw-file search finds only literal strings. A font keyed by glyph ids (CID) stores the term as codes, so the search returns 0 even when the text is still there. It counts as evidence only if it finds the term in the original; if it does not, rely on extraction and rendering and say so. The two metadata checks must print neither an author nor a title you meant to remove, since a redacted copy that keeps its metadata still shows the author. Search every spelling and split form of each term; check bookmarks, annotations, form fields and attachments too. For a scan, the page is an image: confirm the pixels are blanked by rendering, and that no text layer from earlier recognition still holds the term. Report what was searched; never state that a document is "fully redacted" beyond those checks.
Examples
Box over text. Bad: draw a black rectangle on the account number and send the file. Good: remove the content, clear metadata, and show extraction finds the term in the original and returns 0 on the copy, with the rendered page blank; add the raw-file search only if it finds the term in the original.
Edit of a signed contract. Bad: stamp page numbers on a signed PDF and call it done. Good: warn that the signature breaks, produce the copy, and ask the signer to re-sign.
Checklist
- Work happened on a copy; the original is untouched.
- Page count,
qpdf --checkexit code, text extraction and a rendered page were checked for each output. - Bookmarks, form fields,
Taggedstatus and metadata were compared with the input and differences reported. - Signed input: the user was told the signature breaks.
- Redaction: each term was found in the original and returns 0 in extracted text of the copy, a rendered page is blank, the raw-file search counts only if it found the term in the original, neighbouring text was compared and metadata is cleared.
- Passwords used with the owner's authority, with AES-256, and kept out of the log.
Composition / References
Scope limits: making a PDF from another source and extracting tables or text are separate jobs.
- pypdf: https://pypdf.readthedocs.io/en/stable/user/merging-pdfs.html , https://pypdf.readthedocs.io/en/stable/user/forms.html , https://pypdf.readthedocs.io/en/stable/user/encryption-decryption.html , https://pypdf.readthedocs.io/en/stable/user/metadata.html , https://pypdf.readthedocs.io/en/stable/user/add-watermark.html , https://pypdf.readthedocs.io/en/stable/user/file-size.html
- qpdf manual: https://qpdf.readthedocs.io/en/stable/cli.html , https://qpdf.readthedocs.io/en/stable/encryption.html
- PyMuPDF: https://pymupdf.readthedocs.io/en/latest/about.html , https://pymupdf.readthedocs.io/en/latest/page.html#Page.add_redact_annot
- pyHanko, incremental update analysis: https://docs.pyhanko.eu/en/latest/lib-guide/validation/diff-analysis.html
- W3C PDF3: https://www.w3.org/WAI/WCAG22/Techniques/pdf/PDF3
- Structure tree lost on merge: https://github.com/pymupdf/PyMuPDF/issues/2469 , https://github.com/py-pdf/pypdf/discussions/2694
- PDFlib, XFA deprecated in PDF 2.0: https://www.pdflib.com/pdf-knowledge-base/pdf-20/deprecated-features/