Saltar al pie de página
USANDO IRONPDF PARA PYTHON

Cómo Editar Un Archivo PDF en Python

Iron Software presenta la biblioteca IronPDF for Python, una solución que revoluciona la facilidad con la que se realizan las tareas de edición de PDF en Python. Ya sea que necesites insertar firmas, añadir pies de página en HTML, incrustar marcas de agua, incluir anotaciones o editar archivos PDF, IronPDF for Python es tu herramienta ideal. La biblioteca asegura que tu código permanezca legible, admite la creación de PDFs de manera programática, facilita la depuración sencilla y se despliega sin problemas en todas las plataformas y entornos compatibles.

Este artículo tutorial explorará estas características extensas con ejemplos de código en Python ilustrativos y explicaciones completas. Al final de esta guía, tendrás una sólida comprensión de cómo usar IronPDF for Python para todas tus necesidades de edición de PDF.

Cómo editar archivos PDF en Python

  1. Instala la biblioteca Python PDF usando el instalador pip.
  2. Aplica la clave de licencia para la biblioteca Python PDF.
  3. Carga el documento PDF para editar.
  4. Edita el documento PDF usando diferentes opciones como Dividir, Copiar Páginas y otras Operaciones PDF.
  5. Guarda el archivo modificado usando la función SaveAs.

Editar estructura del documento

Manipular páginas

IronPDF simplifica el proceso de añadir páginas en posiciones específicas, extraer páginas específicas o un rango de páginas, y eliminar páginas de cualquier PDF. Se encarga de todos los procesos complejos por ti, haciendo que estas tareas se realicen de manera eficiente.

Añadir páginas

Puedes añadir páginas a los documentos PDF especificando el contenido de la página, tamaño y posición. Después de realizar los cambios deseados, puedes guardar el archivo PDF de salida usando la función SaveAs.

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

Páginas de copia

Puedes copiar páginas de un documento PDF a otro archivo PDF existente especificando el número de página y el destino. Además, tienes la opción de crear un nuevo archivo PDF a partir de las páginas PDF copiadas. También es posible seleccionar una o múltiples páginas de un solo archivo PDF para copiar.

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

Borrar páginas

Puedes eliminar páginas del archivo PDF de entrada especificando el número de página.

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

Fusionar y dividir PDF

La API fácil de usar de IronPDF hace que sea fácil combinar múltiples PDFs en uno solo o dividir un PDF existente en archivos separados.

Unir varios PDF existentes en un único documento PDF

Puedes unir múltiples documentos PDF en un solo documento especificando los documentos PDF de entrada y los documentos PDF de salida.

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

Dividir un PDF y extraer páginas

Puedes dividir un documento PDF en múltiples documentos o extraer páginas específicas de archivos PDF especificando el documento PDF de entrada y los documentos PDF de salida o números de página.

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

Editar propiedades del documento

Añadir y utilizar metadatos PDF

Puedes añadir y utilizar metadatos PDF con IronPDF for Python. Esto puede ser beneficioso para añadir información de derechos de autor, seguir los cambios o simplemente hacer que tus documentos PDF sean más buscables.

Los metadatos PDF son una colección de datos almacenados en un documento PDF. Estos datos pueden incluir el título, autor, tema, palabras clave, fecha de creación y fecha de modificación del documento PDF. Además, puede incluir datos personalizados que añadas según tus requisitos.

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

Firmas digitales

IronPDF te permite firmar digitalmente archivos PDF nuevos o existentes usando certificados digitales .pfx y .p12 X509Certificate2. Cuando un PDF se firma usando este método, cualquier modificación al documento requeriría validación con el certificado, asegurando la integridad del documento.

Puedes encontrar más orientación sobre cómo generar un certificado de firma gratis con Adobe Reader en el sitio web de Adobe.

Además de la firma criptográfica, IronPDF también admite el uso de una imagen de firma manuscrita o una imagen de sello de la empresa como una forma alternativa de firmar el documento.

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

Adjuntos PDF

