Cómo editar un PDF en C#

This article was translated from English: Does it need improvement?
Translated
View the article in English

Introducción

Iron Software ha simplificado muchas funciones diferentes de edición de PDF en métodos fáciles de leer y comprender en la biblioteca IronPDF. Ya sea para añadir firmas, añadir pies de página HTML, estampar marcas de agua o añadir anotaciones. IronPDF es la herramienta que le permite disponer de código legible, generación programática de PDF, depuración sencilla e implantación fácil en cualquier entorno o plataforma compatible.

IronPDF tiene innumerables funciones a la hora de editar PDF. En este artículo tutorial, vamos a recorrer algunos de los principales con ejemplos de código y algunas explicaciones.

Con este artículo usted tendrá una buena comprensión de cómo utilizar IronPDF para editar sus PDFs en C#.

Índice

Editar la estructura del documento

Manipular páginas

Añadir PDF en índices específicos, copiar páginas como un rango o una a una, y eliminar páginas de cualquier PDF es un paseo por el parque con IronPDF, que se encarga de todo entre bastidores.

Añadir páginas

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-1.cs
var pdf = new PdfDocument("report.pdf");
var renderer = new ChromePdfRenderer();
var coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>");
pdf.PrependPdf(coverPagePdf);
pdf.SaveAs("report_with_cover.pdf");
Dim pdf = New PdfDocument("report.pdf")
Dim renderer = New ChromePdfRenderer()
Dim coverPagePdf = renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>")
pdf.PrependPdf(coverPagePdf)
pdf.SaveAs("report_with_cover.pdf")
VB   C#

Páginas de copia

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-2.cs
var pdf = new PdfDocument("report.pdf");
// Copy pages 5 to 7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("report_highlight.pdf");
Dim pdf = New PdfDocument("report.pdf")
' Copy pages 5 to 7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("report_highlight.pdf")
VB   C#

Borrar páginas

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-3.cs
var pdf = new PdfDocument("report.pdf");

// Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1);
pdf.SaveAs("report_minus_one_page.pdf");
Dim pdf = New PdfDocument("report.pdf")

' Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("report_minus_one_page.pdf")
VB   C#

Fusionar y dividir PDF

Fusionar PDFs en un solo PDF o dividir un PDF existente se consigue fácilmente con la intuitiva API de IronPDF.

Unir varios PDF existentes en un único documento PDF

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-4.cs
var pdfs = new List<PdfDocument>
{
    PdfDocument.FromFile("A.pdf"),
    PdfDocument.FromFile("B.pdf"),
    PdfDocument.FromFile("C.pdf")
};

PdfDocument mergedPdf = PdfDocument.Merge(pdfs);
mergedPdf.SaveAs("merged.pdf");

foreach (var pdf in pdfs)
{
    pdf.Dispose();
}
Dim pdfs = New List(Of PdfDocument) From {PdfDocument.FromFile("A.pdf"), PdfDocument.FromFile("B.pdf"), PdfDocument.FromFile("C.pdf")}

Dim mergedPdf As PdfDocument = PdfDocument.Merge(pdfs)
mergedPdf.SaveAs("merged.pdf")

For Each pdf In pdfs
	pdf.Dispose()
Next pdf
VB   C#

Para ver la unión de dos o más PDF en nuestra página de ejemplos de código, visite aquí.

Dividir un PDF y extraer páginas

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-5.cs
var pdf = new PdfDocument("sample.pdf");

// Take the first page
var pdf_page1 = pdf.CopyPage(0);
pdf_page1.SaveAs("Split1.pdf");

// Take the pages 2 & 3
var pdf_page2_3 = pdf.CopyPages(1, 2);
pdf_page2_3.SaveAs("Spli2t.pdf");
Dim pdf = New PdfDocument("sample.pdf")

' Take the first page
Dim pdf_page1 = pdf.CopyPage(0)
pdf_page1.SaveAs("Split1.pdf")

' Take the pages 2 & 3
Dim pdf_page2_3 = pdf.CopyPages(1, 2)
pdf_page2_3.SaveAs("Spli2t.pdf")
VB   C#

Para ver la división y extracción de páginas en nuestra página de ejemplos de código, visite aquí.

