Skip to footer content
USING IRONPDF FOR PYTHON

How to Edit A PDF File in Python

Iron Software presents the IronPDF for Python library, a solution that revolutionizes the ease with which PDF editing tasks are performed in Python. Whether you need to insert signatures, add HTML footers, embed watermarks, include annotations, or edit PDF files, IronPDF for Python is your go-to tool. The library ensures your code remains readable, supports the creation of PDFs programmatically, facilitates straightforward debugging, and seamlessly deploys across all compatible platforms and environments.

This tutorial article will explore these extensive features with illustrative Python code examples and comprehensive explanations. By the end of this guide, you'll have a solid understanding of how to use IronPDF for Python for all your PDF editing needs.

How to Edit PDF Files in Python

  1. Install the Python PDF Library using pip Installer.
  2. Apply the License Key for the Python PDF Library.
  3. Load the PDF Document for editing.
  4. Edit the PDF document using different options such as Split, Copy Pages, and other PDF Operations.
  5. Save the modified file using the SaveAs function.

Edit Document Structure

Manipulate Pages

IronPDF simplifies the process of adding pages at specific positions, extracting specific pages or a range of pages, and removing pages from any PDF. It handles all the complex processes for you, making it easy to perform these tasks efficiently.

Add Pages

You can add pages to PDF documents by specifying the page content, size, and position. After making the desired changes, you can save the output PDF file using the SaveAs function.

from ironpdf import *

# Enable debugging and set log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load existing PDF and Render HTML as new PDF page
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
renderer = ChromePdfRenderer()
coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")

# Prepend new page to existing PDF
pdf.PrependPdf(coverPagePdf)

# Save the updated PDF document
pdf.SaveAs("report_with_cover.pdf")
from ironpdf import *

# Enable debugging and set log path
Logger.EnableDebugging = True
Logger.LogFilePath = "Custom.log"
Logger.LoggingMode = Logger.LoggingModes.All

# Load existing PDF and Render HTML as new PDF page
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")
renderer = ChromePdfRenderer()
coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")

# Prepend new page to existing PDF
pdf.PrependPdf(coverPagePdf)

# Save the updated PDF document
pdf.SaveAs("report_with_cover.pdf")
PYTHON

Copy Pages

You can copy pages from one PDF document to another existing PDF file by specifying the page number and destination. Additionally, you have the option to create a new PDF file from the copied PDF pages. It is also possible to select one page or multiple pages from a single PDF file for copying.

from ironpdf import *

# Load the PDF document
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")

# Copy pages 3 to 5 and save them as a new document.
pdf.CopyPages(2, 4).SaveAs("report_highlight.pdf")
from ironpdf import *

# Load the PDF document
pdf = PdfDocument("C:\\Users\\Administrator\\Downloads\\Documents\\sample.pdf")

# Copy pages 3 to 5 and save them as a new document.
pdf.CopyPages(2, 4).SaveAs("report_highlight.pdf")
PYTHON

Delete Pages

You can delete pages from the input PDF file by specifying the page number.

from ironpdf import *

# Load the PDF document
pdf = PdfDocument("report.pdf")

# Remove the last page from the PDF
pdf.RemovePage(pdf.PageCount-1)

# Save the updated PDF
pdf.SaveAs("Report-Minus-1.pdf")
from ironpdf import *

# Load the PDF document
pdf = PdfDocument("report.pdf")

# Remove the last page from the PDF
pdf.RemovePage(pdf.PageCount-1)

# Save the updated PDF
pdf.SaveAs("Report-Minus-1.pdf")
PYTHON

Merge and Split PDFs

IronPDF's user-friendly API makes it easy to combine multiple PDFs into one or break down an existing PDF into separate files.

Join Multiple Existing PDFs into a Single PDF Document

You can join multiple PDF documents into a single document by specifying the input PDF documents and output PDF documents.

from ironpdf import *

# Define HTML content for two separate PDFs
html_a = """<p> [PDF_A] </p>
            <p> [PDF_A] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_A] 2nd Page</p>"""

