Cómo crear un PDF en C#
Crear PDFs programáticamente a menudo puede presentar desafíos significativos, ya sea que estés agregando encabezados y pies de página o navegando por problemas de compatibilidad. Afortunadamente, Iron Software simplifica este proceso consolidando varias funciones de creación de PDF en métodos intuitivos y fáciles de entender, lo que permite a los desarrolladores sumergirse directamente en sus proyectos.
Con IronPDF, puedes agregar formas, texto, imágenes, encabezados y pies de página. También tienes la flexibilidad de establecer la orientación, tamaño y metadatos del documento y exportar a varios estándares como PDF/UA y PDF/A. Además, integrar IronPDF en aplicaciones existentes para visualizar PDFs o imprimir documentos programáticamente es sencillo.
En este tutorial, exploraremos cada característica y mostraremos cómo IronPDF mejora la experiencia de desarrollo. Te permite crear componentes de código legibles y reutilizables que se pueden implementar en cualquier entorno y plataforma compatible.
Al final de este artículo, tendrás un sólido entendimiento de cómo crear PDFs estilísticos y únicos adaptados a tus necesidades con IronPDF.
Para comenzar a instalar IronPDF y seguir los ejemplos del tutorial descritos en este artículo, consulta esta guía rápida de instalación que te ayudará a configurar todo sin problemas.
Inicio rápido: crea tu primer PDF con IronPDFCrea fácilmente tu primer PDF en C# usando IronPDF con solo unas pocas líneas de código. Esta guía rápida te muestra cómo inicializar un documento PDF, agregar contenido y guardarlo, asegurando un inicio fluido para desarrolladores nuevos en la biblioteca. Sumérgete en la creación de PDFs en segundos y expande las capacidades de tu aplicación C# con facilidad.
-
1Instalar IronPDF con NuGet Package Manager
-
2Copie y ejecute este fragmento de código.
new IronPdf.PdfDocument(500, 500).SaveAs("output.pdf");New IronPdf.PdfDocument(500, 500).SaveAs("output.pdf")New IronPdf.PdfDocument(500, 500).SaveAs("output.pdf") -
3Despliegue para probar en su entorno real
Empiece a usar IronPDF en su proyecto hoy con una prueba gratuita
- Diseña PDFs Perfectos
- Personalización Total del PDF Fácil
- Conformidad con los Estándares
Diseñe su PDF perfecto
Crear PDF en blanco
Crear un PDF en blanco con IronPDF es intuitivo y sencillo, requiriendo solo un par de líneas de código. Primero iniciamos una nueva clase PdfDocument, le proporcionamos dimensiones y llamamos al método SaveAs para guardarlo. TextHeaderFooter
using IronPdf;
// Create a blank page, width and height in millimetres
PdfDocument pdf = new PdfDocument(270, 270);
pdf.SaveAs("blankPage.pdf");
Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Añadir encabezados y pies de página
Agrega encabezados y pies de página en la parte superior o inferior de tu PDF fácilmente usando IronPDF. IronPDF te permite agregar dos tipos de encabezados y pies de página. TextHeaderFooter es ideal para escenarios donde solo se requiere texto, como mostrar el número de página con interpolación de cadenas, por ejemplo, "{page} of {total-pages}" HtmlHeaderFooter. Al mismo tiempo, HtmlHeaderFooter es una variación más avanzada que permite a los desarrolladores personalizar el contenido HTML que colocan.
Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Cabecera y pie de página HTML
Al configurar el objeto HtmlHeaderFooter <center>, podemos personalizar dónde aparece el texto envolviendo los números de página en etiquetas span y agregando un recurso de imagen para asegurar que el documento sea único.
using IronPdf;
string headerHtml = @"
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a header!</h1>
</body>
</html>";
string footerHtml = @"
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a footer!</h1>
</body>
</html>";
// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
// Create header and footer
HtmlHeaderFooter htmlHeader = new HtmlHeaderFooter
{
HtmlFragment = headerHtml,
LoadStylesAndCSSFromMainHtmlDocument = true,
};
HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
{
HtmlFragment = footerHtml,
LoadStylesAndCSSFromMainHtmlDocument = true,
};
// Add to PDF
pdf.AddHtmlHeaders(htmlHeader);
pdf.AddHtmlFooters(htmlFooter);using IronPdf;
string headerHtml = @"
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a header!</h1>
</body>
</html>";
string footerHtml = @"
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a footer!</h1>
</body>
</html>";
// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
// Create header and footer
HtmlHeaderFooter htmlHeader = new HtmlHeaderFooter
{
HtmlFragment = headerHtml,
LoadStylesAndCSSFromMainHtmlDocument = true,
};
HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
{
HtmlFragment = footerHtml,
LoadStylesAndCSSFromMainHtmlDocument = true,
};
// Add to PDF
pdf.AddHtmlHeaders(htmlHeader);
pdf.AddHtmlFooters(htmlFooter);Imports IronPdf
Private headerHtml As String = "
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a header!</h1>
</body>
</html>"
Private footerHtml As String = "
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a footer!</h1>
</body>
</html>"
' Instantiate renderer and create PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Create header and footer
Private htmlHeader As New HtmlHeaderFooter With {
.HtmlFragment = headerHtml,
.LoadStylesAndCSSFromMainHtmlDocument = True
}
Private htmlFooter As New HtmlHeaderFooter With {
.HtmlFragment = footerHtml,
.LoadStylesAndCSSFromMainHtmlDocument = True
}
' Add to PDF
pdf.AddHtmlHeaders(htmlHeader)
pdf.AddHtmlFooters(htmlFooter)Imports IronPdf
Private headerHtml As String = "
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a header!</h1>
</body>
</html>"
Private footerHtml As String = "
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<h1>This is a footer!</h1>
</body>
</html>"
' Instantiate renderer and create PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Create header and footer
Private htmlHeader As New HtmlHeaderFooter With {
.HtmlFragment = headerHtml,
.LoadStylesAndCSSFromMainHtmlDocument = True
}
Private htmlFooter As New HtmlHeaderFooter With {
.HtmlFragment = footerHtml,
.LoadStylesAndCSSFromMainHtmlDocument = True
}
' Add to PDF
pdf.AddHtmlHeaders(htmlHeader)
pdf.AddHtmlFooters(htmlFooter)Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Cabecera y pie de página
El ejemplo a continuación usa TextHeaderFooter con valores de marcador de posición para indicar los números de página, URLs y fecha.
using IronPdf;
// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
CenterText = "This is the header!",
};
// Create text footer
TextHeaderFooter textFooter = new TextHeaderFooter
{
CenterText = "This is the footer!",
};
// Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader);
pdf.AddTextFooters(textFooter);
pdf.SaveAs("addTextHeaderFooter.pdf");using IronPdf;
// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
CenterText = "This is the header!",
};
// Create text footer
TextHeaderFooter textFooter = new TextHeaderFooter
{
CenterText = "This is the footer!",
};
// Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader);
pdf.AddTextFooters(textFooter);
pdf.SaveAs("addTextHeaderFooter.pdf");Imports IronPdf
' Instantiate renderer and create PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Create text header
Dim textHeader As New TextHeaderFooter With {
.CenterText = "This is the header!"
}
' Create text footer
Dim textFooter As New TextHeaderFooter With {
.CenterText = "This is the footer!"
}
' Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader)
pdf.AddTextFooters(textFooter)
pdf.SaveAs("addTextHeaderFooter.pdf")Imports IronPdf
' Instantiate renderer and create PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Create text header
Dim textHeader As New TextHeaderFooter With {
.CenterText = "This is the header!"
}
' Create text footer
Dim textFooter As New TextHeaderFooter With {
.CenterText = "This is the footer!"
}
' Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader)
pdf.AddTextFooters(textFooter)
pdf.SaveAs("addTextHeaderFooter.pdf")Junto con los campos mostrados arriba, también tenemos los siguientes valores de marcador de posición disponibles y serán reemplazados al renderizar: {page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}.
Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Añadir números de página
Similar al ejemplo anterior, podemos usar TextHeaderFooter o HtmlHeaderFooter para mostrar el número de página colocando valores de marcador de posición en el encabezado o pie de página, que se mostrarán cuando se renderice el documento.
using IronPdf;
// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter()
{
CenterText = "{page} of {total-pages}"
};
// Create html footer
HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
};
// Render a new PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
// Add header and footer
pdf.AddTextHeaders(textHeader);
pdf.AddHtmlFooters(htmlFooter);
pdf.SaveAs("pdfWithPageNumber.pdf");using IronPdf;
// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter()
{
CenterText = "{page} of {total-pages}"
};
// Create html footer
HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
{
HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
};
// Render a new PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
// Add header and footer
pdf.AddTextHeaders(textHeader);
pdf.AddHtmlFooters(htmlFooter);
pdf.SaveAs("pdfWithPageNumber.pdf");Imports IronPdf
' Create text header
Private textHeader As New TextHeaderFooter() With {.CenterText = "{page} of {total-pages}"}
' Create html footer
Private htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"}
' Render a new PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Add header and footer
pdf.AddTextHeaders(textHeader)
pdf.AddHtmlFooters(htmlFooter)
pdf.SaveAs("pdfWithPageNumber.pdf")Imports IronPdf
' Create text header
Private textHeader As New TextHeaderFooter() With {.CenterText = "{page} of {total-pages}"}
' Create html footer
Private htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"}
' Render a new PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
' Add header and footer
pdf.AddTextHeaders(textHeader)
pdf.AddHtmlFooters(htmlFooter)
pdf.SaveAs("pdfWithPageNumber.pdf")Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Incorporar imágenes con DataURI
Hay ocasiones en las que depender de un directorio de recursos es demasiado lento e ineficaz; por lo tanto, podemos incrustar imágenes con Data URIs como una solución alternativa. Aquí hay un breve fragmento de código sobre cómo hacerlo.
using IronPdf;
using System;
// Read byte from image file
var pngBinaryData = System.IO.File.ReadAllBytes("My_image.png");
// Convert bytes to base64
var ImgDataURI = @"data:image/png;base64," + Convert.ToBase64String(pngBinaryData);
// Import base64 to img tag
var ImgHtml = $"<img src='{ImgDataURI}'>";
ChromePdfRenderer Renderer = new ChromePdfRenderer();
// Render the HTML string
var pdf = Renderer.RenderHtmlAsPdf(ImgHtml);
pdf.SaveAs("datauri_example.pdf");using IronPdf;
using System;
// Read byte from image file
var pngBinaryData = System.IO.File.ReadAllBytes("My_image.png");
// Convert bytes to base64
var ImgDataURI = @"data:image/png;base64," + Convert.ToBase64String(pngBinaryData);
// Import base64 to img tag
var ImgHtml = $"<img src='{ImgDataURI}'>";
ChromePdfRenderer Renderer = new ChromePdfRenderer();
// Render the HTML string
var pdf = Renderer.RenderHtmlAsPdf(ImgHtml);
pdf.SaveAs("datauri_example.pdf");Imports IronPdf
Imports System
' Read byte from image file
Private pngBinaryData = System.IO.File.ReadAllBytes("My_image.png")
' Convert bytes to base64
Private ImgDataURI = "data:image/png;base64," & Convert.ToBase64String(pngBinaryData)
' Import base64 to img tag
Private ImgHtml = $"<img src='{ImgDataURI}'>"
Private Renderer As New ChromePdfRenderer()
' Render the HTML string
Private pdf = Renderer.RenderHtmlAsPdf(ImgHtml)
pdf.SaveAs("datauri_example.pdf")Imports IronPdf
Imports System
' Read byte from image file
Private pngBinaryData = System.IO.File.ReadAllBytes("My_image.png")
' Convert bytes to base64
Private ImgDataURI = "data:image/png;base64," & Convert.ToBase64String(pngBinaryData)
' Import base64 to img tag
Private ImgHtml = $"<img src='{ImgDataURI}'>"
Private Renderer As New ChromePdfRenderer()
' Render the HTML string
Private pdf = Renderer.RenderHtmlAsPdf(ImgHtml)
pdf.SaveAs("datauri_example.pdf")Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
OpenAI para PDF
IronPDF mejora la eficiencia y escalabilidad al soportar el modelo OpenAI para una rápida resumación, consulta y memorización, todo utilizando Microsoft Semantic Kernel. Aquí hay un breve fragmento de código sobre cómo usar OpenAI para resumir rápidamente los contenidos de un PDF.
using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Memory;
using System;
using System.Threading.Tasks;
// Setup OpenAI
var azureEndpoint = "<<enter your azure endpoint here>>";
var apiKey = "<<enter your azure API key here>>";
var builder = Kernel.CreateBuilder()
.AddAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)
.AddAzureOpenAIChatCompletion("oaichat", azureEndpoint, apiKey);
var kernel = builder.Build();
// Setup Memory
var memory_builder = new MemoryBuilder()
// optionally use new ChromaMemoryStore("http://127.0.0.1:8000") (see https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/09-memory-with-chroma.ipynb)
.WithMemoryStore(new VolatileMemoryStore())
.WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey);
var memory = memory_builder.Build();
// Initialize IronAI
IronDocumentAI.Initialize(kernel, memory);
License.LicenseKey = "<<enter your IronPdf license key here";
// Import PDF document
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Summarize the document
Console.WriteLine("Please wait while I summarize the document...");
string summary = await pdf.Summarize(); // optionally pass AI instance or use AI instance directly
Console.WriteLine($"Document summary: {summary}\n\n");using IronPdf;
using IronPdf.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Memory;
using System;
using System.Threading.Tasks;
// Setup OpenAI
var azureEndpoint = "<<enter your azure endpoint here>>";
var apiKey = "<<enter your azure API key here>>";
var builder = Kernel.CreateBuilder()
.AddAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)
.AddAzureOpenAIChatCompletion("oaichat", azureEndpoint, apiKey);
var kernel = builder.Build();
// Setup Memory
var memory_builder = new MemoryBuilder()
// optionally use new ChromaMemoryStore("http://127.0.0.1:8000") (see https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/09-memory-with-chroma.ipynb)
.WithMemoryStore(new VolatileMemoryStore())
.WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey);
var memory = memory_builder.Build();
// Initialize IronAI
IronDocumentAI.Initialize(kernel, memory);
License.LicenseKey = "<<enter your IronPdf license key here";
// Import PDF document
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Summarize the document
Console.WriteLine("Please wait while I summarize the document...");
string summary = await pdf.Summarize(); // optionally pass AI instance or use AI instance directly
Console.WriteLine($"Document summary: {summary}\n\n");Imports Microsoft.VisualBasic
Imports IronPdf
Imports IronPdf.AI
Imports Microsoft.SemanticKernel
Imports Microsoft.SemanticKernel.Connectors.OpenAI
Imports Microsoft.SemanticKernel.Memory
Imports System
Imports System.Threading.Tasks
' Setup OpenAI
Private azureEndpoint = "<<enter your azure endpoint here>>"
Private apiKey = "<<enter your azure API key here>>"
Private builder = Kernel.CreateBuilder().AddAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey).AddAzureOpenAIChatCompletion("oaichat", azureEndpoint, apiKey)
Private kernel = builder.Build()
' Setup Memory
Private memory_builder = (New MemoryBuilder()).WithMemoryStore(New VolatileMemoryStore()).WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)
Private memory = memory_builder.Build()
' Initialize IronAI
IronDocumentAI.Initialize(kernel, memory)
License.LicenseKey = "<<enter your IronPdf license key here"
' Import PDF document
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")
' Summarize the document
Console.WriteLine("Please wait while I summarize the document...")
Dim summary As String = Await pdf.Summarize() ' optionally pass AI instance or use AI instance directly
Console.WriteLine($"Document summary: {summary}" & vbLf & vbLf)Imports Microsoft.VisualBasic
Imports IronPdf
Imports IronPdf.AI
Imports Microsoft.SemanticKernel
Imports Microsoft.SemanticKernel.Connectors.OpenAI
Imports Microsoft.SemanticKernel.Memory
Imports System
Imports System.Threading.Tasks
' Setup OpenAI
Private azureEndpoint = "<<enter your azure endpoint here>>"
Private apiKey = "<<enter your azure API key here>>"
Private builder = Kernel.CreateBuilder().AddAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey).AddAzureOpenAIChatCompletion("oaichat", azureEndpoint, apiKey)
Private kernel = builder.Build()
' Setup Memory
Private memory_builder = (New MemoryBuilder()).WithMemoryStore(New VolatileMemoryStore()).WithAzureOpenAITextEmbeddingGeneration("oaiembed", azureEndpoint, apiKey)
Private memory = memory_builder.Build()
' Initialize IronAI
IronDocumentAI.Initialize(kernel, memory)
License.LicenseKey = "<<enter your IronPdf license key here"
' Import PDF document
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")
' Summarize the document
Console.WriteLine("Please wait while I summarize the document...")
Dim summary As String = Await pdf.Summarize() ' optionally pass AI instance or use AI instance directly
Console.WriteLine($"Document summary: {summary}" & vbLf & vbLf)Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Personalización completa de PDF
Orientación y rotación
Orientación
La propiedad PaperOrientation de la clase RenderingOptions te permite dictar cómo se representa la orientación del PDF. En este ejemplo, la configuramos en PdfPaperOrientation.Landscape para representar la orientación del PDF en modo horizontal.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Change paper orientation
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
pdf.SaveAs("landscape.pdf");
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Change paper orientation
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
pdf.SaveAs("landscape.pdf");Dim renderer As New ChromePdfRenderer()
' Change paper orientation
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
pdf.SaveAs("landscape.pdf")Dim renderer As New ChromePdfRenderer()
' Change paper orientation
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
pdf.SaveAs("landscape.pdf")Rotación
Para configurar la rotación de una página PDF, podemos usar el método SetPageRotation, junto con un PdfPageRotation enum como entrada, para rotar la página.
using IronPdf;
using IronPdf.Rendering;
using System.Collections.Generic;
PdfDocument pdf = PdfDocument.FromFile("landscape.pdf");
// Set all pages
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90);
// Set a single page
pdf.SetPageRotation(1, PdfPageRotation.Clockwise180);
// Set multiple pages
List<int> selectedPages = new List<int>() { 0, 3 };
pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270);
pdf.SaveAs("rotatedLandscape.pdf");using IronPdf;
using IronPdf.Rendering;
using System.Collections.Generic;
PdfDocument pdf = PdfDocument.FromFile("landscape.pdf");
// Set all pages
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90);
// Set a single page
pdf.SetPageRotation(1, PdfPageRotation.Clockwise180);
// Set multiple pages
List<int> selectedPages = new List<int>() { 0, 3 };
pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270);
pdf.SaveAs("rotatedLandscape.pdf");Imports IronPdf
Imports IronPdf.Rendering
Imports System.Collections.Generic
Private pdf As PdfDocument = PdfDocument.FromFile("landscape.pdf")
' Set all pages
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90)
' Set a single page
pdf.SetPageRotation(1, PdfPageRotation.Clockwise180)
' Set multiple pages
Dim selectedPages As New List(Of Integer)() From {0, 3}
pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270)
pdf.SaveAs("rotatedLandscape.pdf")Imports IronPdf
Imports IronPdf.Rendering
Imports System.Collections.Generic
Private pdf As PdfDocument = PdfDocument.FromFile("landscape.pdf")
' Set all pages
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90)
' Set a single page
pdf.SetPageRotation(1, PdfPageRotation.Clockwise180)
' Set multiple pages
Dim selectedPages As New List(Of Integer)() From {0, 3}
pdf.SetPageRotations(selectedPages, PdfPageRotation.Clockwise270)
pdf.SaveAs("rotatedLandscape.pdf")Para una explicación más detallada de cómo configurar la orientación y rotación del PDF y explorar su funcionalidad adicional, por favor consulta nuestra completa guía de cómo hacerlo.
Tamaño de papel personalizado
Establece las dimensiones del PDF configurando width y height usando el método SetCustomPaperSizeinCentimeters. IronPDF también admite configuraciones a tamaños estandarizados como A4 configurando la propiedad PaperSize a una lista de enums disponibles.
Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Tamaño de papel personalizado en Cm
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set custom paper size in cm
renderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15);
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>");
pdf.SaveAs("customPaperSize.pdf");using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set custom paper size in cm
renderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15);
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>");
pdf.SaveAs("customPaperSize.pdf");Imports IronPdf
Private renderer As New ChromePdfRenderer()
' Set custom paper size in cm
renderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15)
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>")
pdf.SaveAs("customPaperSize.pdf")Imports IronPdf
Private renderer As New ChromePdfRenderer()
' Set custom paper size in cm
renderer.RenderingOptions.SetCustomPaperSizeinCentimeters(15, 15)
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Custom Paper Size</h1>")
pdf.SaveAs("customPaperSize.pdf")Tamaño estándar del papel
En este ejemplo, también configuramos la propiedad PaperSize al enum de PdfPaperSize.A4.
using IronPdf;
using IronPdf.Rendering;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set paper size to A4
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>");
pdf.SaveAs("standardPaperSize.pdf");using IronPdf;
using IronPdf.Rendering;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set paper size to A4
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>");
pdf.SaveAs("standardPaperSize.pdf");Imports IronPdf
Imports IronPdf.Rendering
Private renderer As New ChromePdfRenderer()
' Set paper size to A4
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>")
pdf.SaveAs("standardPaperSize.pdf")Imports IronPdf
Imports IronPdf.Rendering
Private renderer As New ChromePdfRenderer()
' Set paper size to A4
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Standard Paper Size</h1>")
pdf.SaveAs("standardPaperSize.pdf")Para obtener una lista de tamaños estandarizados compatibles, por favor haz clic aquí.
Cumplimiento de normas
Exportar documentos en formato PDF/A en C#
Crea y exporta PDFs compatibles con los estándares PDF/UA usando el método SaveAsPdfUA.
using IronPdf;
// Create a PdfDocument object or open any PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Use the SaveAsPdfA method to save to file
pdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b);using IronPdf;
// Create a PdfDocument object or open any PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Use the SaveAsPdfA method to save to file
pdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b);Imports IronPdf
' Create a PdfDocument object or open any PDF File
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")
' Use the SaveAsPdfA method to save to file
pdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b)Imports IronPdf
' Create a PdfDocument object or open any PDF File
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")
' Use the SaveAsPdfA method to save to file
pdf.SaveAsPdfA("pdf-a3-wikipedia.pdf", PdfAVersions.PdfA3b)Para una explicación más detallada de este fragmento de código y explorar su funcionalidad adicional, por favor consulta nuestra guía completa.
Exportar documentos en formato PDF/UA en C#
Para convertir PDF a PDF/A en C#, también podemos usar la biblioteca IronPDF, que soporta los estándares más recientes de PDF/A, garantizando la integridad de tus archivos; similar al ejemplo anterior, llamamos a SaveAsPdfA para guardar el PDF en estándares PDF/A.
using IronPdf;
// Open PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Export as PDF/UA. Pass the document's natural language so assistive
// technologies announce the correct pronunciation.
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage: NaturalLanguages.English);using IronPdf;
// Open PDF File
PdfDocument pdf = PdfDocument.FromFile("wikipedia.pdf");
// Export as PDF/UA. Pass the document's natural language so assistive
// technologies announce the correct pronunciation.
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage: NaturalLanguages.English);Imports IronPdf
' Open PDF File
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")
' Export as PDF/UA. Pass the document's natural language so assistive
' technologies announce the correct pronunciation.
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage:=NaturalLanguages.English)Imports IronPdf
' Open PDF File
Dim pdf As PdfDocument = PdfDocument.FromFile("wikipedia.pdf")
' Export as PDF/UA. Pass the document's natural language so assistive
' technologies announce the correct pronunciation.
pdf.SaveAsPdfUA("pdf-ua-wikipedia.pdf", NaturalLanguage:=NaturalLanguages.English)En este ejemplo, guardamos el PDF en la variación PDF/A-3, usando el enum para PdfAVersions.
Para una lista completa de versiones PDF/A compatibles, por favor haz clic aquí.
Conclusión
Los breves ejemplos compartidos anteriormente muestran las impresionantes capacidades y características destacadas que puedes desbloquear al crear PDFs usando IronPDF.
Si deseas solicitar una característica o tienes preguntas generales sobre IronPDF o licencias, por favor contacta a nuestro equipo de soporte. Estaremos más que felices de asistirte.
Preguntas frecuentes
¿Para qué se utiliza IronPDF?
IronPDF se utiliza para crear, editar y gestionar archivos PDF en C#. Proporciona características como la adición de encabezados, pies de página, formas, texto, imágenes y la configuración de los metadatos del documento, lo que permite una integración sencilla en aplicaciones existentes.
¿Cómo puedo crear un PDF con un tamaño de página específico usando IronPDF?
Con IronPDF, puede establecer un tamaño de papel personalizado usando el método SetCustomPaperSizeinCentimeters o elegir entre tamaños estandarizados como A4 configurando la propiedad PaperSize a un enum disponible.
¿Puede IronPDF manejar diferentes estándares de archivos PDF?
Sí, IronPDF admite la exportación de documentos a varios estándares PDF como PDF/UA y PDF/A, garantizando el cumplimiento con los requisitos de accesibilidad y archivo.
¿Cómo puedo agregar encabezados y pies de página basados en HTML con IronPDF?
IronPDF le permite usar la clase HtmlHeaderFooter para añadir contenido HTML personalizable a los encabezados y pies de página. Esto permite la inclusión de diseños complejos y medios, incluidos texto e imágenes.
¿Cuáles son las opciones para agregar números de página en un PDF usando IronPDF?
IronPDF ofrece las clases TextHeaderFooter y HtmlHeaderFooter que le permiten incorporar valores de marcador de posición para números de página dentro de encabezados o pies de página, los cuales se renderizan apropiadamente en el PDF.
¿Cómo puede IronPDF ayudar a incrustar imágenes dentro de un PDF?
IronPDF admite la incrustación de imágenes directamente en los PDFs usando URIs de datos. Esto permite incluir imágenes sin depender de directorios externos de recursos, mejorando el rendimiento y la portabilidad.
¿IronPDF admite la resumión de documentos o operaciones basadas en inteligencia artificial?
Sí, IronPDF admite operaciones como resumión rápida, consulta y memorización al integrarse con Microsoft Semantic Kernel y modelos de OpenAI, mejorando la eficiencia y la escalabilidad.
¿Puedo rotar páginas o configurar la orientación del documento usando IronPDF?
IronPDF le permite establecer la rotación de páginas usando el método SetPageRotation con enums PdfPageRotation. Además, la orientación del documento puede configurarse mediante la propiedad RenderingOptions.PaperOrientation.
¿Cómo puedo empezar a crear un PDF con IronPDF?
Para empezar con IronPDF, solo necesita unas pocas líneas de código para inicializar un nuevo documento PDF usando la clase PdfDocument y usar el método SaveAs para crear un archivo PDF.
¿Dónde puedo encontrar guías y documentación más detalladas para IronPDF?
Las guías y documentación para IronPDF se pueden encontrar en su sitio web oficial, con enlaces incrustados dentro de los tutoriales para guiar a los usuarios a través de varias características e implementaciones.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.