Editar las propiedades del documento

Añadir y utilizar metadatos PDF

Puede utilizar IronPDF fácilmente para examinar y editar metadatos PDF:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-6.cs
// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = System.DateTime.Now;

// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;

// Change or set the document encryption password
pdf.SecuritySettings.OwnerPassword = "top-secret"; // password to edit the pdf
pdf.SecuritySettings.UserPassword = "shareable";  // password to open the pdf
pdf.SaveAs("secured.pdf");
Imports System

' Open an Encrypted File, alternatively create a new PDF from Html
Dim pdf = PdfDocument.FromFile("encrypted.pdf", "password")

' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = DateTime.Now

' Edit file security settings
' The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights

' Change or set the document encryption password
pdf.SecuritySettings.OwnerPassword = "top-secret" ' password to edit the pdf
pdf.SecuritySettings.UserPassword = "shareable" ' password to open the pdf
pdf.SaveAs("secured.pdf")
VB   C#

Firmas digitales

IronPDF tiene opciones para firmar digitalmente archivos PDF nuevos o existentes utilizando certificados digitales .pfx y .p12 X509Certificate2.

Una vez firmado un archivo PDF, no puede modificarse sin que se valide el certificado. Así se garantiza la fidelidad.

Para generar gratuitamente un certificado de firma utilizando Adobe Reader, lea https://helpx.adobe.com/acrobat/using/digital-ids.html.

Además de la firma criptográfica, también se puede utilizar una imagen de firma manuscrita o de sello de empresa para firmar con IronPDF.

Firme criptográficamente un PDF existente en 1 línea de código!

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-7.cs
using IronPdf;
using IronPdf.Signing;


new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");
Imports IronPdf
Imports IronPdf.Signing


Call (New IronPdf.Signing.PdfSignature("Iron.p12", "123456")).SignPdfFile("any.pdf")
VB   C#

Ejemplo más avanzado que tiene más control:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-8.cs
using IronPdf;

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

// Step 2. Create a Signature.
// You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
// Read: https://helpx.adobe.com/acrobat/using/digital-ids.html
var signature = new IronPdf.Signing.PdfSignature("Iron.pfx", "123456")
{
    // Step 3. Optional signing options and a handwritten signature graphic
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "Chicago, USA",
    SigningReason = "To show how to sign a PDF"
};

//Step 4. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature);

//Step 5. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");
Imports IronPdf

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

' Step 2. Create a Signature.
' You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
' Read: https://helpx.adobe.com/acrobat/using/digital-ids.html
Private signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
	.SigningContact = "support@ironsoftware.com",
	.SigningLocation = "Chicago, USA",
	.SigningReason = "To show how to sign a PDF"
}

'Step 4. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature)

'Step 5. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf")
VB   C#

Archivos adjuntos en PDF

IronPDF es totalmente compatible con la adición y eliminación de archivos adjuntos a y desde sus documentos PDF.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-9.cs
var Renderer = new ChromePdfRenderer();
var myPdf = Renderer.RenderHtmlFileAsPdf("my-content.html");

// Here we can add an attachment with a name and byte[]
var attachment1 = myPdf.Attachments.AddAttachment("attachment_1", example_attachment);

// And here is an example of removing an attachment
myPdf.Attachments.RemoveAttachment(attachment1);

myPdf.SaveAs("my-content.pdf");
Dim Renderer = New ChromePdfRenderer()
Dim myPdf = Renderer.RenderHtmlFileAsPdf("my-content.html")

' Here we can add an attachment with a name and byte[]
Dim attachment1 = myPdf.Attachments.AddAttachment("attachment_1", example_attachment)

' And here is an example of removing an attachment
myPdf.Attachments.RemoveAttachment(attachment1)

myPdf.SaveAs("my-content.pdf")
VB   C#

Comprimir PDF

IronPDF admite la compresión de archivos PDF. Una forma de reducir el tamaño de un archivo PDF es reducir el tamaño de las imágenes incrustadas en el documento. En IronPDF, podemos llamar al método CompressImages.

