Generador de PDF ASP .NET
- Convertir HTML a PDF en aplicaciones web, Windows o de consola ASP.NET
- Crear, editar y leer PDFs usando C# y VB .NET
- Soporta HTML, JS, CSS e Imágenes
Ejemplos de código ASP.NET C# y VB
using IronPdf;
using IronPdf.Engines.Chrome;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20);
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape;
renderer.RenderingOptions.Title = "My PDF Document Name";
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(50); // in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Supports margin customization!
renderer.RenderingOptions.MarginTop = 40; //millimeters
renderer.RenderingOptions.MarginLeft = 20; //millimeters
renderer.RenderingOptions.MarginRight = 20; //millimeters
renderer.RenderingOptions.MarginBottom = 40; //millimeters
// Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1; // use 2 if a cover page will be appended
// Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf");
using IronPdf;
using IronPdf.Engines.Chrome;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20);
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape;
renderer.RenderingOptions.Title = "My PDF Document Name";
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(50); // in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Supports margin customization!
renderer.RenderingOptions.MarginTop = 40; //millimeters
renderer.RenderingOptions.MarginLeft = 20; //millimeters
renderer.RenderingOptions.MarginRight = 20; //millimeters
renderer.RenderingOptions.MarginBottom = 40; //millimeters
// Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1; // use 2 if a cover page will be appended
// Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf");
using IronPdf;
using IronPdf.Engines.Chrome;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20);
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape;
renderer.RenderingOptions.Title = "My PDF Document Name";
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(50); // in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Supports margin customization!
renderer.RenderingOptions.MarginTop = 40; //millimeters
renderer.RenderingOptions.MarginLeft = 20; //millimeters
renderer.RenderingOptions.MarginRight = 20; //millimeters
renderer.RenderingOptions.MarginBottom = 40; //millimeters
// Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1; // use 2 if a cover page will be appended
// Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf");
Imports IronPdf
Imports IronPdf.Engines.Chrome
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20)
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape
renderer.RenderingOptions.Title = "My PDF Document Name"
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.RenderDelay(50) ' in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom
renderer.RenderingOptions.Zoom = 100
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Supports margin customization!
renderer.RenderingOptions.MarginTop = 40 'millimeters
renderer.RenderingOptions.MarginLeft = 20 'millimeters
renderer.RenderingOptions.MarginRight = 20 'millimeters
renderer.RenderingOptions.MarginBottom = 40 'millimeters
' Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1 ' use 2 if a cover page will be appended
' Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf")Imports IronPdf
Imports IronPdf.Engines.Chrome
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20)
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape
renderer.RenderingOptions.Title = "My PDF Document Name"
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.RenderDelay(50) ' in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom
renderer.RenderingOptions.Zoom = 100
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Supports margin customization!
renderer.RenderingOptions.MarginTop = 40 'millimeters
renderer.RenderingOptions.MarginLeft = 20 'millimeters
renderer.RenderingOptions.MarginRight = 20 'millimeters
renderer.RenderingOptions.MarginBottom = 40 'millimeters
' Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1 ' use 2 if a cover page will be appended
' Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf")Imports IronPdf
Imports IronPdf.Engines.Chrome
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Many rendering options to use to customize!
renderer.RenderingOptions.SetCustomPaperSizeInInches(12.5, 20)
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Landscape
renderer.RenderingOptions.Title = "My PDF Document Name"
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.RenderDelay(50) ' in milliseconds
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
renderer.RenderingOptions.FitToPaperMode = FitToPaperModes.Zoom
renderer.RenderingOptions.Zoom = 100
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Supports margin customization!
renderer.RenderingOptions.MarginTop = 40 'millimeters
renderer.RenderingOptions.MarginLeft = 20 'millimeters
renderer.RenderingOptions.MarginRight = 20 'millimeters
renderer.RenderingOptions.MarginBottom = 40 'millimeters
' Can set FirstPageNumber if you have a cover page
renderer.RenderingOptions.FirstPageNumber = 1 ' use 2 if a cover page will be appended
' Settings have been set, we can render:
renderer.RenderHtmlFileAsPdf("assets/wikipedia.html").SaveAs("output/my-content.pdf")IronPDF tiene como objetivo ser lo más flexible posible para el desarrollador.
En este Ejemplo de Tutorial de Generación de PDF en C#, mostramos el equilibrio entre proporcionar una API que automatice la funcionalidad interna y ofrecer una que te dé control.
IronPDF admite muchas personalizaciones para archivos PDF generados, incluyendo el tamaño de la página, márgenes de página, contenido de encabezado/pie de página, escala de contenido, conjuntos de reglas CSS y ejecución de JavaScript.
Queremos que los desarrolladores puedan controlar cómo Chrome convierte una página web en un PDF. La Visión General de la Clase ChromePdfRenderer hace esto posible.
Ejemplos de configuraciones disponibles en la clase ChromePdfRenderer incluyen configuraciones para márgenes, encabezados, pies de página, tamaño del papel y creación de formularios.
- El ejemplo de código anterior demuestra cómo crear un documento PDF a partir de una página web usando la biblioteca IronPDF.
- Esto implica configurar un
renderercon opciones específicas como tamaño del papel, márgenes, encabezado y pie de página. - La clase
ChromePdfRendererse utiliza pararenderla URL a un PDF. - El documento PDF resultante se guarda luego en un archivo llamado "output.pdf".
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
// Advanced Example with HTML Assets
// Load external html assets: Images, CSS and JavaScript.
// An optional BaseUrlOrPath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Con IronPDF, puedes crear nuevos documentos PDF a partir de cadenas HTML dentro de un proyecto .NET, y IronPDF se puede utilizar desde C#, F# y VB.NET. La clase ChromePdfRenderer renderiza el HTML con un motor Chromium incorporado, y la guía para HTML a PDF pixel-perfecto explica cómo hacer coincidir la salida con el navegador. El tutorial de HTML a PDF cubre el conjunto más amplio de características de conversión.
Los 4 pasos para convertir una cadena HTML a PDF
- Importe la biblioteca IronPDF.
- Inicialice un nuevo objeto
ChromePdfRenderer. - Utilice el método
RenderHtmlAsPdf. - Guarde el PDF utilizando
PdfDocument.SaveAs.
El primer paso para convertir una cadena HTML a un PDF en C# es instalar la biblioteca IronPDF en el proyecto. La directiva using IronPdf en la parte superior del ejemplo da acceso a las clases necesarias para la conversión de HTML a PDF.
El ejemplo crea una instancia de ChromePdfRenderer, que maneja la conversión de HTML a PDF. El método RenderHtmlAsPdf convierte una cadena HTML simple ("<h1>Hello World</h1>") en un documento PDF, y el método SaveAs escribe ese documento en disco.
En el ejemplo avanzado, IronPDF renderiza HTML que hace referencia a recursos externos como imágenes, archivos CSS y JavaScript. El argumento opcional BaseUrlOrPath de RenderHtmlAsPdf establece la carpeta o URL contra la cual se resuelven las rutas relativas, por lo que icons/iron.png carga desde la carpeta icons bajo esa ruta base. El PDF resultante, que incluye los recursos externos, se guarda con el mismo método. Para tamaño de papel, márgenes, encabezados, pies de página y otras configuraciones de salida, consulte la guía de opciones de renderizado.
Installation.EnableWebSecurity = true al renderizar HTML no confiable de usuarios. La seguridad web desactiva operaciones que requieren acceso al disco local o solicitudes cruzadas, por lo que los recursos locales, como la imagen en el ejemplo avanzado, no se cargan.using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Create a PDF from a URL or local file path
Dim pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Export to a file or Stream
pdf.SaveAs("url.pdf")Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Create a PDF from a URL or local file path
Dim pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Export to a file or Stream
pdf.SaveAs("url.pdf")Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Create a PDF from a URL or local file path
Dim pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")
' Export to a file or Stream
pdf.SaveAs("url.pdf")IronPDF hace que sea muy sencillo renderizar HTML desde URL existentes como documentos PDF. Hay un alto nivel de soporte para JavaScript, imágenes, formularios y CSS.
Renderizar PDFs desde URLs de ASP.NET que aceptan variables de cadena de consulta puede facilitar el desarrollo de PDFs como un esfuerzo colaborativo entre diseñadores y programadores.
Pasos para convertir URL a PDF en C#
- Descargar la biblioteca de conversión de URL a PDF de IronPDF
- Instale la biblioteca con NuGet para probar sus características
- Renderizar PDFs desde URLs de ASP.NET que aceptan variables de cadena de consulta usando
IronPDF - Crea un documento PDF directamente desde una URL con
IronPDF - Visualice y valide fácilmente su documento PDF de salida.
using IronPdf;
private void Form1_Load(object sender, EventArgs e)
{
//Changes the ASPX output into a pdf instead of HTML
IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
using IronPdf;
private void Form1_Load(object sender, EventArgs e)
{
//Changes the ASPX output into a pdf instead of HTML
IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
using IronPdf;
private void Form1_Load(object sender, EventArgs e)
{
//Changes the ASPX output into a pdf instead of HTML
IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
Imports IronPdf
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Changes the ASPX output into a pdf instead of HTML
AspxToPdf.RenderThisPageAsPdf()
End SubImports IronPdf
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Changes the ASPX output into a pdf instead of HTML
AspxToPdf.RenderThisPageAsPdf()
End SubImports IronPdf
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Changes the ASPX output into a pdf instead of HTML
AspxToPdf.RenderThisPageAsPdf()
End SubUsando la biblioteca IronPDF, las páginas web de ASP.NET se pueden renderizar en PDF en lugar de HTML al agregar una sola línea de código al evento Page_Load.
Este ejemplo muestra cómo IronPDF puede producir PDFs complejos y basados en datos que son diseñados y probados como HTML primero para mayor simplicidad.
La funcionalidad de conversión de ASPX a PDF de IronPDF te permite llamar a un único método dentro de una página ASPX y hacer que devuelva un PDF en lugar de HTML.
Puedes codificar el PDF para que se muestre "en el navegador," o se comporte como una descarga de archivo.
Aprenda a renderizar páginas ASPX como PDF con IronPDFusing IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Create a PDF from an existing HTML file using VB
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")
' Export to a file or Stream
pdf.SaveAs("output.pdf")Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Create a PDF from an existing HTML file using VB
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")
' Export to a file or Stream
pdf.SaveAs("output.pdf")Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Create a PDF from an existing HTML file using VB
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")
' Export to a file or Stream
pdf.SaveAs("output.pdf")IronPDF es una poderosa biblioteca .NET capaz de convertir archivos HTML en archivos PDF de alta calidad. Con IronPDF, puedes renderizar archivos HTML a PDF en solo un par de líneas, y gracias a su soporte para estándares web modernos, los archivos PDF resultantes serán perfectamente fieles. Aprovechar la potente función de IronPDF para convertir archivos HTML a PDF es fácil gracias a su uso de la clase ChromePdfRenderer, que maneja la conversión de HTML a PDF con facilidad.
Pasos para convertir archivos HTML a PDF con IronPDF
- Instale la biblioteca IronPDF de C# para convertir HTML a PDF
using IronPdf;var renderer = new ChromePdfRenderer();var pdf = renderer.RenderHtmlFileAsPdf("example.html");pdf.SaveAs("output.pdf");
Este código crea un nuevo archivo PDF que ha sido renderizado desde un archivo HTML. Para hacer esto, primero debemos asegurarnos de que la biblioteca IronPDF esté instalada e incluida en tu proyecto a través de la línea using IronPdf. Luego, inicie la clase ChromePdfRenderer, que proporciona la funcionalidad para renderizar contenido HTML como un PDF. Esta clase asegura que la calidad original del archivo HTML no se pierda en el proceso de conversión.
Una vez que se instancie renderer, puedes convertir un archivo HTML existente en un PDF utilizando el método RenderHtmlFileAsPdf. En este ejemplo, el archivo HTML "example.html" se pasa al método, creando un objeto PDF. Finalmente, para guardar el PDF generado, utiliza el método SaveAs, especificando el nombre y la ubicación de archivo deseados. Este sencillo proceso te permite generar fácilmente PDFs a partir de archivos HTML en tus aplicaciones C#.
using IronPdf;
var PdfOptions = new IronPdf.ChromePdfRenderOptions()
{
CreatePdfFormsFromHtml = true,
EnableJavaScript = false,
Title = "My ASPX Page Rendered as a PDF"
//.. many more options available
};
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions);
using IronPdf;
var PdfOptions = new IronPdf.ChromePdfRenderOptions()
{
CreatePdfFormsFromHtml = true,
EnableJavaScript = false,
Title = "My ASPX Page Rendered as a PDF"
//.. many more options available
};
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions);
using IronPdf;
var PdfOptions = new IronPdf.ChromePdfRenderOptions()
{
CreatePdfFormsFromHtml = true,
EnableJavaScript = false,
Title = "My ASPX Page Rendered as a PDF"
//.. many more options available
};
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions);
Imports IronPdf
Dim PdfOptions = New IronPdf.ChromePdfRenderOptions() With {
.CreatePdfFormsFromHtml = True,
.EnableJavaScript = False,
.Title = "My ASPX Page Rendered as a PDF"
'.. many more options available
}
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions)Imports IronPdf
Dim PdfOptions = New IronPdf.ChromePdfRenderOptions() With {
.CreatePdfFormsFromHtml = True,
.EnableJavaScript = False,
.Title = "My ASPX Page Rendered as a PDF"
'.. many more options available
}
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions)Imports IronPdf
Dim PdfOptions = New IronPdf.ChromePdfRenderOptions() With {
.CreatePdfFormsFromHtml = True,
.EnableJavaScript = False,
.Title = "My ASPX Page Rendered as a PDF"
'.. many more options available
}
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment, "MyPdfFile.pdf", PdfOptions)Este ejemplo demuestra cómo el usuario puede cambiar las opciones de impresión PDF para convertir un formulario en HTML.
La funcionalidad Guía de conversión de ASPX a PDF de IronPDF tiene muchas opciones disponibles para renderizar HTML a PDF desde una cadena o un archivo.
Dos opciones de particular importancia son:
- Permitiendo a los desarrolladores especificar si los formularios
HTMLdeben renderizarse como formularios interactivosPDFdurante la conversión. - Permitiendo a los desarrolladores especificar si
PDFdebe mostrarse "en el navegador" o como una descarga de archivo.
PDF con IronPDFusing IronPdf;
using System.IO;
using System.Linq;
// One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));
// Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");
// Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnails
using IronPdf;
using System.IO;
using System.Linq;
// One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));
// Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");
// Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnails
using IronPdf;
using System.IO;
using System.Linq;
// One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));
// Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");
// Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnails
Imports IronPdf
Imports System.IO
Imports System.Linq
' One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
Dim imageFiles = Directory.EnumerateFiles("assets").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))
' Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf")
' Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnailsImports IronPdf
Imports System.IO
Imports System.Linq
' One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
Dim imageFiles = Directory.EnumerateFiles("assets").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))
' Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf")
' Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnailsImports IronPdf
Imports System.IO
Imports System.Linq
' One or more images as IEnumerable. This example selects all JPEG images in a specific 'assets' folder.
Dim imageFiles = Directory.EnumerateFiles("assets").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))
' Converts the images to a PDF and save it.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf")
' Also see PdfDocument.RasterizeToImageFiles() method to flatten a PDF to images or thumbnailsDada una sola imagen ubicada en una computadora en C:\images\example.png, puede convertirla rápidamente en un documento PDF llamando al método IronPdf.ImageToPdfConverter.ImageToPdf con su ruta de archivo:
También puede convertir múltiples imágenes en un solo documento PDF pasando una colección de rutas de imágenes a ImageToPdfConverter.ImageToPdf:
Para explorar más sobre convertir imágenes a PDFs usando IronPDF para mejorar sus aplicaciones, o para descubrir la suite completa de herramientas para desarrolladores ofrecidas por Iron Software, incluyendo IronBarcode, IronOCR y más, visite el sitio web de Iron Software.
Aprenda a convertir imágenes a PDF con IronPDFSystem.IO.Directory.EnumerateFiles
ImageToPdfConverter.ImageToPdf
using IronPdf;
// Initiate PDF Renderer
var renderer = new ChromePdfRenderer();
// Add a header to every page easily
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 = IronSoftware.Drawing.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for header
// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for footer
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
using IronPdf;
// Initiate PDF Renderer
var renderer = new ChromePdfRenderer();
// Add a header to every page easily
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 = IronSoftware.Drawing.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for header
// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for footer
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
using IronPdf;
// Initiate PDF Renderer
var renderer = new ChromePdfRenderer();
// Add a header to every page easily
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 = IronSoftware.Drawing.FontTypes.Helvetica;
renderer.RenderingOptions.TextHeader.FontSize = 12;
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for header
// Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
renderer.RenderingOptions.TextFooter.FontSize = 10;
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
renderer.RenderingOptions.MarginTop = 25; //create 25mm space for footer
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
Imports IronPdf
' Initiate PDF Renderer
Dim renderer = New ChromePdfRenderer()
' Add a header to every page easily
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 = IronSoftware.Drawing.FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for header
' Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for footer
' Mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}Imports IronPdf
' Initiate PDF Renderer
Dim renderer = New ChromePdfRenderer()
' Add a header to every page easily
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 = IronSoftware.Drawing.FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for header
' Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for footer
' Mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}Imports IronPdf
' Initiate PDF Renderer
Dim renderer = New ChromePdfRenderer()
' Add a header to every page easily
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 = IronSoftware.Drawing.FontTypes.Helvetica
renderer.RenderingOptions.TextHeader.FontSize = 12
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for header
' Add a footer too
renderer.RenderingOptions.TextFooter.DrawDividerLine = True
renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial
renderer.RenderingOptions.TextFooter.FontSize = 10
renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
renderer.RenderingOptions.MarginTop = 25 'create 25mm space for footer
' Mergeable fields are:
' {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}Existen dos métodos a través de los cuales se pueden agregar encabezados y pies de página a un documento PDF. Se pueden agregar en un formato de texto clásico, con la opción de fusionar datos dinámicos. O, pueden agregarse a través del formato HTML mucho más flexible, que permite a los desarrolladores renderizar encabezados y pies de página dinámicos a través de su contenido HTML.
Pasos para añadir encabezados y pies de página a archivos PDF con IronPDF
Hoy veremos cómo puede agregar encabezados y pies de página de texto clásico en sus documentos PDF en solo unos pocos pasos simples. El primer paso para añadir encabezados y pies de página personalizados a tus documentos PDF es asegurarte de que la biblioteca IronPdf esté incluida en tu proyecto con la declaración using IronPdf;. Luego, instancia ChromePdfRenderer, que proporciona la funcionalidad para renderizar tu contenido HTML en documentos PDF de píxeles perfectos.
A continuación, configure el encabezado. La propiedad FirstPageNumber te permite especificar el número de página inicial, acomodando una página de portada si es necesario. Las propiedades TextHeader te permiten personalizar la apariencia, como dibujar una línea divisoria, centrar el texto (en este caso, la URL del documento), seleccionar el tipo y tamaño de fuente, y crear un margen en la parte superior de la página para el encabezado.
Después de configurar el encabezado, establece el pie de página usando las propiedades TextFooter. Similar al encabezado, puede dibujar una línea divisoria, elegir el tipo y tamaño de fuente, e incluir contenido dinámico como la fecha, hora actuales y números de página con el total de páginas. Finalmente, se crea un margen en la parte inferior de la página para acomodar el pie de página.
Siguiendo estos pasos, puede mejorar sus documentos PDF con encabezados y pies de página informativos que mejoran su profesionalismo y legibilidad.
Descubra cómo añadir encabezados y pies de página con IronPDFusing IronPdf;
using System;
// Instantiate Renderer
var renderer = new IronPdf.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
};
// Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25; //mm
// 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 Uri(@"C:\assets\images\").AbsoluteUri
};
// Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25; //mm
using IronPdf;
using System;
// Instantiate Renderer
var renderer = new IronPdf.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
};
// Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25; //mm
// 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 Uri(@"C:\assets\images\").AbsoluteUri
};
// Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25; //mm
using IronPdf;
using System;
// Instantiate Renderer
var renderer = new IronPdf.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
};
// Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25; //mm
// 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 Uri(@"C:\assets\images\").AbsoluteUri
};
// Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25; //mm
Imports IronPdf
Imports System
' Instantiate Renderer
Dim renderer = New IronPdf.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, 'millimeters
.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
.DrawDividerLine = True
}
' Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25 'mm
' 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, 'millimeters
.HtmlFragment = "<img src='logo.png'>",
.BaseUrl = New Uri("C:\assets\images\").AbsoluteUri
}
' Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25 'mmImports IronPdf
Imports System
' Instantiate Renderer
Dim renderer = New IronPdf.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, 'millimeters
.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
.DrawDividerLine = True
}
' Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25 'mm
' 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, 'millimeters
.HtmlFragment = "<img src='logo.png'>",
.BaseUrl = New Uri("C:\assets\images\").AbsoluteUri
}
' Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25 'mmImports IronPdf
Imports System
' Instantiate Renderer
Dim renderer = New IronPdf.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, 'millimeters
.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>",
.DrawDividerLine = True
}
' Use sufficient MarginBottom to ensure that the HtmlFooter does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginBottom = 25 'mm
' 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, 'millimeters
.HtmlFragment = "<img src='logo.png'>",
.BaseUrl = New Uri("C:\assets\images\").AbsoluteUri
}
' Use sufficient MarginTop to ensure that the HtmlHeader does not overlap with the main PDF page content.
renderer.RenderingOptions.MarginTop = 25 'mmLos encabezados y pies de página en HTML proporcionan un método flexible para crear encabezados y pies de página dinámicos para sus documentos PDF. Al agregar encabezados y pies de página a través de este método, los desarrolladores tienen control total sobre cómo se ven sus encabezados y pies de página, ya que se representan como documentos HTML independientes capaces de contener sus propios recursos y hojas de estilo.
Pasos para añadir encabezados y pies de página HTML personalizados en un PDF con IronPDF
Para comenzar, primero debe crear una instancia de la clase ChromePdfRenderer, que maneja la renderización de contenido HTML en un documento PDF con precisión de píxeles.
A continuación, defina un pie de página utilizando la clase HtmlHeaderFooter, donde especifica el MaxHeight, contenido HTML para el pie de página (que en nuestro caso incluye numeración de páginas), y la URL base para la resolución de imágenes. El pie de página está diseñado para mostrar la información de la página centrada.
Para evitar el solapamiento entre el pie de página y el contenido principal del PDF, establezca un margen inferior utilizando la propiedad MarginBottom. De manera similar, cree un encabezado que incluya una imagen (como un logotipo) usando la clase HtmlHeaderFooter. Aquí hemos configurado un BaseUrl al directorio que contiene su recurso de imagen, lo que permite una resolución de imagen adecuada durante la renderización.
Finalmente, use la propiedad MarginTop para establecer un margen superior que evite el solapamiento entre el encabezado y el contenido. Este ejemplo demuestra lo fácil que es implementar encabezados y pies de página HTML personalizados en sus documentos PDF con IronPDF.
using IronPdf;
using System;
// Step 1. Creating a PDF with editable forms from HTML using form and input tags
// Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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=''> <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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
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");
// 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");
using IronPdf;
using System;
// Step 1. Creating a PDF with editable forms from HTML using form and input tags
// Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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=''> <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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
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");
// 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");
using IronPdf;
using System;
// Step 1. Creating a PDF with editable forms from HTML using form and input tags
// Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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=''> <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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
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");
// 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");
Imports IronPdf
Imports System
' Step 1. Creating a PDF with editable forms from HTML using form and input tags
' Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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=''> <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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
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")
' 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")Imports IronPdf
Imports System
' Step 1. Creating a PDF with editable forms from HTML using form and input tags
' Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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=''> <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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
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")
' 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")Imports IronPdf
Imports System
' Step 1. Creating a PDF with editable forms from HTML using form and input tags
' Radio Button and Checkbox can also be implemented with input type 'radio' and 'checkbox'
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=''> <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='Stoke' value='Stoke'>
<label for='condition3'> Stoke</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
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")
' 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")Su empresa está gastando demasiado en suscripciones anuales para seguridad y cumplimiento de PDF. Considere IronSecureDoc, una Solución Integral de Seguridad para PDF, que ofrece soluciones para gestionar servicios SaaS como firma digital, censura, cifrado y protección, todo por un único pago. Explore la Documentación de IronSecureDoc.
Puede crear documentos PDF editables con IronPDF tan fácilmente como un documento normal. La clase PdfForm es una colección de campos de formulario editables por el usuario dentro de un documento PDF. Se puede implementar en su renderizado de PDF para convertirlo en un formulario o un documento editable.
Este ejemplo le muestra cómo crear formularios PDF editables en IronPDF.
Los PDFs con formularios editables se pueden crear desde HTML simplemente añadiendo etiquetas <form>, <input> y <textarea> a las partes del documento.
El método PdfDocument.Form.FindFormField se puede usar para leer y escribir el valor de cualquier campo de formulario. El atributo name del campo se asigna a ese campo en su HTML.
El objeto PdfDocument.Form se puede utilizar de dos maneras:
- Asignación de valores predeterminados: Permite establecer valores predeterminados para los campos del formulario que se mostrarán en visores de PDF como Adobe Reader.
- Lectura de la entrada del usuario: Después de que el usuario complete el formulario, se puede acceder a sus campos y leer los datos desde su aplicación.
En el ejemplo anterior, primero importamos la biblioteca IronPdf y definimos la estructura HTML de un formulario simple con campos de entrada para nombre y apellido, botones de radio para género y casillas de verificación para condiciones médicas. Usando el ChromePdfRenderer con CreatePdfFormsFromHtml habilitado, convertimos este contenido HTML en un documento PDF.
El PDF renderizado se guarda primero como "BasicForm.pdf". Luego se usa el objeto PdfDocument.Form para acceder y manipular los campos del formulario, aquí establecemos valores para los campos de nombre y apellido. Finalmente, el documento completado se guarda como "FilledForm.pdf", permitiendo que sea almacenado o compartido con campos editables incrustados.
using IronPdf;
using IronSoftware.Drawing;
var pdf = PdfDocument.FromFile("Example.pdf");
// Extract all pages to a folder as image files
pdf.RasterizeToImageFiles(@"C:\image\folder\*.png");
// Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles(@"C:\image\folder\example_pdf_image_*.jpg", 100, 80);
// Extract all pages as AnyBitmap objects
AnyBitmap[] pdfBitmaps = pdf.ToBitmap();
using IronPdf;
using IronSoftware.Drawing;
var pdf = PdfDocument.FromFile("Example.pdf");
// Extract all pages to a folder as image files
pdf.RasterizeToImageFiles(@"C:\image\folder\*.png");
// Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles(@"C:\image\folder\example_pdf_image_*.jpg", 100, 80);
// Extract all pages as AnyBitmap objects
AnyBitmap[] pdfBitmaps = pdf.ToBitmap();
using IronPdf;
using IronSoftware.Drawing;
var pdf = PdfDocument.FromFile("Example.pdf");
// Extract all pages to a folder as image files
pdf.RasterizeToImageFiles(@"C:\image\folder\*.png");
// Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles(@"C:\image\folder\example_pdf_image_*.jpg", 100, 80);
// Extract all pages as AnyBitmap objects
AnyBitmap[] pdfBitmaps = pdf.ToBitmap();
Imports IronPdf
Imports IronSoftware.Drawing
Dim pdf = PdfDocument.FromFile("Example.pdf")
' Extract all pages to a folder as image files
pdf.RasterizeToImageFiles("C:\image\folder\*.png")
' Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles("C:\image\folder\example_pdf_image_*.jpg", 100, 80)
' Extract all pages as AnyBitmap objects
Dim pdfBitmaps As AnyBitmap() = pdf.ToBitmap()Imports IronPdf
Imports IronSoftware.Drawing
Dim pdf = PdfDocument.FromFile("Example.pdf")
' Extract all pages to a folder as image files
pdf.RasterizeToImageFiles("C:\image\folder\*.png")
' Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles("C:\image\folder\example_pdf_image_*.jpg", 100, 80)
' Extract all pages as AnyBitmap objects
Dim pdfBitmaps As AnyBitmap() = pdf.ToBitmap()Imports IronPdf
Imports IronSoftware.Drawing
Dim pdf = PdfDocument.FromFile("Example.pdf")
' Extract all pages to a folder as image files
pdf.RasterizeToImageFiles("C:\image\folder\*.png")
' Dimensions and page ranges may be specified
pdf.RasterizeToImageFiles("C:\image\folder\example_pdf_image_*.jpg", 100, 80)
' Extract all pages as AnyBitmap objects
Dim pdfBitmaps As AnyBitmap() = pdf.ToBitmap()Para convertir un documento PDF en imágenes, llame al método RasterizeToImageFiles de IronPDF en un objeto PdfDocument. Un documento PDF puede ser cargado utilizando el método PdfDocument.FromFile o uno de los métodos disponibles para la generación de PDF para .NET Core.
RasterizeToImageFiles renderiza cada página del PDF como una imagen rasterizada. El primer argumento especifica el patrón de nomenclatura a utilizar para cada imagen. Se pueden utilizar argumentos opcionales para personalizar la calidad y las dimensiones de cada imagen. Otra opción permite que el método convierta páginas seleccionadas del PDF en imágenes.
La línea 13 del ejemplo de código destacado demuestra el método ToBitmap. Llame a este método en cualquier objeto PdfDocument para convertir rápidamente el PDF en objetos AnyBitmap que se pueden guardar en archivos o manipular según sea necesario.
Cómo convertir un PDF en imágenes en C#
- Instale la biblioteca de C# para convertir PDF a imagen
- Importar archivo PDF existente con el método
FromFile - Convertir PDF a imagen usando el método
RasterizeToImageFiles - Especifique el directorio de almacenamiento y el tamaño de la imagen
- Compruebe las imágenes de salida
using IronPdf;
using IronPdf.Signing;
// Cryptographically sign an existing PDF in 1 line of code!
new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");
/***** Advanced example for more control *****/
// 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 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature);
//Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");
using IronPdf;
using IronPdf.Signing;
// Cryptographically sign an existing PDF in 1 line of code!
new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");
/***** Advanced example for more control *****/
// 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 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature);
//Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");
using IronPdf;
using IronPdf.Signing;
// Cryptographically sign an existing PDF in 1 line of code!
new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");
/***** Advanced example for more control *****/
// 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 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature);
//Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
' Cryptographically sign an existing PDF in 1 line of code!
Call (New IronPdf.Signing.PdfSignature("Iron.p12", "123456")).SignPdfFile("any.pdf")
'/***** Advanced example for more control *****/
' Step 1. Create a PDF
Dim renderer = New ChromePdfRenderer()
Dim 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
Dim signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
' 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 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature)
'Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf")Imports IronPdf
Imports IronPdf.Signing
' Cryptographically sign an existing PDF in 1 line of code!
Call (New IronPdf.Signing.PdfSignature("Iron.p12", "123456")).SignPdfFile("any.pdf")
'/***** Advanced example for more control *****/
' Step 1. Create a PDF
Dim renderer = New ChromePdfRenderer()
Dim 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
Dim signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
' 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 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature)
'Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf")Imports IronPdf
Imports IronPdf.Signing
' Cryptographically sign an existing PDF in 1 line of code!
Call (New IronPdf.Signing.PdfSignature("Iron.p12", "123456")).SignPdfFile("any.pdf")
'/***** Advanced example for more control *****/
' Step 1. Create a PDF
Dim renderer = New ChromePdfRenderer()
Dim 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
Dim signature = New IronPdf.Signing.PdfSignature("Iron.pfx", "123456") With {
' 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 3. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.Sign(signature)
'Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf")Su empresa está gastando demasiado en suscripciones anuales para seguridad y cumplimiento de PDF. Considere IronSecureDoc, que proporciona soluciones para gestionar servicios SaaS como firma digital, censura, encriptación y protección, todo por un pago único. Explore la documentación de IronSecureDoc.
Firmar digitalmente un documento PDF ayuda a asegurar la integridad del documento al proporcionar un método de autenticación al propio PDF. Con IronPDF, tiene varias opciones cuando se trata de firmar un archivo PDF nuevo o existente. Estas incluyen firmar digitalmente el documento PDF con un certificado, agregar una versión gráfica de su firma manuscrita al PDF, estampar una imagen del certificado en el PDF, o simplemente crear un campo de formulario de firma en el PDF para pedir la firma del usuario.
Pasos para firmar digitalmente un PDF con IronPDF
El primer paso en este proceso es cargar o crear el PDF que queremos firmar. Para este ejemplo, creamos una nueva instancia de ChromePdfRenderer. Este es el potente motor de renderizado de IronPDF que se utiliza para renderizar HTML, CSS y JavaScript en PDF sin perder calidad. Luego usamos el método RenderHtmlAsPdf para renderizar nuestra cadena HTML en un documento PDF de alta calidad listo para ser firmado. El PDF resultante se almacena en la variable doc.
A continuación, necesitamos crear nuestra firma. Para este ejemplo, firmamos nuestro documento PDF con un certificado. PdfSignature representa el objeto de firma digital para firmar el PDF, y requiere la ruta al archivo .pfx que queremos usar para la firma y la contraseña para acceder a este archivo. Hemos incluido tres propiedades opcionales: SigningContact añade un correo electrónico o información de contacto a los metadatos de la firma, SigningLocation representa dónde se firma el documento, y SigningReason proporciona la razón por la cual se firma el documento.
A continuación, firmamos el documento PDF con el objeto PdfSignature que creamos. Al llamar al método Sign, aplicamos la firma al documento PDF en una línea sencilla. Se pueden aplicar múltiples certificados de firma al documento PDF utilizando este método.
Finalmente, guardamos el documento PDF firmado usando el método SaveAs, que guarda el PDF en la ubicación de archivo especificada.
using IronPdf;
using System.Collections.Generic;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Join Multiple Existing PDFs into a single document
var pdfs = new List<PdfDocument>();
pdfs.Add(PdfDocument.FromFile("A.pdf"));
pdfs.Add(PdfDocument.FromFile("B.pdf"));
pdfs.Add(PdfDocument.FromFile("C.pdf"));
var pdf = PdfDocument.Merge(pdfs);
pdf.SaveAs("merged.pdf");
// Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"));
// Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1);
pdf.SaveAs("merged.pdf");
// Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf");
foreach (var eachPdf in pdfs)
{
eachPdf.Dispose();
}
using IronPdf;
using System.Collections.Generic;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Join Multiple Existing PDFs into a single document
var pdfs = new List<PdfDocument>();
pdfs.Add(PdfDocument.FromFile("A.pdf"));
pdfs.Add(PdfDocument.FromFile("B.pdf"));
pdfs.Add(PdfDocument.FromFile("C.pdf"));
var pdf = PdfDocument.Merge(pdfs);
pdf.SaveAs("merged.pdf");
// Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"));
// Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1);
pdf.SaveAs("merged.pdf");
// Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf");
foreach (var eachPdf in pdfs)
{
eachPdf.Dispose();
}
using IronPdf;
using System.Collections.Generic;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Join Multiple Existing PDFs into a single document
var pdfs = new List<PdfDocument>();
pdfs.Add(PdfDocument.FromFile("A.pdf"));
pdfs.Add(PdfDocument.FromFile("B.pdf"));
pdfs.Add(PdfDocument.FromFile("C.pdf"));
var pdf = PdfDocument.Merge(pdfs);
pdf.SaveAs("merged.pdf");
// Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"));
// Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1);
pdf.SaveAs("merged.pdf");
// Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf");
foreach (var eachPdf in pdfs)
{
eachPdf.Dispose();
}
Imports IronPdf
Imports System.Collections.Generic
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Join Multiple Existing PDFs into a single document
Dim pdfs = New List(Of PdfDocument)()
pdfs.Add(PdfDocument.FromFile("A.pdf"))
pdfs.Add(PdfDocument.FromFile("B.pdf"))
pdfs.Add(PdfDocument.FromFile("C.pdf"))
Dim pdf = PdfDocument.Merge(pdfs)
pdf.SaveAs("merged.pdf")
' Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"))
' Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("merged.pdf")
' Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf")
For Each eachPdf In pdfs
eachPdf.Dispose()
NextImports IronPdf
Imports System.Collections.Generic
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Join Multiple Existing PDFs into a single document
Dim pdfs = New List(Of PdfDocument)()
pdfs.Add(PdfDocument.FromFile("A.pdf"))
pdfs.Add(PdfDocument.FromFile("B.pdf"))
pdfs.Add(PdfDocument.FromFile("C.pdf"))
Dim pdf = PdfDocument.Merge(pdfs)
pdf.SaveAs("merged.pdf")
' Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"))
' Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("merged.pdf")
' Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf")
For Each eachPdf In pdfs
eachPdf.Dispose()
NextImports IronPdf
Imports System.Collections.Generic
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
' Join Multiple Existing PDFs into a single document
Dim pdfs = New List(Of PdfDocument)()
pdfs.Add(PdfDocument.FromFile("A.pdf"))
pdfs.Add(PdfDocument.FromFile("B.pdf"))
pdfs.Add(PdfDocument.FromFile("C.pdf"))
Dim pdf = PdfDocument.Merge(pdfs)
pdf.SaveAs("merged.pdf")
' Add a cover page
pdf.PrependPdf(renderer.RenderHtmlAsPdf("<h1>Cover Page</h1><hr>"))
' Remove the last page from the PDF and save again
pdf.RemovePage(pdf.PageCount - 1)
pdf.SaveAs("merged.pdf")
' Copy pages 5-7 and save them as a new document.
pdf.CopyPages(4, 6).SaveAs("excerpt.pdf")
For Each eachPdf In pdfs
eachPdf.Dispose()
NextIronPDF ofrece más de 50 funciones para leer y editar PDFs. Las más populares son fusionar PDFs, clonar páginas y extraer texto de contenido rotado.
IronPDF también permite a sus usuarios añadir marcas de agua, rotar páginas, añadir anotaciones, firmar digitalmente páginas PDF, crear nuevos documentos PDF, adjuntar páginas de portada, personalizar tamaños de PDF y mucho más al generar y formatear archivos PDF. Además, admite la conversión de PDFs a todos los tipos de archivos de imagen convencionales, incluidos JPG, BMP, JPEG, GIF, PNG, TIFF, etc.
Lea el tutorial de edición de PDF en C# para aprender a utilizar IronPDF al máximo para modificar documentos PDF y así adaptarlos mejor a los requisitos del proyecto.
Cómo editar archivos PDF en C#
- Instalar la biblioteca C# que puede editar archivos PDF
- Utilizar el método
FromFilepara importar varios archivos PDF - Acceso y modificación de archivos PDF mediante API intuitivas en C#
- Guardar la versión actualizada como un nuevo PDF utilizando C#
- Ver el documento PDF recién editado
using IronPdf;
// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");
// Get file metadata
System.Collections.Generic.List<string> metadatakeys = pdf.MetaData.Keys(); // returns {"Title", "Creator", ...}
// Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title");
metadatakeys = pdf.MetaData.Keys(); // return {"Creator", ...} // title was deleted
// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = System.DateTime.Now;
// 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 = "sharable"; // password to open the pdf
pdf.SaveAs("secured.pdf");
using IronPdf;
// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");
// Get file metadata
System.Collections.Generic.List<string> metadatakeys = pdf.MetaData.Keys(); // returns {"Title", "Creator", ...}
// Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title");
metadatakeys = pdf.MetaData.Keys(); // return {"Creator", ...} // title was deleted
// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = System.DateTime.Now;
// 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 = "sharable"; // password to open the pdf
pdf.SaveAs("secured.pdf");
using IronPdf;
// Open an Encrypted File, alternatively create a new PDF from Html
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");
// Get file metadata
System.Collections.Generic.List<string> metadatakeys = pdf.MetaData.Keys(); // returns {"Title", "Creator", ...}
// Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title");
metadatakeys = pdf.MetaData.Keys(); // return {"Creator", ...} // title was deleted
// Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto";
pdf.MetaData.Keywords = "SEO, Friendly";
pdf.MetaData.ModifiedDate = System.DateTime.Now;
// 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 = "sharable"; // password to open the pdf
pdf.SaveAs("secured.pdf");
Imports IronPdf
' Open an Encrypted File, alternatively create a new PDF from Html
Dim pdf = PdfDocument.FromFile("encrypted.pdf", "password")
' Get file metadata
Dim metadatakeys As System.Collections.Generic.List(Of String) = pdf.MetaData.Keys() ' returns {"Title", "Creator", ...}
' Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title")
metadatakeys = pdf.MetaData.Keys() ' return {"Creator", ...} ' title was deleted
' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = System.DateTime.Now
' 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 = "sharable" ' password to open the pdf
pdf.SaveAs("secured.pdf")Imports IronPdf
' Open an Encrypted File, alternatively create a new PDF from Html
Dim pdf = PdfDocument.FromFile("encrypted.pdf", "password")
' Get file metadata
Dim metadatakeys As System.Collections.Generic.List(Of String) = pdf.MetaData.Keys() ' returns {"Title", "Creator", ...}
' Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title")
metadatakeys = pdf.MetaData.Keys() ' return {"Creator", ...} ' title was deleted
' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = System.DateTime.Now
' 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 = "sharable" ' password to open the pdf
pdf.SaveAs("secured.pdf")Imports IronPdf
' Open an Encrypted File, alternatively create a new PDF from Html
Dim pdf = PdfDocument.FromFile("encrypted.pdf", "password")
' Get file metadata
Dim metadatakeys As System.Collections.Generic.List(Of String) = pdf.MetaData.Keys() ' returns {"Title", "Creator", ...}
' Remove file metadata
pdf.MetaData.RemoveMetaDataKey("Title")
metadatakeys = pdf.MetaData.Keys() ' return {"Creator", ...} ' title was deleted
' Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = System.DateTime.Now
' 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 = "sharable" ' password to open the pdf
pdf.SaveAs("secured.pdf")IronPDF proporciona a los desarrolladores opciones sólidas de seguridad para PDF que permiten personalizar y configurar metadatos, contraseñas, permisos y más. Con las opciones de contraseñas, seguridad y metadatos de IronPDF, puede crear permisos personalizados y niveles de seguridad que se adapten a las necesidades de su documento PDF. Para ello, se utilizan clases como SecuritySettings y MetaData. Entre las opciones disponibles se incluyen impedir la impresión de documentos PDF, configurarlos como solo lectura, cifrarlos con 128 bits y protegerlos con contraseña.
Para configurar metadatos personalizados, se utiliza la clase MetaData para acceder a las distintas opciones de metadatos PDF y asignarles valores personalizados. Esto permite cambiar el autor, las palabras clave, la fecha de modificación y más. Los ajustes de seguridad personalizados permiten establecer contraseñas de usuario y propietario, permisos de impresión, el modo de solo lectura y más.
5 pasos para establecer contraseñas, metadatos y seguridad en PDF
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");System.Collections.Generic.List<string> metadatakeys = pdf.MetaData.Keys;var metadatakeys = pdf.MetaData.Keys;pdf.MetaData.Author = "Satoshi Nakamoto";pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
Para empezar a personalizar la seguridad de sus documentos PDF, primero debe cargar un PDF existente o crear uno nuevo. Aquí, hemos cargado un documento PDF existente protegido por contraseña e ingresado la contraseña necesaria para abrirlo. Una vez cargado el PDF, usamos pdf.MetaData.Keys para obtener sus metadatos actuales. Para eliminar los valores de metadatos existentes en el PDF, utilice el método RemoveMetaDataKey. Para establecer nuevos valores de metadatos, use pdf.MetaData.metadataField (por ejemplo, pdf.MetaData.Keywords) y asígnele el nuevo valor. Los campos de metadatos como Title y Keywords aceptan valores de cadena, mientras que el campo ModifiedDate acepta valores de fecha y hora.
A continuación, hemos establecido nuevos ajustes de seguridad mediante la clase SecuritySettings. Como puede ver, hay una variedad de ajustes disponibles. Esto le da control total sobre los permisos y niveles de seguridad de cada documento PDF con el que trabaja. Para acceder a estos ajustes, utilice pdf.SecuritySettings, seguido del ajuste que desea modificar. Por ejemplo, el método MakePdfDocumentReadOnly configura el documento PDF como solo lectura y cifra su contenido con 128 bits. Otras opciones de SecuritySettings incluyen:
AllowUserAnnotations: Controla si los usuarios pueden anotar el PDF o no.AllowUserPrinting: Controla los permisos de impresión para el documento.AllowUserFormData: Establece los permisos para que los usuarios puedan completar formularios.OwnerPassword: Establece la contraseña del propietario para el PDF, que se usa para deshabilitar o habilitar otras configuraciones de seguridad.UserPassword: Establece la contraseña de usuario para el PDF, que debe ingresarse para abrir o imprimir el documento.
Una vez que haya establecido los metadatos personalizados, las contraseñas y los ajustes de seguridad de su documento PDF, use el método pdf.SaveAs para guardar el PDF en la ubicación especificada.
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("watermarked.pdf");
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("watermarked.pdf");
using IronPdf;
// Stamps a Watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
pdf.SaveAs("watermarked.pdf");
Imports IronPdf
' Stamps a Watermark onto a new or existing PDF
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("watermarked.pdf")Imports IronPdf
' Stamps a Watermark onto a new or existing PDF
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("watermarked.pdf")Imports IronPdf
' Stamps a Watermark onto a new or existing PDF
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center)
pdf.SaveAs("watermarked.pdf")IronPDF proporciona métodos para 'marcar con agua' documentos PDF con HTML.
Utilizando el método ApplyWatermark, los desarrolladores pueden añadir una marca de agua basada en HTML a un archivo PDF. Como se muestra en el ejemplo anterior, el código HTML para la marca de agua es el primer argumento del método. Argumentos adicionales para ApplyWatermark controlan la opacidad, rotación y alineación de la marca de agua.
Use el método ApplyWatermark como una forma rápida de superponer una marca de agua HTML en un PDF. Por ejemplo, use ApplyWatermark para:
- Añadir marcas de agua (texto o imagen) en HTML a los PDFs
- Aplicar la marca de agua a lo largo de las páginas del PDF
- Establecer la opacidad de la marca de agua
- Ajustar la rotación y alineación de la marca de agua
Cómo añadir marcas de agua a archivos PDF en C#
- Descargar e instalar la biblioteca de IronPDF desde NuGet.
- Cree un nuevo
PdfDocumento utilice un archivoPdfDocumentexistente. - Llame al método
ApplyWatermarkpara añadir marcas de agua al PDF. - Exporte el archivo PDF llamando a
SaveAs.
Código de ejemplo C# para aplicar una marca de agua utilizando IronPDF
Asegúrese de haber instalado la biblioteca IronPDF en su proyecto. Puede encontrar instrucciones más detalladas en la página del paquete NuGet de IronPDF.
Explicación del código:
- Comenzamos importando la biblioteca
IronPdf, que proporciona todas las clases y métodos necesarios para la manipulación de PDF. - Un documento PDF es creado o cargado utilizando
PdfDocument.FromFile, especificando la ruta del archivo del PDF existente. - Se define el contenido HTML para la marca de agua. En este caso, la marca de agua muestra "Confidential" con un estilo específico.
- El método
ApplyWatermarkse usa para superponer la marca de agua en el PDF. Sus argumentos permiten personalización:- El primer argumento es el contenido HTML de la marca de agua.
opacity: Determina la transparencia de la marca de agua.- Los argumentos de alineación vertical y horizontal posicionan la marca de agua en la página.
- Finalmente, el método
SaveAsexporta el PDF modificado a un nuevo archivo.
En conclusión, el método ApplyWatermark de IronPDF permite un marcaje de agua sencillo en documentos PDF usando HTML. Este enfoque es flexible, adaptándose a varias necesidades de personalización para posicionamiento, estilo y opacidad de las marcas de agua.
using IronPdf;
// With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
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("complete.pdf");
using IronPdf;
// With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
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("complete.pdf");
using IronPdf;
// With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
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("complete.pdf");
Imports IronPdf
' With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
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("complete.pdf")Imports IronPdf
' With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
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("complete.pdf")Imports IronPdf
' With IronPDF, we can easily merge 2 PDF files using one as a background or foreground
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("complete.pdf")Es posible que desee utilizar un fondo y un primer plano específicos al crear y renderizar sus documentos PDF en IronPDF. En tal caso, puede usar un PDF existente o renderizado como fondo o primer plano para otro documento PDF. Esto es particularmente útil para la consistencia del diseño y la creación de plantillas.
Este ejemplo le muestra cómo usar un documento PDF como fondo o primer plano de otro documento PDF.
Puede hacer esto en C# cargando o creando un PDF de varias páginas como un objeto IronPdf.PdfDocument.
Puede agregar fondos usando PdfDocument.AddBackgroundPdf. Para obtener más detalles sobre los métodos de inserción de fondos, consulte la documentación de fondos IronPDF.PdfDocument; describe varios métodos de inserción de fondos y sus anulaciones. Esto agrega un fondo a cada página de su PDF de trabajo. El fondo se copia de una página en otro documento PDF.
Puede agregar primeros planos, también conocidos como "Overlays", usando PdfDocument.AddForegroundOverlayPdfToPage. Para obtener información detallada sobre los métodos de inserción de primeros planos, consulte la documentación de overlays IronPDF.PdfDocument.
Este código ilustra cómo integrar elementos de diseño adicionales sobre un PDF base usando IronPDF. Consulte siempre la documentación oficial para técnicas más avanzadas y opciones adicionales.
Explore nuestra guía sobre cómo añadir fondos y primeros planos
Soporte humano directo de nuestro equipo de desarrollo .NET
Ya sean consultas sobre productos, integración o licencias, el equipo de desarrollo de productos Iron está disponible para apoyar todas sus preguntas. Ponerse en contacto y comenzar un diálogo con Iron para aprovechar al máximo nuestra biblioteca en su proyecto.
Biblioteca .NET HTML a PDF C# & VB
IronPDF usa un motor Chromium .NET para renderizar páginas HTML a archivos PDF. No hay necesidad de usar APIs complejas para posicionar o diseñar PDFs: IronPDF soporta documentos web estándar HTML, ASPX, JS, CSS e Imágenes.Extraer y reutilizar texto e imágenes de PDF
IronPDF le permite leer contenido automáticamente de PDFs para inyección en sus aplicaciones C# y .NET y soluciones de almacenamiento de datos. Importe, migre e indexe contenido del almacenamiento de documentos PDF antiguo en su gestión de documentos y aplicaciones de procesos empresariales.Herramientas Elegantes para Editar Documentos PDF en .NET
Desde fusionar, dividir, hasta editar PDFs, use sus habilidades de desarrollo para producir exactamente el PDF correcto en el momento adecuado. IronPDF pone un creciente conjunto de características directamente en sus manos, dentro de su proyecto C#/VB.NET.
Funciona con documentos que ya tiene
Apunte a IronPDF sobre sus HTML, formularios ASPX, vistas MVC y archivos de imágenes existentes para convertirlos directamente a PDF. Esto utiliza sus activos y páginas web existentes para renderizar sus datos en formato PDF.Instalación rápida con Microsoft Visual Studio
IronPDF pone herramientas de generación y manipulación de PDF en sus propias manos rápidamente con soporte total para Intellisense y un instalador de Visual Studio. Ya sea instalando directamente desde NuGet con Visual Studio o descargando el DLL, estará listo en poco tiempo. Solo un DLL y sin dependencias.Compatible con:
Licencias y precios
Gratis licencias de desarrollo comunitario. Licencias comerciales desde $999.
Ver todas las opciones de licenciaTutoriales de PDF en C# de nuestra comunidad