html_b = """<p> [PDF_B] </p>
            <p> [PDF_B] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_B] 2nd Page</p>"""

# Render each HTML content as PDF
renderer = ChromePdfRenderer()
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)

# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b)

# Save the merged PDF
merged.SaveAs("Merged.pdf")
from ironpdf import *

# Define HTML content for two separate PDFs
html_a = """<p> [PDF_A] </p>
            <p> [PDF_A] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_A] 2nd Page</p>"""

html_b = """<p> [PDF_B] </p>
            <p> [PDF_B] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_B] 2nd Page</p>"""

# Render each HTML content as PDF
renderer = ChromePdfRenderer()
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)

# Merge the PDFs into a single document
merged = PdfDocument.Merge(pdfdoc_a, pdfdoc_b)

# Save the merged PDF
merged.SaveAs("Merged.pdf")
PYTHON

Splitting a PDF and Extracting Pages

You can split a PDF document into multiple documents or extract specific pages from PDF files by specifying the input PDF document and output PDF documents or page numbers.

from ironpdf import *

# Define the HTML structure of the document
html = """<p> Hello Iron </p>
          <p> This is 1st Page </p>
          <div style='page-break-after: always;'></div>
          <p> This is 2nd Page</p>
          <div style='page-break-after: always;'></div>
          <p> This is 3rd Page</p>"""

# Render the HTML as a PDF document
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)

# Create a separate document for the first page
page1doc = pdf.CopyPage(0)
page1doc.SaveAs("Split1.pdf")

# Create a separate document for pages 2 and 3
page23doc = pdf.CopyPages(1, 2)
page23doc.SaveAs("Split2.pdf")
from ironpdf import *

# Define the HTML structure of the document
html = """<p> Hello Iron </p>
          <p> This is 1st Page </p>
          <div style='page-break-after: always;'></div>
          <p> This is 2nd Page</p>
          <div style='page-break-after: always;'></div>
          <p> This is 3rd Page</p>"""

# Render the HTML as a PDF document
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html)

# Create a separate document for the first page
page1doc = pdf.CopyPage(0)
page1doc.SaveAs("Split1.pdf")

# Create a separate document for pages 2 and 3
page23doc = pdf.CopyPages(1, 2)
page23doc.SaveAs("Split2.pdf")
PYTHON

Edit Document Properties

Add and Use PDF Metadata

You can add and use PDF metadata with IronPDF for Python. This can be beneficial for adding copyright information, tracking changes, or simply making your PDF documents more searchable.

PDF metadata is a collection of data stored in a PDF document. This data can include the title, author, subject, keywords, creation date, and modification date of the PDF document. Additionally, it can include custom data that you add as per your requirements.

from ironpdf import *
from datetime import datetime

# Load the encrypted PDF document
pdf = PdfDocument.FromFile("encrypted.pdf", "password")

# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()

# Save the updated PDF document
pdf.SaveAs("MetaData-Updated.pdf")
from ironpdf import *
from datetime import datetime

# Load the encrypted PDF document
pdf = PdfDocument.FromFile("encrypted.pdf", "password")

# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = datetime.now()

# Save the updated PDF document
pdf.SaveAs("MetaData-Updated.pdf")
PYTHON

Digital Signatures

IronPDF allows you to digitally sign new or existing PDF files using .pfx and .p12 X509Certificate2 digital certificates. When a PDF is signed using this method, any modifications to the document would require validation with the certificate, ensuring the document's integrity.

You can find more guidance on generating a signing certificate for free with Adobe Reader on Adobe's website.

In addition to cryptographic signing, IronPDF also supports the use of a handwritten signature image or a company stamp image as an alternative way of signing the document.

from ironpdf import *

# Cryptographically sign an existing PDF in one line of code!
PdfSignature(r".\certificates\IronSoftware.p12", "123456").SignPdfFile("any.pdf")

##### Advanced example for more control #####

# Step 1. Create a PDF.
renderer = ChromePdfRenderer()
doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")

# Step 2. Create a digital signature.
signature = PdfSignature(r"certificates\IronSoftware.pfx", "123456")