Tal y como funciona el redimensionamiento de JPEG, la calidad del 100% casi no tiene pérdida, y el 1% es una imagen de salida de muy baja calidad. En general, el 90% o más se considera de alta calidad, el 80%-90% de calidad media y el 70%-80% de baja calidad. Reducir por debajo del 70% producirá imágenes de baja calidad, pero hacerlo puede reducir drásticamente el tamaño total del archivo PdfDocument.

Experimente con distintos valores para hacerse una idea de la relación entre la calidad y el tamaño del archivo y conseguir el equilibrio óptimo para sus necesidades. La obviedad de la reducción de calidad depende en última instancia del tipo de imagen que se haya introducido, y algunas imágenes pueden reducir su claridad de forma más significativa que otras.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-10.cs
var pdf = new PdfDocument("document.pdf");

// Quality parameter can be 1-100, where 100 is 100% of original quality
pdf.CompressImages(60);
pdf.SaveAs("document_compressed.pdf");
Dim pdf = New PdfDocument("document.pdf")

' Quality parameter can be 1-100, where 100 is 100% of original quality
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")
VB   C#

Hay un segundo parámetro opcional que puede reducir la resolución de la imagen según su tamaño visible en el documento PDF. Tenga en cuenta que esto puede causar distorsión con algunas configuraciones de imagen:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-11.cs
var pdf = new PdfDocument("document.pdf");

pdf.CompressImages(90, true);
pdf.SaveAs("document_scaled_compressed.pdf");
Dim pdf = New PdfDocument("document.pdf")

pdf.CompressImages(90, True)
pdf.SaveAs("document_scaled_compressed.pdf")
VB   C#

Editar contenido PDF

Añadir encabezados y pies de página

Puede añadir fácilmente encabezados y pies de página a su PDF. IronPDF tiene dos tipos diferentes de "HeaderFooters" que son TextHeaderFooter y HtmlHeaderFooter. TextHeaderFooter es mejor para encabezados y pies de página que sólo contienen texto y pueden querer utilizar campos merge como ".{página} de {total-páginas}". HtmlHeaderFooter es un avanzado encabezado y pie de página que funciona con cualquier HTML en él y formatos ordenadamente.

Encabezado y pie de página HTML

HTML Header and Footer utilizará la versión renderizada de su HTML como encabezado o pie de página en su documento PDF para un diseño perfecto.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-12.cs
var renderer = new ChromePdfRenderer();

// Build a footer using html to style the text
// mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    MaxHeight = 15, //millimeters
    HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
    DrawDividerLine = true
};

// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    MaxHeight = 20, //millimeters
    HtmlFragment = "<img src='logo.png'>",
    BaseUrl = new System.Uri(@"C:\assets\images").AbsoluteUri
};
Dim renderer = New ChromePdfRenderer()

' Build a footer using html to style the text
' mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
	.MaxHeight = 15,
	.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
	.DrawDividerLine = True
}

' Build a header using an image asset
' Note the use of BaseUrl to set a relative path to the assets
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
	.MaxHeight = 20,
	.HtmlFragment = "<img src='logo.png'>",
	.BaseUrl = (New System.Uri("C:\assets\images")).AbsoluteUri
}
VB   C#

Para ver un ejemplo completo con múltiples casos de uso, consulte el siguiente tutorial: aquí.

Encabezado y pie de página de texto

El encabezado y pie de página básico es el TextHeaderFooter, por favor vea el ejemplo a continuación.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-13.cs
var renderer = new ChromePdfRenderer
{
    RenderingOptions =
    {
        FirstPageNumber = 1, // use 2 if a cover-page  will be appended

        // Add a header to every page easily:
        TextHeader =
        {
            DrawDividerLine = true,
            CenterText = "{url}",
            Font = IronSoftware.Drawing.FontTypes.Helvetica,
            FontSize = 12
        },

        // Add a footer too:
        TextFooter =
        {
            DrawDividerLine = true,
            Font = IronSoftware.Drawing.FontTypes.Arial,
            FontSize = 10,
            LeftText = "{date} {time}",
            RightText = "{page} of {total-pages}"
        }
    }
};
Dim renderer = New ChromePdfRenderer With {
	.RenderingOptions = {
		FirstPageNumber = 1, TextHeader = {
			DrawDividerLine = True,
			CenterText = "{url}",
			Font = IronSoftware.Drawing.FontTypes.Helvetica,
			FontSize = 12
		},
		TextFooter = {
			DrawDividerLine = True,
			Font = IronSoftware.Drawing.FontTypes.Arial,
			FontSize = 10,
			LeftText = "{date} {time}",
			RightText = "{page} of {total-pages}"
		}
	}
}
VB   C#

