惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyberwarzone
Cyberwarzone
S
Secure Thoughts
L
LINUX DO - 热门话题
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CERT Recently Published Vulnerability Notes
P
Privacy & Cybersecurity Law Blog
A
Arctic Wolf
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cybersecurity and Infrastructure Security Agency CISA
大猫的无限游戏
大猫的无限游戏
U
Unit 42
Recorded Future
Recorded Future
Hacker News: Ask HN
Hacker News: Ask HN
F
Full Disclosure
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Know Your Adversary
Know Your Adversary
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
T
Threatpost
I
InfoQ
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cloudbric
Cloudbric
L
LangChain Blog
N
Netflix TechBlog - Medium
The Register - Security
The Register - Security
S
Security @ Cisco Blogs
B
Blog
T
Threat Research - Cisco Blogs
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
D
DataBreaches.Net
Simon Willison's Weblog
Simon Willison's Weblog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
W
WeLiveSecurity
Forbes - Security
Forbes - Security
O
OpenAI News
C
Check Point Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Last Watchdog
The Last Watchdog
H
Help Net Security
SecWiki News
SecWiki News

Inside Nutrient

A guide to the invisible work behind documents Introducing Nutrient Documents for Salesforce: Native document generation and signing Document AI vs. traditional OCR: Choosing between OCR, AI, and hybrid pipelines PDF SDK compliance and security evaluation checklist for enterprise teams (2026) Invariant Corp replaces paper processes with Nutrient Workflow and scales without limits What is process mapping? A complete guide Nutrient vs. Conga Composer for Salesforce document generation (2026) Document routing: How to automate document distribution The CTO’s AI playbook: Why accountability architecture beats orchestration Compliance workflow automation: Why built-in compliance is table stakes Workflow diagrams: Examples, symbols, and how to build one that actually runs Digital forms: Replace paper forms with automated workflows Approval workflow software: How to automate approvals Why document-centric automation is different The CEO’s AI playbook: Why decision architecture beats model selection Nutrient SDK product updates for Q1 2026 PDF redaction verification: How to prove sensitive data is permanently removed What is a VPAT? The complete guide to accessibility conformance reports What is PDF/UA? The accessible PDF standard explained Salesforce eSignatures: Generate, sign, and track documents in one flow Online document viewer: Options, tradeoffs, and how to embed one Document viewer for web apps: React, Vue, Angular (2026) Best document viewers in 2026: A buyer’s guide Nutrient advances Workflow platform with agentic AI for enterprise-grade speed and consistency in document-heavy operations How to create a Salesforce quote template from opportunity data The business case for accessibility: Five ways it drives enterprise value Python PDF library comparison (2026): 7 libraries for developers Why your AI agent hallucinates PDF table data PDF.js limitations: When to upgrade to a commercial PDF SDK How Subject scaled 5× with Nutrient’s PDF SDK without rebuilding its document layer I replaced our sales training with an AI coach that runs in Slack — here’s what broke Redirecting to: https://securitybuzz.com/cybersecurity-news/why-enterprise-permissions-are-ais-most-dangerous-inheritance/ Nutrient .NET SDK vs. iText Core: Complete comparison for .NET developers DocuVieware: Support’s most frequently asked setup questions Introducing Nutrient Workflow How to convert PDF to Word in C# (.NET) When email and spreadsheets stop working: Work order approval workflows for field teams on the move Compliance with confidence: Why document-centric automation is the foundation of your mission Nutrient expands AI Assistant, automating multistep document workflows inside any application What is document generation? A developer’s guide to PDF generation Document Converter data flow and how real-time watermarks skip the queue PDF/UA compliance guide: Requirements, standards, and best practices Computers still can’t understand you How Athena Intelligence built AI agents for regulated enterprises with Nutrient’s document infrastructure How to convert HTML to PDF (2026): 4 methods from browser print to SDK How to build a document extraction pipeline with Nutrient Vision API OCR vs. intelligent document processing: Choosing the right document extraction engine Beyond OCR: How document intelligence eliminates manual processing in regulated industries Nutrient vs. IronPDF: Complete comparison for .NET developers Nutrient vs. Aspose.PDF: Complete comparison for .NET developers Redirecting to: https://fortune.com/2026/02/19/openclaw-who-is-peter-steinberger-openai-sam-altman-anthropic-moltbook/ Lufthansa Systems uses Nutrient to deliver reliable, scalable PDF rendering for pilots worldwide Nutrient vs. Syncfusion: Complete comparison for .NET developers React’s useTransition: The hook you’re probably using wrong First City Monument Bank streamlines banking processes with Nutrient Workflow Redirecting to: https://www.sdcexec.com/warehousing/automation/article/22957364/nutrient-workflow-automation-the-missing-link-in-supply-chain-efficiency The complete guide to digital signatures: PAdES, CAdES, and XAdES explained Nutrient Python SDK: Production-grade document processing for Python Introducing agentic document editing for web applications with AI Assistant Nutrient vs. QuestPDF: Complete comparison for .NET developers How we fixed the GdPicture license expiration (and what to do if you’re affected) Red team security testing with agentic AI The future of healthcare document automation Best healthcare workflow software compared Nutrient SDK product updates for Q4 2025 How Harvey scaled legal document workflows 50 percent MoM without rebuilding infrastructure HIPAA-compliant document management in hospitals How we optimized rendering performance while handling thousands of annotations in React — Part 2 Automated PII removal with Nutrient API Redirecting to: https://www.devopsdigest.com/2026-low-code-no-code-predictions Redirecting to: https://www.kmworld.com/Articles/Editorial/ViewPoints/Leaders-predict-AI-to-continue-permeating-all-aspects-of-KM-in-2026-172594.aspx What are deep agents and how do they solve complex problems? Whipping up document magic: Your easy-bake recipe for Vue and Nutrient Web SDK 🧁 What I’ve learned about product iteration planning while building SDKs Passwordless document signing: Three-layer security guide New zip folder functionality streamlines file management in Document Automation Server The keyboard shortcuts playbook: Taking control of keyboard events in Nutrient Web SDK From experienced engineer to AI beginner: My unexpected journey AI-assisted manual testing: Handling Safari’s PDF rendering and UI quirks How to keep a 20-year-old SDK up to date How we optimized rendering performance while handling thousands of annotations in React — Part 1 Nutrient announces new executive hires to accelerate next phase of growth High performance UI using web workers Automate document conversion at scale with Python and Nutrient DCS From curiosity to PLG (and AI): My journey to understanding product-led growth Prost to progress: One year as Nutrient Pigeon usage at Nutrient: Bridging native SDKs to Flutter Modernizing CI build servers: How to migrate from Chef to Ansible Unix man pages: AI-friendly documentation since 1971 Consistent hashing for even load distribution Best AI redaction APIs: Complete comparison guide for 2025 Why AI document redaction matters for modern security From coding to coordinating: How AI transformed my workflow What is intelligent document processing (IDP)? A complete guide Enterprise PDF SDKs: Best PSPDFKit (now Nutrient) alternatives Nutrient SDK product updates for Q3 2025 GdPicture support best practices Redacting sensitive data with Nutrient AI redaction API How AI is transforming the customer experience at Nutrient: From instant answers to intelligent support How manual QA uses PR testing between releases
How to edit a PDF in Python: Add text, images, and annotations
Hulya Masharipov · 2026-04-22 · via Inside Nutrient