# Step 3. Optional signing options and a handwritten signature graphic.
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"

# Step 4. Sign the PDF with the PdfSignature.
doc.Sign(signature)

# Step 5. The PDF is not signed until saved to file, stream, or byte array.
doc.SaveAs("signed.pdf")
from ironpdf import *

# Cryptographically sign an existing PDF in one line of code!
PdfSignature(r".\certificates\IronSoftware.p12", "123456").SignPdfFile("any.pdf")

##### Advanced example for more control #####

# Step 1. Create a PDF.
renderer = ChromePdfRenderer()
doc = renderer.RenderHtmlAsPdf("<h1>Testing 2048 bit digital security</h1>")

# Step 2. Create a digital signature.
signature = PdfSignature(r"certificates\IronSoftware.pfx", "123456")

# Step 3. Optional signing options and a handwritten signature graphic.
signature.SigningContact = "support@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "To show how to sign a PDF"

# Step 4. Sign the PDF with the PdfSignature.
doc.Sign(signature)

# Step 5. The PDF is not signed until saved to file, stream, or byte array.
doc.SaveAs("signed.pdf")
PYTHON

PDF Attachments

IronPDF makes it very easy to add attachments to your PDF documents and remove them whenever you want. This means you can put extra files into your PDFs and take them out as needed, all with the help of IronPDF.

from ironpdf import *

# Instantiate the Renderer and create a PdfDocument from HTML
renderer = ChromePdfRenderer()
my_pdf = renderer.RenderHtmlFileAsPdf("my-content.html")

# Open the PDF document to be attached
pdf = PdfDocument.FromFile("new_sample.pdf")

# Add an attachment with a name and a byte array
attachment1 = my_pdf.Attachments.AddAttachment("attachment_1", pdf.BinaryData)

# Remove an attachment
my_pdf.Attachments.RemoveAttachment(attachment1)

# Save the PDF with attachments
my_pdf.SaveAs("my-content.pdf")
from ironpdf import *

# Instantiate the Renderer and create a PdfDocument from HTML
renderer = ChromePdfRenderer()
my_pdf = renderer.RenderHtmlFileAsPdf("my-content.html")

# Open the PDF document to be attached
pdf = PdfDocument.FromFile("new_sample.pdf")

# Add an attachment with a name and a byte array
attachment1 = my_pdf.Attachments.AddAttachment("attachment_1", pdf.BinaryData)

# Remove an attachment
my_pdf.Attachments.RemoveAttachment(attachment1)

# Save the PDF with attachments
my_pdf.SaveAs("my-content.pdf")
PYTHON

Compress PDFs

IronPDF has the feature to compress PDFs to help reduce their file size. One method is by decreasing the size of the images embedded in the PDF document using the CompressImages method.

Regarding image quality, with JPEG images, 100% quality gives you nearly no loss in the quality of the image, while 1% yields a very poor quality output. In general, an image quality of 90% or more is considered high quality. A medium-quality image lies between 80% and 90%, and a low-quality image ranges from 70% to 80%. If you go below 70%, the image quality significantly deteriorates, but this can help drastically reduce the overall file size of the PDF document.

It is recommended to try different quality percentages to find the right balance of quality and file size that suits your needs. Keep in mind that the noticeable loss in quality after reduction can vary depending on the type of image you're dealing with, as some images may lose clarity more than others.

from ironpdf import *

# Load the PDF document
pdf = PdfDocument("document.pdf")

# Compress images within the PDF (quality between 1-100)
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")

# Compress images with scaling image resolution
pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")
from ironpdf import *

# Load the PDF document
pdf = PdfDocument("document.pdf")

# Compress images within the PDF (quality between 1-100)
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")

# Compress images with scaling image resolution
pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")
PYTHON

Editing PDF Content

Add Headers and Footers

Adding headers and footers to your PDF documents is straightforward with IronPDF. The software provides two distinct types of HeaderFooters: TextHeaderFooter and HtmlHeaderFooter. TextHeaderFooter is ideal for headers and footers that contain only text and might need to incorporate merge fields such as "{page} of {total-pages}". On the other hand, HtmlHeaderFooter is a more advanced option that can handle any HTML content and format it neatly, making it suitable for more complex headers and footers.