También tenemos los siguientes campos merge que serán reemplazados por valores cuando se rendericen: {página}, {total-páginas}, {url}, {fecha}, {tiempo}, {html-title}, {título pdf}

Buscar y reemplazar texto en un PDF

Cree marcadores de posición en sus PDF y sustitúyalos mediante programación, o simplemente sustituya todas las instancias de una frase de texto utilizando nuestro método ReplaceTextOnPage.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-14.cs
// Using an existing PDF
var pdf = PdfDocument.FromFile("sample.pdf");

// Parameters
int pageIndex = 1;
string oldText = ".NET 6"; // Old text to remove
string newText = ".NET 7"; // New text to add

// Replace Text on Page
pdf.ReplaceTextOnPage(pageIndex, oldText, newText);

// Placeholder Template Example
pdf.ReplaceTextOnPage(pageIndex, "[DATE]", "01/01/2000");

// Save your new PDF
pdf.SaveAs("new_sample.pdf");
' Using an existing PDF
Dim pdf = PdfDocument.FromFile("sample.pdf")

' Parameters
Dim pageIndex As Integer = 1
Dim oldText As String = ".NET 6" ' Old text to remove
Dim newText As String = ".NET 7" ' New text to add

' Replace Text on Page
pdf.ReplaceTextOnPage(pageIndex, oldText, newText)

' Placeholder Template Example
pdf.ReplaceTextOnPage(pageIndex, "[DATE]", "01/01/2000")

' Save your new PDF
pdf.SaveAs("new_sample.pdf")
VB   C#

Para ver el ejemplo de Buscar y reemplazar texto en nuestra página de ejemplos de código, visite aquí

Esquemas y marcadores

Un esquema o "marcador" añade una forma de navegar a páginas clave de un PDF. En Adobe Acrobat Reader estos marcadores (que pueden estar anidados) se muestran en la barra lateral izquierda de la aplicación. IronPDF importará automáticamente los marcadores existentes en los documentos PDF y permitirá añadir, editar y anidar más.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-15.cs
// Create a new PDF or edit an existing document.
PdfDocument pdf = PdfDocument.FromFile("existing.pdf");

// Add bookmark
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2);
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3);

// Store new bookmark in a variable to add nested bookmarks to
var summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17);

// Add a sub-bookmark within the summary
var conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18);

// Add another bookmark to end of highest-level bookmark list
pdf.Bookmarks.AddBookMarkAtEnd("References", 20);

pdf.SaveAs("existing.pdf");
' Create a new PDF or edit an existing document.
Dim pdf As PdfDocument = PdfDocument.FromFile("existing.pdf")

' Add bookmark
pdf.Bookmarks.AddBookMarkAtEnd("Author's Note", 2)
pdf.Bookmarks.AddBookMarkAtEnd("Table of Contents", 3)

' Store new bookmark in a variable to add nested bookmarks to
Dim summaryBookmark = pdf.Bookmarks.AddBookMarkAtEnd("Summary", 17)

' Add a sub-bookmark within the summary
Dim conclusionBookmark = summaryBookmark.Children.AddBookMarkAtStart("Conclusion", 18)

' Add another bookmark to end of highest-level bookmark list
pdf.Bookmarks.AddBookMarkAtEnd("References", 20)

pdf.SaveAs("existing.pdf")
VB   C#

Para ver el ejemplo de esquemas y marcadores en nuestra página de ejemplos de código, visite aquí.

Añadir y editar anotaciones

IronPDF tiene una gran cantidad de personalización en las anotaciones para PDFs. En el siguiente ejemplo se muestran sus posibilidades:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-16.cs
// create a new PDF or load and edit an existing document.
var pdf = PdfDocument.FromFile("existing.pdf");