Table of contents

    Editing PDFs in Python is more difficult than reading them. Most open source libraries let you overlay new content and fill basic AcroForm fields, but truly rewriting text or handling advanced form workflows like XFA, validation, and signatures typically requires a dedicated SDK. This guide covers what each approach can do — with code you can copy.

    How to edit a PDF in Python: Add text, images, and annotations

    TL;DR

    Four ways to edit PDFs in Python:

    Open source tools handle simple overlays and basic form filling. For advanced form workflows, structural redaction, or digital signatures, you’ll need Nutrient Python SDK.

    What “editing” a PDF means

    PDF editing ranges from simple overlays to structural changes. The right tool depends on what you need:

    • Text overlay — Stamp new text on top of existing content without changing the original. Good for watermarks or headers.
    • Content insertion — Add text, images, or shapes at specific coordinates. The original content stays untouched.
    • Form filling — Write values into predefined form fields (AcroForm or XFA).
    • Annotation — Add highlights, sticky notes, or freehand drawings as a separate layer.
    • Text replacement — Find and replace text in the PDF content stream. This is rare and fragile in open source libraries.
    • Redaction — Permanently remove content from the document structure; don’t just draw a black box over it.
    • Digital signatures — Apply certificate-based signatures for legal validity.

    Most open source Python PDF libraries handle the first two well. Everything below that line typically requires a commercial SDK.

    Prerequisites

    All examples in this tutorial use Python 3.10+. Create a virtual environment and install the libraries as you go:

    python -m venv pdf-edit-env

    source pdf-edit-env/bin/activate # macOS/Linux

    # pdf-edit-env\Scripts\activate # Windows

    You’ll also need a sample PDF to work with. Any multipage PDF with text will do.

    Method 1: Add a text overlay with PyPDF and ReportLab

    PyPDF(opens in a new tab) can merge PDF pages, so you can generate a “stamp” page with ReportLab(opens in a new tab) and merge it onto an existing page. This is the most common open source approach for adding text to a PDF.

    Install

    pip install pypdf reportlab

    Code example

    from io import BytesIO

    from pypdf import PdfReader, PdfWriter

    from reportlab.pdfgen import canvas

    # Read the source PDF first so the overlay matches its page size.

    reader = PdfReader("input.pdf")

    first_page = reader.pages[0]

    page_width = float(first_page.mediabox.width)

    page_height = float(first_page.mediabox.height)

    # Create a text overlay sized to the source page.

    buffer = BytesIO()

    c = canvas.Canvas(buffer, pagesize=(page_width, page_height))

    c.setFont("Helvetica", 36)

    c.setFillColorRGB(0.8, 0, 0) # Red text

    c.drawString(100, page_height - 100, "DRAFT — DO NOT DISTRIBUTE")

    c.save()

    buffer.seek(0)

    # Merge overlay onto the first page.

    overlay_reader = PdfReader(buffer)

    writer = PdfWriter()

    first_page.merge_page(overlay_reader.pages[0])

    writer.add_page(first_page)

    # Copy remaining pages unchanged.

    for page in reader.pages[1:]:

    writer.add_page(page)

    with open("output_stamped.pdf", "wb") as f:

    writer.write(f)

    print("Overlay applied to first page.")

    What this approach can do

    • Stamp text, shapes, or images anywhere on existing pages.
    • Add watermarks or headers/footers across all pages.
    • Combine multiple PDFs into one.

    Limitations

    • You can’t read or change existing text; you can only add new layers on top.
    • There’s no annotation or redaction support. PyPDF does support basic AcroForm filling via update_page_form_field_values(), but that’s a separate workflow from the overlay approach shown here.
    • Positioning is manual (you specify x/y coordinates in points).

    Method 2: Insert text and images with PyMuPDF

    PyMuPDF(opens in a new tab) provides direct page-level methods for inserting text and images without needing a separate library.

    Install

    Code example: Insert text

    import pymupdf

    doc = pymupdf.open("input.pdf")

    page = doc[0]

    # Insert text at a specific position.

    page.insert_text(

    (72, 72), # x, y in points (1 inch from top-left)

    "Reviewed: 2026-02-27",

    fontsize=14,

    color=(0, 0, 0.8), # Blue

    )

    doc.save("output_text.pdf")

    doc.close()

    print("Text inserted on first page.")

    Code example: Insert an image

    import pymupdf

    doc = pymupdf.open("input.pdf")

    page = doc[0]

    # Define a rectangle where the image should appear.

    rect = pymupdf.Rect(400, 20, 550, 80) # x0, y0, x1, y1

    page.insert_image(rect, filename="logo.png")

    doc.save("output_logo.pdf")

    doc.close()

    print("Image inserted on first page.")

    Code example: Add a highlight annotation

    import pymupdf

    doc = pymupdf.open("input.pdf")

    page = doc[0]

    # Search for text and highlight it.

    text_instances = page.search_for("important")

    for inst in text_instances:

    page.add_highlight_annot(inst)

    doc.save("output_highlighted.pdf")

    doc.close()

    print(f"Highlighted {len(text_instances)} instances.")

    What this approach can do

    • Insert text, images, and vector shapes at precise coordinates.
    • Add annotations (highlights, underlines, sticky notes, stamps).
    • Basic redaction via add_redact_annot() and apply_redactions().
    • Extract and replace images.

    Limitations

    • The AGPL-3.0 license requires you to open source your own code or purchase a commercial license.
    • Text replacement is fragile — it works by redacting the old text and inserting new text at the same position, which can break with complex fonts or layouts.
    • Form filling is supported via the Widget class, but digital signature creation isn’t.
    • Redaction is annotation-based, which is less robust than structural redaction. add_redact_annot() and apply_redactions() remove visible page content, but recoverable data may remain depending on the document structure and how the file is saved. Use a commercial SDK for regulatory or compliance redaction.

    Method 3: Full PDF editing with Nutrient Python SDK

    Nutrient Python SDK supports structural redaction, digital signatures, and reliable text annotation — capabilities missing from open source libraries — in a single pip install.

    Install

    Code example: Add a text annotation

    from nutrient_sdk import Document, PdfEditor, Color

    with Document.open("input.pdf") as document:

    editor = PdfEditor.edit(document)

    page = editor.get_page_collection().get_first()

    annotations = page.get_annotation_collection()

    annotations.add_free_text(

    100.0, 700.0, 250.0, 40.0, # x, y, width, height

    "Reviewer",

    "Reviewed and approved",

    "Arial",

    14.0,

    Color.from_argb(255, 0, 0, 0),

    )

    editor.save_as("output_annotated.pdf")

    editor.close()

    print("Text annotation added.")

    Code example: Fill form fields

    from nutrient_sdk import Document, PdfEditor

    with Document.open("form.pdf") as document:

    editor = PdfEditor.edit(document)

    form_fields = editor.get_form_field_collection()

    name = form_fields.find_by_full_name("name")

    if name is not None:

    name.set_value("Jane Doe")

    email = form_fields.find_by_full_name("email")

    if email is not None:

    email.set_value("jane@example.com")

    date = form_fields.find_by_full_name("date")

    if date is not None:

    date.set_value("2026-02-27")

    editor.save_as("output_filled.pdf")

    editor.close()

    print("Form fields filled.")

    Code example: Apply structural redaction

    from nutrient_sdk import Document, PdfEditor, Color

    with Document.open("report.pdf") as document:

    editor = PdfEditor.edit(document)

    page = editor.get_page_collection().get_first()

    annotations = page.get_annotation_collection()

    redaction = annotations.add_redact(

    72.0, 200.0, 468.0, 30.0, # x, y, width, height

    )

    redaction.interior_color = Color.from_argb(255, 0, 0, 0)

    editor.save_as("output_redacted.pdf")

    editor.close()

    print("Redaction applied — content permanently removed on save.")

    Code example: Apply a digital signature

    from nutrient_sdk import Document, Signature, DigitalSignatureOptions

    with Signature() as signer, Document.open("contract.pdf") as document:

    options = DigitalSignatureOptions()

    options.certificate_path = "certificate.pfx"

    options.certificate_password = "cert-password"

    options.signer_name = "Jane Doe"

    options.reason = "Contract Approval"

    signer.sign(document, "signed_contract.pdf", options)

    print("Digital signature applied.")

    What this approach can do

    Everything in methods 1 and 2, plus:

    • Fill AcroForm and XFA form fields programmatically.
    • Apply structural redaction that removes content from the PDF stream (not just a visual overlay).
    • Add certificate-based digital signatures.
    • Convert between common document and image formats (PDF, Word, Excel, PowerPoint, HTML, and images).
    • Perform optical character recognition (OCR) on scanned documents with multilanguage support.
    • Batch process thousands of files in server-side workflows.

    Limitations

    • Commercial license — requires a paid subscription.
    • Larger install than pure-Python libraries.

    Test form filling, redaction, and signatures with your own documents.

    Method 4: Edit PDFs via Nutrient API

    Nutrient API provides the same editing operations over HTTP, with no local install. This works well for serverless environments, CI pipelines, or offloading processing to a remote service.

    Code example: Add a watermark via API

    import os

    import requests

    # Store the API key in an environment variable — don't hardcode or commit it.

    api_key = os.environ.get("NUTRIENT_API_KEY")

    if not api_key:

    raise ValueError(

    "Set the NUTRIENT_API_KEY environment variable before running this example."

    )

    url = "https://api.nutrient.io/build"

    with open("input.pdf", "rb") as input_file:

    response = requests.post(

    url,

    headers={"Authorization": f"Bearer {api_key}"},

    files={"file": input_file},

    data={

    "instructions": '{"parts":[{"file":"file"}],'

    '"actions":[{"type":"watermark",'

    '"text":"CONFIDENTIAL","fontSize":48}]}'

    },

    timeout=30,

    )

    response.raise_for_status()

    with open("output_watermarked.pdf", "wb") as f:

    f.write(response.content)

    print("Watermark applied via API.")

    The free tier includes 50 credits. Sign up here(opens in a new tab).

    Comparison: Which method fits your use case?

    CapabilityPyPDF and ReportLabPyMuPDFNutrient SDKNutrient API
    Text overlay
    Image insertion✅ (via ReportLab)
    Annotations
    Form filling✅ Basic
    Structural redaction
    Digital signatures
    Text replacement⚠️ Fragile
    LicenseBSD-3 + BSDAGPL-3.0CommercialPay-per-use
    Local install❌ (HTTP)

    Conclusion

    For text overlays or watermarks, PyPDF with ReportLab or PyMuPDF work well at zero cost. PyMuPDF is faster and has better annotation support, but its AGPL license restricts commercial use without a separate license.

    For structural redaction, digital signatures, or cross-format conversion, open source libraries lack support. Nutrient Python SDK covers those use cases in a single library.

    FAQ

    True in-place text editing (changing the words already in a PDF) is difficult with open source libraries. PyMuPDF can redact old text and insert new text at the same position, but this breaks with complex fonts or multiline content. Nutrient Python SDK provides more reliable text editing through its document engine.

    A text overlay adds new content on top of an existing page — like placing a sticky note on a printed page. The original content remains unchanged underneath. Real PDF editing modifies the document’s internal content stream, which is needed for operations like form filling, redaction, and text replacement.

    Not necessarily. PyPDF supports basic AcroForm filling via update_page_form_field_values(), and PyMuPDF provides form interaction through its Widget class. Both handle simple text fields and checkboxes well. For advanced form types (XFA forms, complex field validation, signature fields) or production batch workflows, Nutrient Python SDK provides broader coverage with support for text fields, checkboxes, dropdowns, radio buttons, and signature fields.

    Explore related topics

    Try for free Ready to get started?

    Related SDK articles

    Explore more