IronPDF hace que sea muy fácil añadir archivos adjuntos a tus documentos PDF y eliminarlos cuando desees. Esto significa que puedes poner archivos extra en tus PDFs y sacarlos según necesites, todo con la ayuda de 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

Comprimir PDF

IronPDF tiene la función de comprimir PDFs para ayudar a reducir su tamaño de archivo. Un método es disminuyendo el tamaño de las imágenes incrustadas en el documento PDF usando el método CompressImages.

En cuanto a la calidad de imagen, con imágenes JPEG, el 100% de calidad te da casi ninguna pérdida en la calidad de la imagen, mientras que el 1% produce una calidad de salida muy pobre. En general, una calidad de imagen del 90% o más se considera de alta calidad. Una imagen de calidad media se encuentra entre el 80% y el 90%, y una imagen de baja calidad oscila entre el 70% y el 80%. Si bajas del 70%, la calidad de la imagen se deteriora significativamente, pero esto puede ayudar a reducir drásticamente el tamaño total del archivo del documento PDF.

Se recomienda probar diferentes porcentajes de calidad para encontrar el equilibrio adecuado de calidad y tamaño de archivo que se adapte a tus necesidades. Ten en cuenta que la pérdida de calidad notable después de la reducción puede variar dependiendo del tipo de imagen con la que estés trabajando, ya que algunas imágenes pueden perder claridad más que otras.

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

Edición de contenido PDF

Añadir encabezados y pies de página

Añadir encabezados y pies de página a tus documentos PDF es sencillo con IronPDF. El software proporciona dos tipos distintos de HeaderFooters: TextHeaderFooter y HtmlHeaderFooter. TextHeaderFooter es ideal para encabezados y pies de página que solo contienen texto y que podrían necesitar incorporar campos de combinación como "{page} of {total-pages}". Por otro lado, HtmlHeaderFooter es una opción más avanzada que puede manejar cualquier contenido HTML y formatearlo ordenadamente, haciéndolo adecuado para encabezados y pies de página más complejos.

Cabecera y pie de página HTML

Con IronPDF for Python, puedes usar la función HtmlHeaderFooter para crear encabezados o pies de página en HTML para tu documento PDF a partir de HTML. Esto significa que puedes diseñar tu encabezado o pie de página usando HTML, e IronPDF for Python lo convertirá perfectamente para ajustarse a tu PDF, asegurando que cada detalle esté justo como lo deseas. Así que, si tienes un diseño en HTML para un encabezado o pie de página, IronPDF for Python puede aplicarlo a tu documento PDF con precisión.

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

Cabecera y pie de página

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

Contornos y marcadores

Un esquema, también conocido como "marcador", es una herramienta que te ayuda a ir rápidamente a páginas importantes en un documento PDF. Si estás usando Adobe Acrobat Reader, puedes ver estos marcadores (que se pueden organizar en una jerarquía) en la barra lateral izquierda de la aplicación.

La biblioteca IronPDF for Python hace que sea aún más fácil trabajar con marcadores. Puede traer automáticamente cualquier marcador existente de los documentos PDF. Además, puedes añadir más marcadores, editarlos o organizarlos en grupos usando 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

Añadir y editar anotaciones

Puedes añadir y editar anotaciones en documentos PDF con IronPDF for Python. Las anotaciones se pueden utilizar para resaltar texto, añadir comentarios o crear enlaces. También puedes editar las anotaciones existentes.

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

Añadir fondos y primeros planos

IronPDF for Python te permite añadir fondos y primeros planos a documentos PDF. Esto puede ser útil para añadir marcas de agua, crear plantillas personalizadas o simplemente hacer que tus documentos PDF se vean más atractivos visualmente. Puedes usar imágenes, colores o degradados como fondos o primeros planos.

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

Sellado y marca de agua

IronPDF for Python te permite estampar y poner marca de agua a documentos PDF. Esto puede ser útil para añadir información de derechos de autor, prevenir copias no autorizadas o simplemente hacer que tus documentos PDF se vean más profesionales. Puedes estampar documentos PDF con texto, imágenes o marcas de agua. También puedes controlar el tamaño, posición y opacidad de los sellos y marcas de agua.