// Create a PDF annotation object
var textAnnotation = new IronPdf.Annotations.TextAnnotation(PageIndex: 0)
{
    Title = "This is the major title",
    Contents = "This is the long 'sticky note' comment content...",
    Subject = "This is a subtitle",
    Icon = IronPdf.Annotations.TextAnnotation.AnnotationIcon.Help,
    Opacity = 0.9,
    Printable = false,
    Hidden = false,
    OpenByDefault = true,
    ReadOnly = false,
    Rotatable = true,
};

// Add the annotation "sticky note" to a specific page and location within any new or existing PDF.
pdf.Annotations.Add(textAnnotation);

pdf.SaveAs("existing.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Las anotaciones en PDF permiten añadir comentarios tipo "nota adhesiva" a las páginas PDF. La clase TextAnnotation permite añadir anotaciones mediante programación. Entre las funciones avanzadas de anotación de texto se incluyen el tamaño, la opacidad, los iconos y la edición.

Añadir fondos y primeros planos

Con IronPDF, podemos fusionar fácilmente 2 archivos PDF, utilizando uno como fondo o primer plano:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-17.cs
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.AddBackgroundPdf(@"MyBackground.pdf");
pdf.AddForegroundOverlayPdfToPage(0, @"MyForeground.pdf", 0);
pdf.SaveAs(@"C:\Path\To\Complete.pdf");
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.AddBackgroundPdf("MyBackground.pdf")
pdf.AddForegroundOverlayPdfToPage(0, "MyForeground.pdf", 0)
pdf.SaveAs("C:\Path\To\Complete.pdf")
VB   C#

Estampación y marca de agua

La posibilidad de hacer sellos y marcas de agua son características fundamentales de cualquier editor de PDF. IronPDF tiene una API increíble para crear una amplia gama de sellos, como sellos de imagen y sellos HTML. Todos ellos tienen un posicionamiento altamente personalizable mediante alineación y desplazamientos que pueden verse aquí:

Estampación y marca de agua

Clase abstracta Stamper

La clase abstracta Stamper se utiliza como parámetro para todos los métodos de estampación de IronPDF.

Hay muchas clases para cada caso de uso:

Propiedades de la clase Stamper

abstract class Stamper

└─── int : Opacity
└─── int : Rotation

└─── double : Scale

└─── Length : HorizontalOffset
└─── Length : VerticalOffset

└─── Length : MinWidth
└─── Length : MaxWidth

└─── Length : MinHeight
└─── Length : MaxHeight

└─── string : Hyperlink

└─── bool : IsStampBehindContent (default : false)

└─── HorizontalAlignment : HorizontalAlignment
│   │   Left
│   │   Center (default)
│   │   Right
│
└─── VerticalAlignment : VerticalAlignment
    │   Top
    │   Middle (default)
    │   Bottom

Ejemplos de estampación

A continuación mostramos cada una de las subclases de Stamper con un ejemplo de código.

Estampar texto en un PDF

Creación de dos Estampadores de Texto diferentes y aplicación de ambos:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-18.cs
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>");

TextStamper stamper1 = new TextStamper
{
    Text = "Hello World! Stamp One Here!",
    FontFamily = "Bungee Spice",
    UseGoogleFont = true,
    FontSize = 100,
    IsBold = true,
    IsItalic = true,
    VerticalAlignment = VerticalAlignment.Top
};

TextStamper stamper2 = new TextStamper()
{
    Text = "Hello World! Stamp Two Here!",
    FontFamily = "Bungee Spice",
    UseGoogleFont = true,
    FontSize = 30,
    VerticalAlignment = VerticalAlignment.Bottom
};

Stamper[] stampersToApply = { stamper1, stamper2 };
pdf.ApplyMultipleStamps(stampersToApply);
pdf.ApplyStamp(stamper2);
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Example HTML Document!</h1>")

Dim stamper1 As New TextStamper With {
	.Text = "Hello World! Stamp One Here!",
	.FontFamily = "Bungee Spice",
	.UseGoogleFont = True,
	.FontSize = 100,
	.IsBold = True,
	.IsItalic = True,
	.VerticalAlignment = VerticalAlignment.Top
}

Dim stamper2 As New TextStamper() With {
	.Text = "Hello World! Stamp Two Here!",
	.FontFamily = "Bungee Spice",
	.UseGoogleFont = True,
	.FontSize = 30,
	.VerticalAlignment = VerticalAlignment.Bottom
}

Dim stampersToApply() As Stamper = { stamper1, stamper2 }
pdf.ApplyMultipleStamps(stampersToApply)
pdf.ApplyStamp(stamper2)
VB   C#

Estampar una imagen en un PDF

Aplicación de un sello de imagen a un documento PDF existente en varias combinaciones de páginas:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-19.cs
var pdf = new PdfDocument("/attachments/2022_Q1_sales.pdf");

ImageStamper logoImageStamper = new ImageStamper("/assets/logo.png");

// Apply to every page, one page, or some pages
pdf.ApplyStamp(logoImageStamper);
pdf.ApplyStamp(logoImageStamper, 0);
pdf.ApplyStamp(logoImageStamper, new[] { 0, 3, 11 });
Dim pdf = New PdfDocument("/attachments/2022_Q1_sales.pdf")

Dim logoImageStamper As New ImageStamper("/assets/logo.png")

' Apply to every page, one page, or some pages
pdf.ApplyStamp(logoImageStamper)
pdf.ApplyStamp(logoImageStamper, 0)
pdf.ApplyStamp(logoImageStamper, { 0, 3, 11 })
VB   C#

Estampar HTML en un PDF

Escribe tu propio HTML para utilizarlo como sello:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-20.cs
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<p>Hello World, example HTML body.</p>");

HtmlStamper stamper = new HtmlStamper($"<p>Example HTML Stamped</p><div style='width:250pt;height:250pt;background-color:red;'></div>")
{
    HorizontalOffset = new Length(-3, MeasurementUnit.Inch),
    VerticalAlignment = VerticalAlignment.Bottom
};

pdf.ApplyStamp(stamper);
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<p>Hello World, example HTML body.</p>")

Dim stamper As New HtmlStamper($"<p>Example HTML Stamped</p><div style='width:250pt;height:250pt;background-color:red;'></div>")
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: HorizontalOffset = new Length(-3, MeasurementUnit.Inch), VerticalAlignment = VerticalAlignment.Bottom
	New Length(-3, MeasurementUnit.Inch), VerticalAlignment = VerticalAlignment.Bottom
	HorizontalOffset = New Length(-3, MeasurementUnit.Inch), VerticalAlignment
End If

pdf.ApplyStamp(stamper)
VB   C#

Estampar un código de barras en un PDF

Ejemplo de creación y estampación de un código de barras:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-21.cs
BarcodeStamper bcStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

bcStamp.HorizontalAlignment = HorizontalAlignment.Left;
bcStamp.VerticalAlignment = VerticalAlignment.Bottom;

var pdf = new PdfDocument("example.pdf");
pdf.ApplyStamp(bcStamp);
Dim bcStamp As New BarcodeStamper("IronPDF", BarcodeEncoding.Code39)

bcStamp.HorizontalAlignment = HorizontalAlignment.Left
bcStamp.VerticalAlignment = VerticalAlignment.Bottom

Dim pdf = New PdfDocument("example.pdf")
pdf.ApplyStamp(bcStamp)
VB   C#

Estampar un código QR en un PDF

Ejemplo de creación y estampación de un código QR:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-22.cs
BarcodeStamper qrStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);