With IronPDF for Python, you can use the HtmlHeaderFooter feature to create HTML headers or footers for your PDF document from HTML. This means you can design your header or footer using HTML, and IronPDF for Python will convert it perfectly to fit your PDF, ensuring every detail is just right. So, if you have an HTML design for a header or footer, IronPDF for Python can apply it to your PDF document with precision.

from ironpdf import *
import os

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Build a footer using HTML to style the text
renderer.RenderingOptions.HtmlFooter = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlFooter.MaxHeight = 15  # millimeters
renderer.RenderingOptions.HtmlFooter.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
renderer.RenderingOptions.HtmlFooter.DrawDividerLine = True

# Ensure sufficient bottom margin
renderer.RenderingOptions.MarginBottom = 25  # mm

# Build a header using an image asset
renderer.RenderingOptions.HtmlHeader = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlHeader.MaxHeight = 20  # millimeters
renderer.RenderingOptions.HtmlHeader.HtmlFragment = "<img src='iron.png'>"
renderer.RenderingOptions.HtmlHeader.BaseUrl = os.path.abspath("C:/Users/lyty1/OneDrive/Documents/IronPdfPythonNew")

# Ensure sufficient top margin
renderer.RenderingOptions.MarginTop = 25  # mm
from ironpdf import *
import os

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Build a footer using HTML to style the text
renderer.RenderingOptions.HtmlFooter = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlFooter.MaxHeight = 15  # millimeters
renderer.RenderingOptions.HtmlFooter.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
renderer.RenderingOptions.HtmlFooter.DrawDividerLine = True

# Ensure sufficient bottom margin
renderer.RenderingOptions.MarginBottom = 25  # mm

# Build a header using an image asset
renderer.RenderingOptions.HtmlHeader = HtmlHeaderFooter()
renderer.RenderingOptions.HtmlHeader.MaxHeight = 20  # millimeters
renderer.RenderingOptions.HtmlHeader.HtmlFragment = "<img src='iron.png'>"
renderer.RenderingOptions.HtmlHeader.BaseUrl = os.path.abspath("C:/Users/lyty1/OneDrive/Documents/IronPdfPythonNew")

# Ensure sufficient top margin
renderer.RenderingOptions.MarginTop = 25  # mm
PYTHON
from ironpdf import *

# Initiate PDF Renderer
renderer = ChromePdfRenderer()

# Add a text header to every page
renderer.RenderingOptions.FirstPageNumber = 1  # use 2 if a cover page will be appended
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25  # create 25mm space for header

# Add a text footer to every page
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginBottom = 25  # create 25mm space for footer
from ironpdf import *

# Initiate PDF Renderer
renderer = ChromePdfRenderer()

# Add a text header to every page
renderer.RenderingOptions.FirstPageNumber = 1  # use 2 if a cover page will be appended
renderer.RenderingOptions.TextHeader.DrawDividerLine = True
renderer.RenderingOptions.TextHeader.CenterText = "{url}"
renderer.RenderingOptions.TextHeader.Font = FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25  # create 25mm space for header

# Add a text footer to every page
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginBottom = 25  # create 25mm space for footer
PYTHON

Outlines and Bookmarks

An outline, also known as a "bookmark", is a tool that helps you quickly go to important pages in a PDF document. If you're using Adobe Acrobat Reader, you can see these bookmarks (which can be organized in a hierarchy) in the app's left sidebar.

IronPDF for Python library makes it even easier to work with bookmarks. It can automatically bring in any existing bookmarks from PDF documents. Plus, you can add more bookmarks, edit them, or arrange them in groups using IronPDF.

from ironpdf import *

# Load an existing PDF document.
pdf = PdfDocument.FromFile("existing.pdf")

# Add bookmarks to the PDF
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)

# Create a new bookmark and add nested bookmarks
summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)
summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)

# Add additional bookmarks
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)

