view source

PDF Editing: Merge, Split, Fill, Redact and Protect

skill

Merge, split, rotate, fill, watermark, compress, password-protect or redact existing PDF files, then check the result. Use when a PDF must be changed.

Apache-2.0 Requires: python3 and uv (pypdf, PyMuPDF on demand); poppler (pdftotext, pdfinfo, pdftoppm) for checks. Optional: qpdf. macOS/Linux.

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

  1. Copy the input to a working name. Never write over the original, and keep the original until the user accepts the result.
  2. One operation per output file, named for the operation (merged.pdf, redacted.pdf), so a failed step can be redone.
  3. After each step run the checks below. A step that fails a check is redone, not patched later.
text
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 it

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

OperationToolNotes
Merge, split, reorder, rotate, extract pages, encrypt, decrypt, checkqpdf (Apache-2.0)Works on structure and leaves page content alone; not a content editor
Fill and flatten forms, stamps, page numbers, metadata, size reductionpypdf (BSD-3-Clause), run with uv run --with pypdf python script.pyPure Python; AES needs --with cryptography
RedactionPyMuPDF, run with uv run --with pymupdf python script.pyAGPL v3 or a commercial Artifex licence: tell the user, and use pypdf or qpdf where they do the job
Checks and renderingpoppler toolsDifferent engine from the editors, so it does not repeat their mistakes

Pages: merge, split, reorder, rotate

text
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; z is the last page and r1 counts from the end; a descending range reverses order.
  • qpdf takes bookmarks, form fields and article tags from the primary (first) file only. With --empty as primary, a merge keeps no bookmarks; with a.pdf as primary it keeps a's and none from b.pdf. pypdf's append imports each file's outline. Compare bookmark counts after a merge.
  • Merging files with forms: call pypdf's add_form_topname on each reader first so field names do not collide.
  • --rotate=+90 rotates clockwise relative to the current rotation; pdfinfo -f 1 -l 1 shows the result as rot: 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

text
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=True to the same call and then w.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 /XFA in 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, then page.merge_page(stamp, over=False) per page of the writer for a watermark behind the content, over=True for 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 with pdfinfo and the XMP with pdfinfo -meta.
  • Size: compress_identical_objects(remove_duplicates=True, remove_unreferenced=True) just before writing, then page.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:

text
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:

text
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 --check exit code, text extraction and a rendered page were checked for each output.
  • Bookmarks, form fields, Tagged status 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.