qrStamp.Height = 50; // pixels
qrStamp.Width = 50; // pixels

qrStamp.HorizontalAlignment = HorizontalAlignment.Left;
qrStamp.VerticalAlignment = VerticalAlignment.Bottom;

var pdf = new PdfDocument("example.pdf");
pdf.ApplyStamp(qrStamp);
Dim qrStamp As New BarcodeStamper("IronPDF", BarcodeEncoding.QRCode)

qrStamp.Height = 50 ' pixels
qrStamp.Width = 50 ' pixels

qrStamp.HorizontalAlignment = HorizontalAlignment.Left
qrStamp.VerticalAlignment = VerticalAlignment.Bottom

Dim pdf = New PdfDocument("example.pdf")
pdf.ApplyStamp(qrStamp)
VB   C#

Añadir una marca de agua a un PDF

La marca de agua es un tipo de sello para cada página que puede aplicarse fácilmente mediante el método ApplyWatermark:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-23.cs
var pdf = new PdfDocument("/attachments/design.pdf");
string html = "<h1> Example Title <h1/>";
int rotation = 0;
int watermarkOpacity = 30;

pdf.ApplyWatermark(html, rotation, watermarkOpacity);
Dim pdf = New PdfDocument("/attachments/design.pdf")
Dim html As String = "<h1> Example Title <h1/>"
Dim rotation As Integer = 0
Dim watermarkOpacity As Integer = 30