# Save the PDF with new bookmarks
pdf.SaveAs("existing.pdf")
from ironpdf import *

# Load an existing PDF document.
pdf = PdfDocument.FromFile("existing.pdf")

# Add bookmarks to the PDF
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)

# Create a new bookmark and add nested bookmarks
summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)
summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)

# Add additional bookmarks
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)

# Save the PDF with new bookmarks
pdf.SaveAs("existing.pdf")
PYTHON

Add and Edit Annotations

You can add and edit annotations to PDF documents with IronPDF for Python. Annotations can be used to highlight text, add comments, or create links. You can also edit existing annotations.

from ironpdf import *

# Load an existing PDF
pdf = PdfDocument("existing.pdf")

# Create a TextAnnotation object
annotation = TextAnnotation()
annotation.Title = "This is the title"
annotation.Subject = "This is a subject"
annotation.Contents = "This is the comment content..."
annotation.Icon = TextAnnotation.AnnotationIcon.Help
annotation.Opacity = 0.9
annotation.Printable = False
annotation.Hidden = False
annotation.OpenByDefault = True
annotation.ReadOnly = False
annotation.Rotateable = True

# Add the annotation to a specific page and location within the PDF
pdf.AddTextAnnotation(annotation, 1, 150, 250)

# Save the PDF with annotations
pdf.SaveAs("existing.pdf")
from ironpdf import *

# Load an existing PDF
pdf = PdfDocument("existing.pdf")

# Create a TextAnnotation object
annotation = TextAnnotation()
annotation.Title = "This is the title"
annotation.Subject = "This is a subject"
annotation.Contents = "This is the comment content..."
annotation.Icon = TextAnnotation.AnnotationIcon.Help
annotation.Opacity = 0.9
annotation.Printable = False
annotation.Hidden = False
annotation.OpenByDefault = True
annotation.ReadOnly = False
annotation.Rotateable = True

# Add the annotation to a specific page and location within the PDF
pdf.AddTextAnnotation(annotation, 1, 150, 250)

# Save the PDF with annotations
pdf.SaveAs("existing.pdf")
PYTHON

Add Backgrounds and Foregrounds

IronPDF for Python lets you add backgrounds and foregrounds to PDF documents. This can be useful for adding watermarks, creating custom templates, or simply making your PDF documents look more visually appealing. You can use images, colors, or gradients as backgrounds or foregrounds.

from ironpdf import *

# Instantiate Renderer for PDF creation
renderer = ChromePdfRenderer()

# Render a PDF from a given URL
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

# Add a background PDF
pdf.AddBackgroundPdf("MyBackground.pdf")

# Add a foreground overlay PDF to the first page
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)

# Save the merged PDF with background and foreground
pdf.SaveAs("Complete.pdf")
from ironpdf import *

# Instantiate Renderer for PDF creation
renderer = ChromePdfRenderer()

# Render a PDF from a given URL
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

# Add a background PDF
pdf.AddBackgroundPdf("MyBackground.pdf")

# Add a foreground overlay PDF to the first page
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)

# Save the merged PDF with background and foreground
pdf.SaveAs("Complete.pdf")
PYTHON

Stamping and Watermarking

IronPDF for Python allows you to stamp and watermark PDF documents. This can be useful for adding copyright information, preventing unauthorized copying, or simply making your PDF documents look more professional. You can stamp PDF documents with text, images, or watermarks. You can also control the size, position, and opacity of stamps and watermarks.

Apply Stamp onto a PDF

You can apply a stamp to a PDF document with IronPDF for Python. This can be useful for adding a logo, a signature, or other identifying information to a PDF document. You can choose the stamp type, position, and size. You can also set the stamp opacity.

from ironpdf import *

# Define an HTML Stamper to apply an image stamp
stamper = HtmlStamper("<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'/>")
stamper.HorizontalAlignment = HorizontalAlignment.Center
stamper.VerticalAlignment = VerticalAlignment.Bottom
stamper.IsStampBehindContent = False
stamper.Opacity = 30