Aplicar sello a un PDF

Puedes aplicar un sello a un documento PDF con IronPDF for Python. Esto puede ser útil para añadir un logotipo, una firma u otra información identificativa a un documento PDF. Puedes elegir el tipo de sello, posición y tamaño. También puedes configurar la opacidad del sello.

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

Añadir una marca de agua a un PDF

IronPDF for Python te permite añadir una marca de agua a un documento PDF. Esto puede ser útil para prevenir copias no autorizadas o simplemente hacer que tus documentos PDF se vean más profesionales. Puedes elegir el texto de la marca de agua, fuente, tamaño y color. También puedes configurar la opacidad de la marca de agua.

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

Uso de formularios en PDF

Puedes crear y editar formularios en documentos PDF con IronPDF for Python. Esto puede ser útil para recopilar datos de los usuarios o simplemente hacer que tus documentos PDF sean más interactivos. Puedes añadir campos de formulario como cuadros de texto, casillas de verificación y botones de opción. También puedes recopilar datos de formularios de los usuarios.

Crear y editar formularios

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

Conclusión

IronPDF for Python es una poderosa biblioteca Python PDF que te permite crear, manipular y editar documentos PDF desde Python. Con esta biblioteca, manipular documentos PDF se ha vuelto notablemente fácil. Ofrece una amplia gama de características, incluyendo la capacidad de editar la estructura del documento, manipular páginas, fusionar y dividir PDFs, editar propiedades del documento, y añadir y usar metadatos PDF.

IronPDF for Python es fácil de usar y se puede integrar sin problemas en cualquier proyecto Python. Sirve como una herramienta valiosa para cualquiera que necesite trabajar con documentos PDF en Python. La licencia de IronPDF for Python comienza desde $799. Puedes encontrar más información en el sitio web de IronPDF.

Preguntas Frecuentes

¿Cómo puedo editar archivos PDF en Python?

Puedes usar IronPDF for Python para editar archivos PDF insertando firmas, añadiendo pies de página en HTML, incorporando marcas de agua e incluyendo anotaciones mediante programación.

¿Qué pasos están involucrados en la instalación de IronPDF for Python?

Para instalar IronPDF for Python, puedes usar el instalador pip ejecutando pip install ironpdf en tu interfaz de línea de comandos.

¿Cómo puedo añadir una marca de agua a un PDF usando Python?

Con IronPDF for Python, puedes añadir marcas de agua a un PDF accediendo al documento PDF y utilizando los métodos de la biblioteca para incorporar imágenes o texto de marca de agua.

¿Puedo combinar múltiples archivos PDF en uno solo usando Python?

Sí, IronPDF te permite combinar múltiples PDFs en un solo documento cargando los PDFs y utilizando la función Merge.

¿Cómo puedo aplicar una firma digital a un PDF en Python?

IronPDF admite la aplicación de firmas digitales usando archivos de certificado .pfx y .p12, lo que te permite firmar PDFs criptográficamente para la integridad del documento.

¿Es posible añadir metadatos a un PDF con IronPDF?

Sí, puedes añadir metadatos como autor, título y palabras clave accediendo a la propiedad MetaData de un objeto PdfDocument y configurando los campos deseados.

¿Cómo añado encabezados y pies de página a un PDF en Python?

Puedes añadir texto y encabezados y pies de página HTML a PDFs usando IronPDF, con opciones para personalizar su contenido y apariencia.

¿Qué métodos puedo usar para comprimir archivos PDF en Python?

IronPDF te permite comprimir PDFs usando el método CompressImages, que reduce el tamaño de las imágenes y puede configurarse para varios niveles de calidad.

¿Cómo puedo crear formularios PDF interactivos en Python?

IronPDF permite la creación y edición de formularios PDF interactivos, permitiendo a los usuarios llenar campos de texto, casillas de verificación y botones de opción.

¿Qué tipos de anotaciones se pueden añadir a un PDF usando IronPDF?

IronPDF te permite añadir anotaciones de texto, comentarios, enlaces y editar anotaciones existentes en documentos PDF.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más