pdf.ApplyWatermark(html, rotation, watermarkOpacity)
VB   C#

Para ver el ejemplo de marca de agua en nuestra página de ejemplos de código, visite aquí.

Aplicar sello a un PDF

Existen algunas sobrecargas del método ApplyStamp que pueden utilizarse para aplicar su Stamper a un PDF.

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-24.cs
var pdf = new PdfDocument("/assets/example.pdf");

// Apply one stamp to all pages
pdf.ApplyStamp(myStamper);

// Apply one stamp to a specific page
pdf.ApplyStamp(myStamper, 0);

// Apply one stamp to specific pages
pdf.ApplyStamp(myStamper, new[] { 0, 3, 5 });

// Apply a stamp array to all pages
pdf.ApplyMultipleStamps(stampArray);

// Apply a stamp array to a specific page
pdf.ApplyMultipleStamps(stampArray, 0);

// Apply a stamp array to specific pages
pdf.ApplyMultipleStamps(stampArray, new[] { 0, 3, 5 });

// And some Async versions of the above
await pdf.ApplyStampAsync(myStamper, 4);
await pdf.ApplyMultipleStampsAsync(stampArray);

// Additional Watermark apply method
string html = "<h1> Example Title <h1/>";
int rotation = 0;
int watermarkOpacity = 30;
pdf.ApplyWatermark(html, rotation, watermarkOpacity);
Dim pdf = New PdfDocument("/assets/example.pdf")

' Apply one stamp to all pages
pdf.ApplyStamp(myStamper)

' Apply one stamp to a specific page
pdf.ApplyStamp(myStamper, 0)

' Apply one stamp to specific pages
pdf.ApplyStamp(myStamper, { 0, 3, 5 })

' Apply a stamp array to all pages
pdf.ApplyMultipleStamps(stampArray)

' Apply a stamp array to a specific page
pdf.ApplyMultipleStamps(stampArray, 0)

' Apply a stamp array to specific pages
pdf.ApplyMultipleStamps(stampArray, { 0, 3, 5 })

' And some Async versions of the above
Await pdf.ApplyStampAsync(myStamper, 4)
Await pdf.ApplyMultipleStampsAsync(stampArray)

' Additional Watermark apply method
Dim html As String = "<h1> Example Title <h1/>"
Dim rotation As Integer = 0
Dim watermarkOpacity As Integer = 30
pdf.ApplyWatermark(html, rotation, watermarkOpacity)
VB   C#

Longitud Clase