# Load existing PDF and apply the stamp
pdf = PdfDocument.FromFile("Sample.pdf")
pdf.ApplyStamp(stamper).SaveAs("stampedimage.pdf")
from ironpdf import *

# Define an HTML Stamper to apply an image stamp
stamper = HtmlStamper("<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'/>")
stamper.HorizontalAlignment = HorizontalAlignment.Center
stamper.VerticalAlignment = VerticalAlignment.Bottom
stamper.IsStampBehindContent = False
stamper.Opacity = 30

# Load existing PDF and apply the stamp
pdf = PdfDocument.FromFile("Sample.pdf")
pdf.ApplyStamp(stamper).SaveAs("stampedimage.pdf")
PYTHON

Add a Watermark to a PDF

IronPDF for Python lets you add a watermark to a PDF document. This can be useful for preventing unauthorized copying or simply making your PDF documents look more professional. You can choose the watermark text, font, size, and color. You can also set the watermark opacity.

from ironpdf import *

# Instantiate the Renderer and create a PdfDocument from a URL
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

# Apply a watermark to the PDF
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)

# Save the watermarked PDF
pdf.SaveAs("Watermarked.pdf")
from ironpdf import *

# Instantiate the Renderer and create a PdfDocument from a URL
renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

# Apply a watermark to the PDF
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)

# Save the watermarked PDF
pdf.SaveAs("Watermarked.pdf")
PYTHON

Using Forms in PDFs

You can create and edit forms in PDF documents with IronPDF for Python. This can be useful for collecting data from users or simply making your PDF documents more interactive. You can add form fields such as text boxes, checkboxes, and radio buttons. You can also collect form data from users.

Create and Edit Forms

from ironpdf import *

# HTML content for a form with text inputs, radio buttons, and checkboxes
form_html = """
<html>
    <body>
        <h2>Editable PDF Form</h2>
        <form>
            First name: <br> <input type='text' name='firstname' value=''> <br>
            Last name: <br> <input type='text' name='lastname' value=''> <br>
            <br>
            <p>Please specify your gender:</p>
            <input type='radio' id='female' name='gender' value= 'Female'>
            <label for='female'>Female</label> <br>
            <br>
            <input type='radio' id='male' name='gender' value='Male'>
            <label for='male'>Male</label> <br>
            <br>
            <input type='radio' id='non-binary/other' name='gender' value='Non-Binary / Other'>
            <label for='non-binary/other'>Non-Binary / Other</label>
            <br>

            <p>Please select all medical conditions that apply:</p>
            <input type='checkbox' id='condition1' name='Hypertension' value='Hypertension'>
            <label for='condition1'> Hypertension</label><br>
            <input type='checkbox' id='condition2' name='Heart Disease' value='Heart Disease'>
            <label for='condition2'> Heart Disease</label><br>
            <input type='checkbox' id='condition3' name='Stroke' value='Stroke'>
            <label for='condition3'> Stroke</label><br>
            <input type='checkbox' id='condition4' name='Diabetes' value='Diabetes'>
            <label for='condition4'> Diabetes</label><br>
            <input type='checkbox' id='condition5' name='Kidney Disease' value='Kidney Disease'>
            <label for='condition5'> Kidney Disease</label><br>
        </form>
    </body>
</html>
"""

# Instantiate Renderer and enable form creation
renderer = ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True

# Render the form HTML to PDF and save it
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")

# Open the form PDF and update form values
form_document = PdfDocument.FromFile("BasicForm.pdf")

# Update and read the form fields
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print(f"FirstNameField value: {first_name_field.Value}")

last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print(f"LastNameField value: {last_name_field.Value}")

# Save the filled form PDF
form_document.SaveAs("FilledForm.pdf")
from ironpdf import *