ASPX a PDF | Tutorial de ASP.NET
Aprende cómo convertir cualquier página ASP.NET ASPX en un documento PDF en lugar de HTML usando solo una línea de código en C# o VB.NET…
Ver el ejemplo de Jacob de ASPX-A-PDF

HTML a PDF en C# | Tutorial de C Sharp y VB.NET
Para muchos, esta es la forma más eficiente de generar archivos PDF desde .NET, porque no hay una API adicional para aprender o un sistema de diseño complejo que navegar…
Ver los ejemplos de HTML-A-PDF de Jean

Creación y edición de PDF en VB.NET | PDF en VB.NET y ASP.NET
Aprende cómo crear y editar documentos PDF en aplicaciones y sitios web VB.NET. Un tutorial gratuito con ejemplos de código.…
Ver el Tutorial PDF de VB.NET de VeronicaMiles de desarrolladores usan IronPDF para...
Sistemas de contabilidad y finanzas
- # Recibos
- # Informes
- # Impresión de facturas
Digitalización de negocios
- # Documentación
- # Pedidos y etiquetado
- # Reemplazo de papel

Gestión de contenido empresarial
- # Producción de contenido
- # Gestión de documentos
- # Distribución de contenido

Aplicaciones de datos e informes
- # Seguimiento del rendimiento
- # Mapeo de tendencias
- # Informes

Miles de corporaciones, gobiernos, PYMEs y desarrolladores confían en los productos de Iron Software.
El equipo de Iron tiene más de 10 años de experiencia en el mercado de componentes de software .NET.








La solución de PDF para C# que ha estado buscando.
- - Crear, leer y editar PDFs. HTML a PDF para .NET.IRONPDF
- - Editar archivos Word DOCX. Sin Office Interop.IRONWORD
- - Editar archivos Excel y CSV. Sin Office Interop.IRONXL
- - Crear, leer y editar presentaciones. Sin Office Interop.IRONPPT
- - OCR en 125 idiomas.IRONOCR
- - Leer y escribir códigos QR y de barras.IRONBARCODE
- - Leer y escribir códigos QR.IRONQR
- - Comprimir y descomprimir archivos.IRONZIP
- - Imprimir documentos en .NET.IRONPRINT
- - Extraer datos estructurados de sitios web.IRONWEBSCRAPER
¿Listo para empezar?
Descargas de NuGet 22,198,312|Versión:2026.11recién lanzado
Cuando necesitas que tu PDF se parezca al HTML, rápido.