La clase Length tiene dos propiedades: Unidad y Valor. Una vez que haya decidido qué unidad utilizar de la lista MeasurementUnit (por defecto esPorcentajede la página)y, a continuación, seleccione elValor` para decidir la cantidad de longitud que se utilizará como múltiplo de la unidad base.

Propiedades de la clase de longitud

class Length

└─── double : Value (default : 0)

└─── MeasurementUnit : Unit
   Inch
   Millimeter
   Centimeter
   Percentage (default)
   Pixel
   Points

Ejemplos de longitud

Crear una longitud

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-25.cs
new Length(value: 5, unit: MeasurementUnit.Inch); // 5 inches

new Length(value: 25, unit: MeasurementUnit.Pixel);// 25px

new Length(); // 0% of the page dimension because value is defaulted to zero and unit is defaulted to percentage

new Length(value: 20); // 20% of the page dimension
Dim tempVar As New Length(value:= 5, unit:= MeasurementUnit.Inch) ' 5 inches

Dim tempVar2 As New Length(value:= 25, unit:= MeasurementUnit.Pixel) ' 25px

Dim tempVar3 As New Length() ' 0% of the page dimension because value is defaulted to zero and unit is defaulted to percentage

Dim tempVar4 As New Length(value:= 20) ' 20% of the page dimension
VB   C#

Utilización de la longitud como parámetro

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-26.cs
HtmlStamper logoStamper = new HtmlStamper
{
    VerticalOffset = new Length(15, MeasurementUnit.Percentage),
    HorizontalOffset = new Length(1, MeasurementUnit.Inch)
    // set other properties...
};
Dim logoStamper As New HtmlStamper With {
	.VerticalOffset = New Length(15, MeasurementUnit.Percentage),
	.HorizontalOffset = New Length(1, MeasurementUnit.Inch)
}
VB   C#

Uso de formularios en PDF

Crear y editar formularios

Utilice IronPDF para crear un PDF con campos de formulario incrustados:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-27.cs
// Step 1.  Creating a PDF with editable forms from HTML using form and input tags
const string formHtml = @"
    <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=''>
            </form>
        </body>
    </html>";

// Instantiate Renderer
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf");

// Step 2. Reading and Writing PDF form values.
var formDocument = PdfDocument.FromFile("BasicForm.pdf");

// Read the value of the "firstname" field
var firstNameField = formDocument.Form.FindFormField("firstname");

// Read the value of the "lastname" field
var lastNameField = formDocument.Form.FindFormField("lastname");
' Step 1.  Creating a PDF with editable forms from HTML using form and input tags
Const formHtml As String = "
    <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=''>
            </form>
        </body>
    </html>"

' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
renderer.RenderHtmlAsPdf(formHtml).SaveAs("BasicForm.pdf")

' Step 2. Reading and Writing PDF form values.
Dim formDocument = PdfDocument.FromFile("BasicForm.pdf")

' Read the value of the "firstname" field
Dim firstNameField = formDocument.Form.FindFormField("firstname")

' Read the value of the "lastname" field
Dim lastNameField = formDocument.Form.FindFormField("lastname")
VB   C#

Para ver el ejemplo del formulario PDF en nuestra página de ejemplos de código, visite aquí.

Rellenar formularios existentes

Con IronPDF puede acceder fácilmente a todos los campos de formulario existentes en un PDF y rellenarlos para volver a guardarlos:

:path=/static-assets/pdf/content-code-examples/tutorials/csharp-edit-pdf-complete-28.cs
var formDocument = PdfDocument.FromFile("BasicForm.pdf");

// Set and Read the value of the "firstname" field
var firstNameField = formDocument.Form.FindFormField("firstname");
firstNameField.Value = "Minnie";
Console.WriteLine("FirstNameField value: {0}", firstNameField.Value);

// Set and Read the value of the "lastname" field
var lastNameField = formDocument.Form.FindFormField("lastname");
lastNameField.Value = "Mouse";
Console.WriteLine("LastNameField value: {0}", lastNameField.Value);

formDocument.SaveAs("FilledForm.pdf");
Dim formDocument = PdfDocument.FromFile("BasicForm.pdf")

' Set and Read the value of the "firstname" field
Dim firstNameField = formDocument.Form.FindFormField("firstname")
firstNameField.Value = "Minnie"
Console.WriteLine("FirstNameField value: {0}", firstNameField.Value)

' Set and Read the value of the "lastname" field
Dim lastNameField = formDocument.Form.FindFormField("lastname")
lastNameField.Value = "Mouse"
Console.WriteLine("LastNameField value: {0}", lastNameField.Value)

formDocument.SaveAs("FilledForm.pdf")
VB   C#

Para ver el ejemplo del formulario PDF en nuestra página de ejemplos de código, visite aquí.

Conclusión

La lista de ejemplos anterior demuestra que IronPDF tiene funciones clave que funcionan de forma inmediata cuando se trata de editar archivos PDF.

Si desea solicitar alguna función o tiene alguna pregunta general sobre IronPDF o las licencias, póngase en contacto con nosotros. contacte con nuestro equipo de asistencia. Estaremos encantados de ayudarle.