# HTML content for a form with text inputs, radio buttons, and checkboxes
form_html = """
<html>
    <body>
        <h2>Editable PDF Form</h2>
        <form>
            First name: <br> <input type='text' name='firstname' value=''> <br>
            Last name: <br> <input type='text' name='lastname' value=''> <br>
            <br>
            <p>Please specify your gender:</p>
            <input type='radio' id='female' name='gender' value= 'Female'>
            <label for='female'>Female</label> <br>
            <br>
            <input type='radio' id='male' name='gender' value='Male'>
            <label for='male'>Male</label> <br>
            <br>
            <input type='radio' id='non-binary/other' name='gender' value='Non-Binary / Other'>
            <label for='non-binary/other'>Non-Binary / Other</label>
            <br>

            <p>Please select all medical conditions that apply:</p>
            <input type='checkbox' id='condition1' name='Hypertension' value='Hypertension'>
            <label for='condition1'> Hypertension</label><br>
            <input type='checkbox' id='condition2' name='Heart Disease' value='Heart Disease'>
            <label for='condition2'> Heart Disease</label><br>
            <input type='checkbox' id='condition3' name='Stroke' value='Stroke'>
            <label for='condition3'> Stroke</label><br>
            <input type='checkbox' id='condition4' name='Diabetes' value='Diabetes'>
            <label for='condition4'> Diabetes</label><br>
            <input type='checkbox' id='condition5' name='Kidney Disease' value='Kidney Disease'>
            <label for='condition5'> Kidney Disease</label><br>
        </form>
    </body>
</html>
"""

# Instantiate Renderer and enable form creation
renderer = ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True

# Render the form HTML to PDF and save it
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")

# Open the form PDF and update form values
form_document = PdfDocument.FromFile("BasicForm.pdf")

# Update and read the form fields
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print(f"FirstNameField value: {first_name_field.Value}")

last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print(f"LastNameField value: {last_name_field.Value}")

# Save the filled form PDF
form_document.SaveAs("FilledForm.pdf")
PYTHON

Conclusion

IronPDF for Python is a powerful Python PDF library that enables you to create, manipulate, and edit PDF documents from Python. With this library, manipulating PDF documents has become remarkably easy. It offers a wide range of features, including the ability to edit document structure, manipulate pages, merge and split PDFs, edit document properties, and add and use PDF metadata.

IronPDF for Python is user-friendly and can be seamlessly integrated into any Python project. It serves as a valuable tool for anyone who needs to work with PDF documents in Python. The IronPDF for Python license starts from $749. You can find more information on the IronPDF website.

Frequently Asked Questions

What is the Python library for simplifying PDF editing tasks?

IronPDF for Python is a library that simplifies PDF editing tasks in Python, allowing you to insert signatures, add HTML footers, embed watermarks, include annotations, and edit PDF files programmatically.

How do I install the PDF library for Python?

You can install the IronPDF library for Python using the pip installer by running 'pip install ironpdf' in your command line interface.

How can I add a new page to an existing PDF?

To add a new page, load the existing PDF with IronPDF's PdfDocument, create a new page with ChromePdfRenderer and RenderHtmlAsPdf, and use PrependPdf or AppendPdf to add the new page. Save the document with SaveAs.

Can I merge multiple PDFs into a single document?

Yes, IronPDF allows you to merge multiple PDFs into a single document by loading the PDFs you want to merge and using the PdfDocument.Merge function.

Is it possible to apply digital signatures to a PDF?

IronPDF supports digital signatures using .pfx and .p12 certificate files. You can sign PDFs cryptographically to ensure document integrity.

How do I add metadata to a PDF?

You can add metadata such as author, title, and keywords to a PDF by accessing the MetaData property of a PdfDocument object and setting the desired fields using IronPDF.

Can I add headers and footers to a PDF?

Yes, you can add both text and HTML headers and footers to PDFs using IronPDF. The library provides options for customizing the content and appearance.

How can I compress a PDF?

IronPDF allows you to compress PDFs by reducing image sizes with the CompressImages method, which can be configured for different quality levels.

Is it possible to create interactive forms in PDFs?

Yes, IronPDF enables you to create and edit interactive forms in PDFs, allowing users to fill in text fields, checkboxes, and radio buttons.

What types of annotations can I add to a PDF?

With IronPDF, you can add various annotations such as text annotations, comments, and links to PDF documents, and you can also edit existing annotations.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.

Install with pip

Version: 2025.6

> pip install ironpdf

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?