Crear PDF en C# 14: Guía avanzada con Visual Studio Code en 2025
Crear PDF en C# es una habilidad esencial para los desarrolladores modernos de .NET, ya sea que estés construyendo informes financieros, generando documentos de salud o produciendo recibos de comercio electrónico. Con la biblioteca .NET PDF adecuada, puedes transformar contenido HTML en documentos PDF profesionales con solo unas pocas líneas de código, dándote control total sobre la estructura y apariencia del documento.
IronPDF es la biblioteca de creación de PDF para .NET más sencilla y usable por mucho - con una curva de aprendizaje increíblemente fácil que te permite generar PDFs en minutos, no en horas. Esta guía completa te mostrará exactamente cómo crear documentos PDF en C# usandoIronPDF- un poderoso generador de PDF en C# que produce resultados perfectos en píxeles y es compatible con todas las plataformas modernas de .NET, incluyendo la próxima versión .NET 10 en noviembre de 2025. Aunque este tutorial cubre todo, desde los casos de uso más simples hasta los escenarios más avanzados de generación de PDF, no te sientas intimidado - comienza desde el principio y avanza. Aprenderás múltiples formas de generar PDFs, desde simples cadenas HTML hasta complejos informes de varias páginas, además de cómo solucionar problemas comunes y optimizar el rendimiento para varias tareas de generación de PDF.
Inicio rápido: Cree su primer PDF en C# (Menos de 2 minutos)
¿Quieres generar un PDF ahora mismo? Vamos a crear un documento PDF simple pero funcional que demuestre el poder de la generación moderna de PDF en .NET. Primero, instala IronPDF a través del Gestor de Paquetes NuGet - este único paquete contiene todo lo que necesitas para comenzar a crear PDFs de inmediato.IronPDFes gratuito para desarrollo, por lo que puedes experimentar con todas las características antes de decidir sobre una licencia.
Install-Package IronPdf
Ahora vamos a crear contenido PDF usando C#:
using IronPdf;
// Instantiate the PDF generator - this is your gateway to PDF creation
var renderer = new ChromePdfRenderer();
// Create a PDF from HTML string - yes, it's really this simple!
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>");
// Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF generated successfully!");using IronPdf;
// Instantiate the PDF generator - this is your gateway to PDF creation
var renderer = new ChromePdfRenderer();
// Create a PDF from HTML string - yes, it's really this simple!
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>");
// Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF generated successfully!");Imports IronPdf
' Instantiate the PDF generator - this is your gateway to PDF creation
Private renderer = New ChromePdfRenderer()
' Create a PDF from HTML string - yes, it's really this simple!
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>PDF generated successfully!</p>")
' Save your newly created PDF document
pdf.SaveAs("my-first-pdf.pdf")
Console.WriteLine("PDF generated successfully!")¡Eso es todo! Acabas de crear tu primer documento PDF en C#. No es necesario aprender API complejas de PDF, no hay dependencias de servidor que instalar, no hay comandos de bajo nivel de PDF que dominar. Solo HTML de entrada, PDF de salida - la forma en que debería ser la generación de PDF. Pero esto es solo el comienzo - exploremos por qué este enfoque es tan poderoso y cómo puedes crear documentos PDF más sofisticados.
Cómo crear un PDF en C#: Una visión rápida
Para crear un PDF en C#, puedes utilizar bibliotecas de terceros como IronPDF, QuestPDF o PDFsharp. Estas bibliotecas ofrecen diversas funcionalidades, incluyendo la creación de PDFs desde cero, la conversión de HTML a PDF, y más.
He aquí un esquema general del proceso:
- Instalar una biblioteca PDF: Usa el Gestor de Paquetes NuGet en Visual Studio para instalar una biblioteca adecuada.
- Crear un nuevo documento PDF: Instanciar un objeto de documento PDF.
- Agregar contenido: Agregar páginas, texto, imágenes y otros elementos al documento.
- Guardar el documento: Especifica una ruta de archivo y guarda el PDF.
He aquí un ejemplo usando IronPDF:
using IronPdf;
public class Example
{
public static void CreatePdf()
{
// Create a new PDF document
var pdf = new ChromePdfRenderer();
// Add some text
string htmlContent = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>";
// Render HTML to PDF
var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
// Save the PDF
pdfDocument.SaveAs("MyDynamicPdf.pdf");
}
}using IronPdf;
public class Example
{
public static void CreatePdf()
{
// Create a new PDF document
var pdf = new ChromePdfRenderer();
// Add some text
string htmlContent = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>";
// Render HTML to PDF
var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
// Save the PDF
pdfDocument.SaveAs("MyDynamicPdf.pdf");
}
}Imports IronPdf
Public Class Example
Public Shared Sub CreatePdf()
' Create a new PDF document
Dim pdf = New ChromePdfRenderer()
' Add some text
Dim htmlContent As String = "<h1>Hello, PDF!</h1><p>This is a dynamically created PDF.</p>"
' Render HTML to PDF
Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
' Save the PDF
pdfDocument.SaveAs("MyDynamicPdf.pdf")
End Sub
End ClassAhora, vamos a profundizar en por qué los desarrolladores necesitan crear PDFs y exploraremos las muchas formas en queIronPDFhace que este proceso sea simple y poderoso.
¿Por qué los desarrolladores necesitan crear archivos PDF en C#?
Crear PDFs programáticamente en C# abre un mundo de posibilidades para automatizar la generación de documentos y agilizar los procesos empresariales.IronPDFha sido confiado por más de 14 millones de desarrolladores instalados en todo el mundo para lograr estas tareas porque proporciona una fiabilidad y facilidad de uso incomparables para construir PDFs en .NET. En finanzas, los desarrolladores usan C# para crear facturas PDF, estados de cuenta e informes regulatorios que requieren formato preciso y características de seguridad. Las organizaciones de salud generan registros de pacientes, resultados de laboratorios y formularios de seguros como PDFs para garantizar la integridad del documento y el cumplimiento con HIPAA. Las plataformas de comercio electrónico producen recibos PDF, etiquetas de envío y boletos con códigos QR (usando herramientas como IronQR) insertados directamente en el PDF. La capacidad de manipular documentos PDF programáticamente significa que puedes crear, modificar y asegurar documentos a escala sin intervención manual.
La belleza de usar una biblioteca .NET PDF moderna comoIronPDFes que integra sin problemas en los flujos de trabajo existentes de tu organización. Ya sea que estés convirtiendo documentos de Word de tus usuarios empresariales, transformando documentación Markdown de tu equipo de desarrollo, o generando PDFs a partir de informes basados en la web,IronPDFmaneja todo. Esta flexibilidad organizacional es la razón por la que las empresas eligen la generación de PDF programática en .NET - elimina la creación manual de documentos, reduce errores, asegura consistencia en todos los PDFs generados, y ahorra innumerables horas de tiempo a los empleados. En lugar de aprender sintaxis propietaria de PDF o posicionar cada elemento manualmente, puedes usar HTML y CSS para diseñar tus documentos. Este enfoque reduce drásticamente el tiempo de desarrollo y facilita mantener una marca consistente en todos tus PDFs producidos. Ya sea que estés creando una factura de una sola página o un informe complejo de varios capítulos, los principios permanecen los mismos - diseñar con HTML, generar PDFs con C#.
Cómo configurarIronPDFen su proyecto de C
Antes de sumergirte en la creación de PDFs, asegurémonos de que tu entorno de desarrollo esté correctamente configurado para una generación óptima de PDF.IronPDFadmite todas las versiones modernas de .NET, incluyendo .NET 8, .NET 9, y ya es compatible con la próxima versión .NET 10 programada para noviembre de 2025 (Iron Software trabaja en estrecha colaboración con la Fundación .NET y Microsoft para asegurar compatibilidad desde el primer día). El proceso de configuración es sencillo, pero entender tus opciones te ayuda a elegir el mejor enfoque para tus necesidades específicas.
Métodos de instalación
Método 1: Gestor de paquetes de Visual Studio (recomendado para principiantes)
La forma más fácil de comenzar conIronPDFes a través del Gestor de Paquetes NuGet integrado de Visual Studio. Esta interfaz gráfica facilita la búsqueda, instalación y gestión de tus dependencias de generación de PDF:
- Haz clic derecho en tu proyecto en el Explorador de Soluciones
- Selecciona "Administrar Paquetes NuGet"
- Haz clic en "Explorar" y busca "IronPDF"
- Selecciona el paquete IronPdf de Iron Software
- Haz clic en Instalar y acepta el acuerdo de licencia

Método 2: Consola del administrador de paquetes
Para los desarrolladores que prefieren herramientas de línea de comandos, la Consola del Administrador de Paquetes proporciona una forma rápida de instalar IronPDF:
Install-Package IronPdf
Método 3: .NET CLI (para desarrollo multiplataforma)
Si estás trabajando en macOS, Linux, o prefieres la CLI de .NET, utiliza este comando en tu directorio de proyecto:
dotnet add package IronPdf
Elegir el paquete adecuado
IronPDF ofrece diferentes paquetes de NuGet optimizados para varios escenarios de despliegue. Entender estas opciones te ayuda a minimizar el tamaño de despliegue y optimizar el rendimiento:
IronPdf: El paquete estándar que incluye todo lo que necesitas para Windows, macOS y Linux. Perfecto para la mayoría de aplicaciones.IronPdf.Slim: Un paquete base ligero que descarga componentes específicos de la plataforma en tiempo de ejecución. Ideal para despliegues en la nube donde el tamaño del paquete importa.IronPdf.Linux: Optimizado específicamente para despliegues en Linux con todas las dependencias requeridas pre-empaquetadas.IronPdf.MacOs: Diseñado para entornos macOS con soporte nativo para Apple Silicon.
Verificación de la instalación
Después de la instalación, verifica que todo funcione correctamente con esta prueba simple que crea un nuevo documento:
using IronPdf;
using System.IO;
// Test yourIronPDFinstallation
var renderer = new ChromePdfRenderer();
var testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>");
testPdf.SaveAs("test.pdf");
if (File.Exists("test.pdf"))
{
Console.WriteLine("IronPDF installed and working correctly!");
}using IronPdf;
using System.IO;
// Test yourIronPDFinstallation
var renderer = new ChromePdfRenderer();
var testPdf = renderer.RenderHtmlAsPdf("<p>Installation test successful!</p>");
testPdf.SaveAs("test.pdf");
if (File.Exists("test.pdf"))
{
Console.WriteLine("IronPDF installed and working correctly!");
}IRON VB CONVERTER ERROR developers@ironsoftware.com¿Cuáles son las diferentes formas de generar archivos PDF en C#?
IronPDF proporciona múltiples enfoques para construir documentos PDF, cada uno adecuado para diferentes escenarios y requisitos. Entender estos métodos te ayuda a elegir el enfoque más eficiente para tu caso de uso específico cuando necesitas producir PDFs en .NET. Ya sea que estés creando PDFs desde cero con cadenas HTML, convirtiendo archivos existentes, o capturando contenido web en vivo,IronPDFte cubre como un generador de PDF en C# integral. Exploremos cada método en detalle con ejemplos prácticos que demuestran aplicaciones del mundo real para creación de PDF en C#.
1. Crear PDF a partir de una cadena HTML (más flexible)
Crear PDFs desde cadenas HTML te da control completo sobre el contenido y el estilo de tu documento final cuando necesitas convertir contenido HTML al formato PDF. Este método es perfecto para generar informes dinámicos, facturas, o cualquier documento donde el contenido cambie basado en datos. Puedes convertir contenido HTML en PDFs profesionales usando las características modernas de HTML5 y CSS3, incluyendo flexbox y diseños de cuadrícula. La capacidad para convertir dinámicamente contenido HTML hace que este sea el enfoque más versátil para creación de PDF en C#:
using IronPdf;
using System;
using System.Linq;
var renderer = new ChromePdfRenderer();
// Build dynamic content with data
var customerName = "Acme Corporation";
var orderDate = DateTime.Now;
var items = new[] {
new { Name = "Widget Pro", Price = 99.99m },
new { Name = "Gadget Plus", Price = 149.99m }
};
// Create HTML with embedded data and modern CSS
var html = $@"
<html>
<head>
<style>
body {{
font-family: 'Segoe UI', Arial, sans-serif;
margin: 40px;
color: #333;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
border-bottom: 2px solid #0066cc;
padding-bottom: 20px;
}}
.items-table {{
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}}
.items-table th {{
background: #f0f0f0;
padding: 10px;
text-align: left;
}}
</style>
</head>
<body>
<div class='invoice-header'>
<div>
<h1>Invoice</h1>
<p>Customer: {customerName}</p>
</div>
<div>
<p>Date: {orderDate:yyyy-MM-dd}</p>
<p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>";
foreach (var item in items)
{
html += $@"
<tr>
<td>{item.Name}</td>
<td>${item.Price:F2}</td>
</tr>";
}
html += @"
</tbody>
</table>
</body>
</html>";
// Generate the PDF document
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf");using IronPdf;
using System;
using System.Linq;
var renderer = new ChromePdfRenderer();
// Build dynamic content with data
var customerName = "Acme Corporation";
var orderDate = DateTime.Now;
var items = new[] {
new { Name = "Widget Pro", Price = 99.99m },
new { Name = "Gadget Plus", Price = 149.99m }
};
// Create HTML with embedded data and modern CSS
var html = $@"
<html>
<head>
<style>
body {{
font-family: 'Segoe UI', Arial, sans-serif;
margin: 40px;
color: #333;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
border-bottom: 2px solid #0066cc;
padding-bottom: 20px;
}}
.items-table {{
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}}
.items-table th {{
background: #f0f0f0;
padding: 10px;
text-align: left;
}}
</style>
</head>
<body>
<div class='invoice-header'>
<div>
<h1>Invoice</h1>
<p>Customer: {customerName}</p>
</div>
<div>
<p>Date: {orderDate:yyyy-MM-dd}</p>
<p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>";
foreach (var item in items)
{
html += $@"
<tr>
<td>{item.Name}</td>
<td>${item.Price:F2}</td>
</tr>";
}
html += @"
</tbody>
</table>
</body>
</html>";
// Generate the PDF document
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf");Imports IronPdf
Imports System
Imports System.Linq
Private renderer = New ChromePdfRenderer()
' Build dynamic content with data
Private customerName = "Acme Corporation"
Private orderDate = DateTime.Now
Private items = {
New With {
Key .Name = "Widget Pro",
Key .Price = 99.99D
},
New With {
Key .Name = "Gadget Plus",
Key .Price = 149.99D
}
}
' Create HTML with embedded data and modern CSS
Private html = $"
<html>
<head>
<style>
body {{
font-family: 'Segoe UI', Arial, sans-serif;
margin: 40px;
color: #333;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
border-bottom: 2px solid #0066cc;
padding-bottom: 20px;
}}
.items-table {{
width: 100%;
margin-top: 30px;
border-collapse: collapse;
}}
.items-table th {{
background: #f0f0f0;
padding: 10px;
text-align: left;
}}
</style>
</head>
<body>
<div class='invoice-header'>
<div>
<h1>Invoice</h1>
<p>Customer: {customerName}</p>
</div>
<div>
<p>Date: {orderDate:yyyy-MM-dd}</p>
<p>Invoice #: INV-{orderDate:yyyyMMdd}-001</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>"
For Each item In items
html += $"
<tr>
<td>{item.Name}</td>
<td>${item.Price:F2}</td>
</tr>"
Next item
html &= "
</tbody>
</table>
</body>
</html>"
' Generate the PDF document
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs($"invoice-{orderDate:yyyyMMdd}.pdf")2. Generar PDF a partir de URL (Captura de página web)
A veces necesitas convertir páginas web existentes en documentos PDF - perfecto para archivar, informar, o crear versiones sin conexión de contenido en línea. La conversión de URL a PDF deIronPDFutiliza un motor Chromium real, asegurando que los sitios complejos cargados en JavaScript se rendericen correctamente. Este método es invaluable para crear instantáneas de paneles, guardar recibos en línea, o documentar informes basados en la web:

using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
// Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000; // 2 seconds
// Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = true;
// Capture a web page as PDF
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard-capture.pdf");
// For authenticated pages, you can set cookies
var cookieManager = renderer.RenderingOptions.CustomCookies;
cookieManager["session_id"] = "your-session-token";
// Capture authenticated content
var securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report");
securePdf.SaveAs("private-report.pdf");using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
// Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000; // 2 seconds
// Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = true;
// Capture a web page as PDF
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard-capture.pdf");
// For authenticated pages, you can set cookies
var cookieManager = renderer.RenderingOptions.CustomCookies;
cookieManager["session_id"] = "your-session-token";
// Capture authenticated content
var securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report");
securePdf.SaveAs("private-report.pdf");Imports IronPdf
Private renderer = New ChromePdfRenderer()
' Configure rendering options for optimal capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
' Wait for JavaScript to fully load (important for SPAs)
renderer.RenderingOptions.RenderDelay = 2000 ' 2 seconds
' Enable JavaScript execution
renderer.RenderingOptions.EnableJavaScript = True
' Capture a web page as PDF
Dim pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard")
pdf.SaveAs("dashboard-capture.pdf")
' For authenticated pages, you can set cookies
Dim cookieManager = renderer.RenderingOptions.CustomCookies
cookieManager("session_id") = "your-session-token"
' Capture authenticated content
Dim securePdf = renderer.RenderUrlAsPdf("https://app.example.com/private/report")
securePdf.SaveAs("private-report.pdf")3. Crear PDF a partir de un archivo HTML (generación basada en plantillas)
La generación de PDF basada en plantillas es ideal cuando tienes diseños complejos que los diseñadores pueden mantener por separado de tu código de aplicación. Al almacenar plantillas HTML como archivos, habilitas una separación limpia entre diseño y lógica. Este enfoque funciona excepcionalmente bien para generar documentos consistentes como certificados, contratos, o informes estandarizados:

using IronPdf;
using System.IO;
using System;
var renderer = new ChromePdfRenderer();
// Basic file conversion
var pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html");
pdf.SaveAs("certificate.pdf");
// Advanced: Using templates with asset directories
// Perfect when your HTML references images, CSS, or JavaScript files
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets");
var pdfWithAssets = renderer.RenderHtmlFileAsPdf(
"Templates/report-template.html",
basePath //IronPDFwill resolve relative paths from here
);
// Even better: Template with placeholders
var templateHtml = File.ReadAllText("Templates/contract-template.html");
templateHtml = templateHtml
.Replace("{{ClientName}}", "Tech Innovations Inc.")
.Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy"))
.Replace("{{ContractValue}}", "$50,000");
var contractPdf = renderer.RenderHtmlAsPdf(templateHtml);
contractPdf.SaveAs("contract-final.pdf");using IronPdf;
using System.IO;
using System;
var renderer = new ChromePdfRenderer();
// Basic file conversion
var pdf = renderer.RenderHtmlFileAsPdf("Templates/certificate-template.html");
pdf.SaveAs("certificate.pdf");
// Advanced: Using templates with asset directories
// Perfect when your HTML references images, CSS, or JavaScript files
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Templates", "Assets");
var pdfWithAssets = renderer.RenderHtmlFileAsPdf(
"Templates/report-template.html",
basePath //IronPDFwill resolve relative paths from here
);
// Even better: Template with placeholders
var templateHtml = File.ReadAllText("Templates/contract-template.html");
templateHtml = templateHtml
.Replace("{{ClientName}}", "Tech Innovations Inc.")
.Replace("{{ContractDate}}", DateTime.Now.ToString("MMMM dd, yyyy"))
.Replace("{{ContractValue}}", "$50,000");
var contractPdf = renderer.RenderHtmlAsPdf(templateHtml);
contractPdf.SaveAs("contract-final.pdf");IRON VB CONVERTER ERROR developers@ironsoftware.com4. Convertir Markdown a PDF
Markdown se ha convertido en el estándar para la documentación técnica, archivos README, y sistemas de gestión de contenido.IronPDFfacilita convertir contenido Markdown directamente a PDF, preservando el formato al crear documentos de aspecto profesional. Esta característica es particularmente valiosa para organizaciones que mantienen su documentación en formato Markdown - los desarrolladores pueden escribir documentación en su formato preferido, y el sistema puede automáticamente generar PDFs para distribución a clientes o partes interesadas.
using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert Markdown string to PDF
string markdownContent = @"
# Project Documentation
## Overview
This project demonstrates **PDF generation** from _Markdown_ content.
### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables
| Característica | Status |
|---------|--------|
| Markdown Support | |
| Table Rendering | |
| Code Blocks | |
```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
";
// Render Markdown as PDF
var pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent);
pdfFromMarkdown.SaveAs("documentation.pdf");
// Convert Markdown file to PDF
var pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md");
pdfFromFile.SaveAs("readme-pdf.pdf");using IronPdf;
var renderer = new ChromePdfRenderer();
// Convert Markdown string to PDF
string markdownContent = @"
# Project Documentation
## Overview
This project demonstrates **PDF generation** from _Markdown_ content.
### Features
- Easy conversion
- Preserves formatting
- Supports lists and tables
| Característica | Status |
|---------|--------|
| Markdown Support | |
| Table Rendering | |
| Code Blocks | |
```csharp
// Code blocks are preserved
var pdf = RenderMarkdownAsPdf(markdown);
\`\`\`
";
// Render Markdown as PDF
var pdfFromMarkdown = renderer.RenderMarkdownStringAsPdf(markdownContent);
pdfFromMarkdown.SaveAs("documentation.pdf");
// Convert Markdown file to PDF
var pdfFromFile = renderer.RenderMarkdownFileAsPdf("README.md");
pdfFromFile.SaveAs("readme-pdf.pdf");IRON VB CONVERTER ERROR developers@ironsoftware.comLa conversión de Markdown a PDF es particularmente útil para organizaciones que utilizan sistemas de control de versiones como Git. Tu flujo de trabajo de documentación completo puede ser automatizado - los desarrolladores actualizan archivos Markdown, los pipelines CI/CD automáticamente generan documentos PDF, y las partes interesadas reciben documentación profesionalmente formateada sin intervención manual. Esta integración sin problemas en los flujos de trabajo existentes es la razón por la que muchos equipos de desarrollo eligenIronPDFpara sus necesidades de documentación.
5. Convertir documentos de Word (DOCX) a PDF
Muchas empresas tienen documentos de Word existentes que necesitan ser convertidos a PDF para distribución o archivo.IronPDFproporciona conversión DOCX a PDF sin problemas que preserva el formato, las imágenes, e incluso características complejas como la combinación de correspondencia. Esta capacidad es transformadora para las organizaciones - los usuarios empresariales pueden continuar trabajando en el familiar Microsoft Word mientras el sistema automáticamente genera PDFs para distribución externa. La característica de conversión DOCX a PDF cubre la brecha entre los usuarios empresariales que prefieren Word y la necesidad de documentos PDF seguros e inalterables.
using IronPdf;
using System.Collections.Generic;
// Simple DOCX to PDF conversion
var docxRenderer = new DocxToPdfRenderer();
var pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx");
pdfFromDocx.SaveAs("proposal.pdf");
// Advanced: Mail merge functionality for mass document generation
var recipients = new List<Dictionary<string, string>>
{
new() { ["Name"] = "John Smith", ["Company"] = "Tech Corp", ["Date"] = "March 15, 2024" },
new() { ["Name"] = "Jane Doe", ["Company"] = "Innovation Inc", ["Date"] = "March 15, 2024" }
};
// Configure mail merge options
var options = new DocxPdfRenderOptions
{
MailMergeDataSource = recipients,
MailMergePrintAllInOnePdfDocument = false // Creates separate PDFs
};
// Generate personalized PDFs from template
foreach (var recipient in recipients)
{
var personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options);
personalizedPdf.SaveAs($"letter-{recipient["Name"].Replace(" ", "-")}.pdf");
}using IronPdf;
using System.Collections.Generic;
// Simple DOCX to PDF conversion
var docxRenderer = new DocxToPdfRenderer();
var pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx");
pdfFromDocx.SaveAs("proposal.pdf");
// Advanced: Mail merge functionality for mass document generation
var recipients = new List<Dictionary<string, string>>
{
new() { ["Name"] = "John Smith", ["Company"] = "Tech Corp", ["Date"] = "March 15, 2024" },
new() { ["Name"] = "Jane Doe", ["Company"] = "Innovation Inc", ["Date"] = "March 15, 2024" }
};
// Configure mail merge options
var options = new DocxPdfRenderOptions
{
MailMergeDataSource = recipients,
MailMergePrintAllInOnePdfDocument = false // Creates separate PDFs
};
// Generate personalized PDFs from template
foreach (var recipient in recipients)
{
var personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options);
personalizedPdf.SaveAs($"letter-{recipient["Name"].Replace(" ", "-")}.pdf");
}Imports IronPdf
Imports System.Collections.Generic
' Simple DOCX to PDF conversion
Private docxRenderer = New DocxToPdfRenderer()
Private pdfFromDocx = docxRenderer.RenderDocxAsPdf("proposal.docx")
pdfFromDocx.SaveAs("proposal.pdf")
' Advanced: Mail merge functionality for mass document generation
Dim recipients = New List(Of Dictionary(Of String, String)) From {
New() {
("Name") = "John Smith",
("Company") = "Tech Corp",
("Date") = "March 15, 2024"
},
New() {
("Name") = "Jane Doe",
("Company") = "Innovation Inc",
("Date") = "March 15, 2024"
}
}
' Configure mail merge options
Dim options = New DocxPdfRenderOptions With {
.MailMergeDataSource = recipients,
.MailMergePrintAllInOnePdfDocument = False
}
' Generate personalized PDFs from template
For Each recipient In recipients
Dim personalizedPdf = docxRenderer.RenderDocxAsPdf("letter-template.docx", options)
personalizedPdf.SaveAs($"letter-{recipient("Name").Replace(" ", "-")}.pdf")
Next recipientEsta característica de conversión DOCX es invaluable para automatizar los flujos de trabajo de documentos dentro de las organizaciones. Considera un equipo de ventas que crea propuestas en Word - con IronPDF, estas propuestas pueden ser automáticamente convertidas a PDF con marcas de agua, configuraciones de seguridad, y firmas digitales aplicadas programáticamente. La funcionalidad de combinación de correspondencia permite la generación masiva de documentos PDF personalizados - perfecto para crear miles de cartas, certificados o contratos personalizados sin intervención manual. Esta capacidad de integración es la razón por la queIronPDFes confiado por empresas en todo el mundo para manejar sus necesidades de automatización de documentos.
6. Convertir imágenes a PDF
Convertir imágenes a PDF es esencial para crear álbumes de fotos, compilaciones de documentos escaneados, o informes basados en imágenes.IronPDFadmite todos los principales formatos de imagen y proporciona opciones para controlar el diseño y la calidad:
using IronPdf;
using IronPdf.Imaging; // Install-Package IronPdf
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert single image to PDF
var imagePath = "product-photo.jpg";
var imageHtml = $@"
<html>
<body style='margin: 0; padding: 0;'>
<img src='{imagePath}' style='width: 100%; height: auto;' />
</body>
</html>";
var imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath));
imagePdf.SaveAs("product-catalog-page.pdf");
// Create multi-page PDF from multiple images
var imageFiles = Directory.GetFiles("ProductImages", "*.jpg");
var catalogHtml = "<html><body style='margin: 0;'>";
foreach (var image in imageFiles)
{
catalogHtml += $@"
<div style='page-break-after: always;'>
<img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
<p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
</div>";
}
catalogHtml += "</body></html>";
var catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages");
catalogPdf.SaveAs("product-catalog.pdf");using IronPdf;
using IronPdf.Imaging; // Install-Package IronPdf
using System.IO;
var renderer = new ChromePdfRenderer();
// Convert single image to PDF
var imagePath = "product-photo.jpg";
var imageHtml = $@"
<html>
<body style='margin: 0; padding: 0;'>
<img src='{imagePath}' style='width: 100%; height: auto;' />
</body>
</html>";
var imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath));
imagePdf.SaveAs("product-catalog-page.pdf");
// Create multi-page PDF from multiple images
var imageFiles = Directory.GetFiles("ProductImages", "*.jpg");
var catalogHtml = "<html><body style='margin: 0;'>";
foreach (var image in imageFiles)
{
catalogHtml += $@"
<div style='page-break-after: always;'>
<img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
<p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
</div>";
}
catalogHtml += "</body></html>";
var catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages");
catalogPdf.SaveAs("product-catalog.pdf");Imports IronPdf
Imports IronPdf.Imaging ' Install-Package IronPdf
Imports System.IO
Private renderer = New ChromePdfRenderer()
' Convert single image to PDF
Private imagePath = "product-photo.jpg"
Private imageHtml = $"
<html>
<body style='margin: 0; padding: 0;'>
<img src='{imagePath}' style='width: 100%; height: auto;' />
</body>
</html>"
Private imagePdf = renderer.RenderHtmlAsPdf(imageHtml, Path.GetDirectoryName(imagePath))
imagePdf.SaveAs("product-catalog-page.pdf")
' Create multi-page PDF from multiple images
Dim imageFiles = Directory.GetFiles("ProductImages", "*.jpg")
Dim catalogHtml = "<html><body style='margin: 0;'>"
For Each image In imageFiles
catalogHtml &= $"
<div style='page-break-after: always;'>
<img src='{Path.GetFileName(image)}' style='width: 100%; height: auto;' />
<p style='text-align: center;'>{Path.GetFileNameWithoutExtension(image)}</p>
</div>"
Next image
catalogHtml &= "</body></html>"
Dim catalogPdf = renderer.RenderHtmlAsPdf(catalogHtml, "ProductImages")
catalogPdf.SaveAs("product-catalog.pdf")7. Generar PDF a partir de páginas ASP.NET
Para aplicaciones web, generar PDFs desde tus vistas existentes proporciona una forma fluida de crear versiones descargables de contenido web. Esta capacidad de integración es crucial para organizaciones que necesitan crear PDFs desde sus aplicaciones web - ya sea portales de clientes generando estados de cuenta, paneles administrativos produciendo informes, o plataformas de e-learning creando certificados.IronPDFfunciona con todas las tecnologías ASP.NET incluyendo MVC, Razor Pages, y Blazor, lo que lo convierte en la opción perfecta para organizaciones ya invertidas en el ecosistema de Microsoft:
// Namespace: Microsoft.AspNetCore.Mvc
using Microsoft.AspNetCore.Mvc;
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// ASP.NET Core MVC Controller
public class ReportController : Controller
{
private readonly ChromePdfRenderer _pdfRenderer;
public ReportController()
{
_pdfRenderer = new ChromePdfRenderer();
}
public async Task<IActionResult> DownloadReport(int reportId)
{
// Get your report data
var reportData = await GetReportData(reportId);
// Render view to HTML string
var html = await RenderViewToStringAsync("Reports/MonthlyReport", reportData);
// Convert HTML content to PDF
var pdf = _pdfRenderer.RenderHtmlAsPdf(html);
// Return as file download
return File(
pdf.BinaryData,
"application/pdf",
$"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf"
);
}
private async Task<string> RenderViewToStringAsync(string viewName, object model)
{
ViewData.Model = model;
using var sw = new StringWriter();
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(
ControllerContext,
viewResult.View,
ViewData,
TempData,
sw,
new HtmlHelperOptions()
);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}// Namespace: Microsoft.AspNetCore.Mvc
using Microsoft.AspNetCore.Mvc;
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// ASP.NET Core MVC Controller
public class ReportController : Controller
{
private readonly ChromePdfRenderer _pdfRenderer;
public ReportController()
{
_pdfRenderer = new ChromePdfRenderer();
}
public async Task<IActionResult> DownloadReport(int reportId)
{
// Get your report data
var reportData = await GetReportData(reportId);
// Render view to HTML string
var html = await RenderViewToStringAsync("Reports/MonthlyReport", reportData);
// Convert HTML content to PDF
var pdf = _pdfRenderer.RenderHtmlAsPdf(html);
// Return as file download
return File(
pdf.BinaryData,
"application/pdf",
$"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf"
);
}
private async Task<string> RenderViewToStringAsync(string viewName, object model)
{
ViewData.Model = model;
using var sw = new StringWriter();
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(
ControllerContext,
viewResult.View,
ViewData,
TempData,
sw,
new HtmlHelperOptions()
);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}' Namespace: Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc
' Namespace: IronPdf
Imports IronPdf
' Namespace: System.Threading.Tasks
Imports System.Threading.Tasks
' Namespace: System.IO
Imports System.IO
' Namespace: System
Imports System
' ASP.NET Core MVC Controller
Public Class ReportController
Inherits Controller
Private ReadOnly _pdfRenderer As ChromePdfRenderer
Public Sub New()
_pdfRenderer = New ChromePdfRenderer()
End Sub
Public Async Function DownloadReport(ByVal reportId As Integer) As Task(Of IActionResult)
' Get your report data
Dim reportData = Await GetReportData(reportId)
' Render view to HTML string
Dim html = Await RenderViewToStringAsync("Reports/MonthlyReport", reportData)
' Convert HTML content to PDF
Dim pdf = _pdfRenderer.RenderHtmlAsPdf(html)
' Return as file download
Return File(pdf.BinaryData, "application/pdf", $"report-{reportId}-{DateTime.Now:yyyy-MM}.pdf")
End Function
Private Async Function RenderViewToStringAsync(ByVal viewName As String, ByVal model As Object) As Task(Of String)
ViewData.Model = model
Dim sw = New StringWriter()
Dim viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName)
Dim viewContext As New ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw, New HtmlHelperOptions())
viewResult.View.Render(viewContext, sw)
Return sw.GetStringBuilder().ToString()
End Function
End Class¿Cómo conseguir que mis PDF tengan un aspecto profesional?
Crear PDFs es una cosa - hacer que se vean profesionales es lo que distingue a tu aplicación cuando generas PDFs en .NET. Los documentos PDF profesionales requieren atención al detalle en el diseño, la tipografía, y la consistencia de marca para causar la impresión correcta. Con las opciones de estilo exhaustivas y características avanzadas de PDF de IronPDF, puedes crear documentos que coincidan perfectamente con la identidad corporativa usando este poderoso generador de PDF en C#. Las capacidades de conversión de HTML a PDF aseguran que tus documentos estilizados mantengan su atractivo visual cuando se produzcan como PDFs. Exploremos las características que transforman PDFs básicos en documentos pulidos y profesionales que impresionan a clientes y partes interesadas.
Cabeceras, pies de página y números de página
Los documentos profesionales necesitan encabezados y pies de página consistentes que proporcionen contexto y navegación.IronPDFofrece tanto opciones de texto simple como opciones complejas basadas en HTML para encabezados y pies de página. Esta flexibilidad es la razón por la que las organizaciones eligenIronPDFcuando necesitan crear documentos PDF de marca a escala. Puedes incluir contenido dinámico como números de página, fechas, y títulos de documentos - asegurando que cada PDF generado mantenga estándares profesionales:
using IronPdf;
using System;
var renderer = new ChromePdfRenderer();
// Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
Text = "Confidential Report - {date}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 12
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 10,
CenterText = true
};
// HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
Html = @"
<div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
<img src='logo.png' style='height: 40px;' />
<div style='text-align: center;'>
<h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
<p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
</div>
<div style='text-align: right; font-size: 11px; color: #666;'>
Generated: {date}<br/>
Department: Finance
</div>
</div>",
Height = 80,
LoadStylesAndCSSFromMainHtmlDocument = true
};
// Create your PDF with professional headers/footers
var html = @"<h1>Financial Overview</h1><p>Report content here...</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("professional-report.pdf");using IronPdf;
using System;
var renderer = new ChromePdfRenderer();
// Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
Text = "Confidential Report - {date}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 12
};
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages}",
DrawDividerLine = true,
Font = "Arial",
FontSize = 10,
CenterText = true
};
// HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
Html = @"
<div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
<img src='logo.png' style='height: 40px;' />
<div style='text-align: center;'>
<h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
<p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
</div>
<div style='text-align: right; font-size: 11px; color: #666;'>
Generated: {date}<br/>
Department: Finance
</div>
</div>",
Height = 80,
LoadStylesAndCSSFromMainHtmlDocument = true
};
// Create your PDF with professional headers/footers
var html = @"<h1>Financial Overview</h1><p>Report content here...</p>";
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("professional-report.pdf");Imports IronPdf
Imports System
Private renderer = New ChromePdfRenderer()
' Simple text header and footer with page numbers
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.Text = "Confidential Report - {date}",
.DrawDividerLine = True,
.Font = "Arial",
.FontSize = 12
}
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.Text = "Page {page} of {total-pages}",
.DrawDividerLine = True,
.Font = "Arial",
.FontSize = 10,
.CenterText = True
}
' HTML headers for complex layouts with logos
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
.Html = "
<div style='display: flex; justify-content: space-between; align-items: center; padding: 10px 40px;'>
<img src='logo.png' style='height: 40px;' />
<div style='text-align: center;'>
<h2 style='margin: 0; color: #333;'>Annual Report 2024</h2>
<p style='margin: 0; font-size: 12px; color: #666;'>Confidential</p>
</div>
<div style='text-align: right; font-size: 11px; color: #666;'>
Generated: {date}<br/>
Department: Finance
</div>
</div>",
.Height = 80,
.LoadStylesAndCSSFromMainHtmlDocument = True
}
' Create your PDF with professional headers/footers
Dim html = "<h1>Financial Overview</h1><p>Report content here...</p>"
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("professional-report.pdf")Estas opciones de encabezado y pie de página permiten a las organizaciones mantener la consistencia de marca en todos los PDFs generados. Ya sea que estés creando informes financieros o documentación técnica, los encabezados y pies de página profesionales aseguran que tus documentos cumplan con los estándares corporativos.
Configuración avanzada de páginas y control de diseño
El control sobre el diseño de página es crucial para crear documentos que se impriman correctamente y se vean profesionales en todos los dispositivos.IronPDFproporciona amplias opciones para la configuración de página, incluyendo tamaños personalizados, orientaciones, y márgenes:
var renderer = new ChromePdfRenderer();
// Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
// Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297); // A4
// Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100; // 0-100 scalevar renderer = new ChromePdfRenderer();
// Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
// Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297); // A4
// Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100; // 0-100 scaleDim renderer = New ChromePdfRenderer()
' Configure page setup for professional printing
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
' Set margins in millimeters for precise control
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
' Enable background colors and images (important for branding)
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Use screen media type for vibrant colors
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen
' Custom page size for special documents
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(210, 297) ' A4
' Enable high-quality rendering
renderer.RenderingOptions.RenderQuality = 100 ' 0-100 scaleTrabajo con fuentes y tipografía
La tipografía juega un papel crucial en la profesionalidad del documento.IronPDFadmite fuentes web, fuentes personalizadas, y características avanzadas de tipografía:
var renderer = new ChromePdfRenderer();
// HTML with custom fonts and typography
var html = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
<style>
@font-face {
font-family: 'CustomBrand';
src: url('BrandFont.ttf') format('truetype');
}
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #333;
}
h1 {
font-family: 'CustomBrand', Georgia, serif;
font-size: 28pt;
color: #0066cc;
letter-spacing: -0.5px;
}
.quote {
font-style: italic;
font-size: 14pt;
color: #666;
border-left: 4px solid #0066cc;
padding-left: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>This document demonstrates professional typography.</p>
<div class='quote'>
"Excellence in typography enhances readability and professionalism."
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts");
pdf.SaveAs("typography-demo.pdf");var renderer = new ChromePdfRenderer();
// HTML with custom fonts and typography
var html = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
<style>
@font-face {
font-family: 'CustomBrand';
src: url('BrandFont.ttf') format('truetype');
}
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #333;
}
h1 {
font-family: 'CustomBrand', Georgia, serif;
font-size: 28pt;
color: #0066cc;
letter-spacing: -0.5px;
}
.quote {
font-style: italic;
font-size: 14pt;
color: #666;
border-left: 4px solid #0066cc;
padding-left: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>This document demonstrates professional typography.</p>
<div class='quote'>
"Excellence in typography enhances readability and professionalism."
</div>
</body>
</html>";
var pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts");
pdf.SaveAs("typography-demo.pdf");Dim renderer = New ChromePdfRenderer()
' HTML with custom fonts and typography
Dim html = "
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap' rel='stylesheet'>
<style>
@font-face {
font-family: 'CustomBrand';
src: url('BrandFont.ttf') format('truetype');
}
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 11pt;
line-height: 1.6;
color: #333;
}
h1 {
font-family: 'CustomBrand', Georgia, serif;
font-size: 28pt;
color: #0066cc;
letter-spacing: -0.5px;
}
.quote {
font-style: italic;
font-size: 14pt;
color: #666;
border-left: 4px solid #0066cc;
padding-left: 20px;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Professional Document</h1>
<p>This document demonstrates professional typography.</p>
<div class='quote'>
"Excellence in typography enhances readability [and] professionalism." </div> </body> </html>"
Dim pdf = renderer.RenderHtmlAsPdf(html, "Assets/Fonts")
pdf.SaveAs("typography-demo.pdf")Ejemplo del mundo real: ¿Cómo genero una factura en PDF?
Creemos un generador de facturas completo y listo para producción que demuestre las mejores prácticas para crear documentos PDF en aplicaciones del mundo real. Este ejemplo muestra por qué miles de empresas eligenIronPDFcomo su generador de PDF en C# para necesidades de generación de facturas - combina enlace de datos, estilo profesional, y estructura adecuada del documento de una manera que es tanto poderosa como mantenible. Implementaciones similares son utilizadas por plataformas de comercio electrónico para generar millones de facturas mensuales, demostrando la escalabilidad de la generación de PDF programática en .NET. Puedes adaptar este código para tus propios tareas de creación de PDF:
using IronPdf;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class InvoiceGenerator
{
private readonly ChromePdfRenderer _renderer;
public InvoiceGenerator()
{
_renderer = new ChromePdfRenderer();
ConfigureRenderer();
}
private void ConfigureRenderer()
{
// Professional page setup
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
_renderer.RenderingOptions.MarginTop = 25;
_renderer.RenderingOptions.MarginBottom = 25;
_renderer.RenderingOptions.MarginLeft = 25;
_renderer.RenderingOptions.MarginRight = 25;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Add footer with page numbers
_renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages} | Invoice generated on {date}",
FontSize = 9,
Font = "Arial",
CenterText = true
};
}
public void CreateInvoice(Invoice invoice)
{
var html = GenerateInvoiceHtml(invoice);
var pdf = _renderer.RenderHtmlAsPdf(html);
// Add metadata to the final document
pdf.MetaData.Title = $"Invoice {invoice.Number}";
pdf.MetaData.Author = "Your Company Name";
pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}";
pdf.MetaData.Keywords = "invoice, billing, payment";
pdf.MetaData.CreationDate = DateTime.Now;
// Save the PDF document
var fileName = $"Invoice-{invoice.Number}.pdf";
pdf.SaveAs(fileName);
Console.WriteLine($"PDF generated successfully: {fileName}");
}
private string GenerateInvoiceHtml(Invoice invoice)
{
var itemsHtml = string.Join("", invoice.Items.Select(item => $@"
<tr>
<td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
</tr>"));
return $@"
<html>
<head>
<style>
* {{ box-sizing: border-box; }}
body {{
font-family: 'Segoe UI', Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}}
.invoice-container {{
max-width: 800px;
margin: 0 auto;
padding: 40px;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 3px solid #0066cc;
}}
.company-details {{
flex: 1;
}}
.company-details h1 {{
color: #0066cc;
margin: 0 0 10px 0;
font-size: 28px;
}}
.invoice-details {{
flex: 1;
text-align: right;
}}
.invoice-details h2 {{
margin: 0 0 10px 0;
color: #666;
font-size: 24px;
}}
.invoice-number {{
font-size: 18px;
color: #0066cc;
font-weight: bold;
}}
.billing-section {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
}}
.billing-box {{
flex: 1;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-right: 20px;
}}
.billing-box:last-child {{
margin-right: 0;
}}
.billing-box h3 {{
margin: 0 0 15px 0;
color: #0066cc;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
}}
.items-table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
.items-table th {{
background: #0066cc;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
}}
.items-table th:last-child {{
text-align: right;
}}
.totals-section {{
display: flex;
justify-content: flex-end;
margin-bottom: 40px;
}}
.totals-box {{
width: 300px;
}}
.total-row {{
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.total-row.final {{
border-bottom: none;
border-top: 2px solid #0066cc;
margin-top: 10px;
padding-top: 15px;
font-size: 20px;
font-weight: bold;
color: #0066cc;
}}
.payment-terms {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}}
.payment-terms h3 {{
margin: 0 0 10px 0;
color: #0066cc;
}}
.footer-note {{
text-align: center;
color: #666;
font-size: 14px;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
}}
</style>
</head>
<body>
<div class='invoice-container'>
<div class='invoice-header'>
<div class='company-details'>
<h1>{invoice.CompanyName}</h1>
<p>{invoice.CompanyAddress}<br>
{invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
Phone: {invoice.CompanyPhone}<br>
Email: {invoice.CompanyEmail}</p>
</div>
<div class='invoice-details'>
<h2>INVOICE</h2>
<p class='invoice-number'>#{invoice.Number}</p>
<p><strong>Date:</strong> {invoice.Date:MMMM dd, yyyy}<br>
<strong>Due Date:</strong> {invoice.DueDate:MMMM dd, yyyy}</p>
</div>
</div>
<div class='billing-section'>
<div class='billing-box'>
<h3>Bill To</h3>
<p><strong>{invoice.CustomerName}</strong><br>
{invoice.CustomerAddress}<br>
{invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
{invoice.CustomerEmail}</p>
</div>
<div class='billing-box'>
<h3>Payment Information</h3>
<p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
<strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
<strong>Amount Due:</strong> ${invoice.Total:F2}</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Description</th>
<th style='text-align: center;'>Quantity</th>
<th style='text-align: right;'>Unit Price</th>
<th style='text-align: right;'>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='totals-section'>
<div class='totals-box'>
<div class='total-row'>
<span>Subtotal:</span>
<span>${invoice.Subtotal:F2}</span>
</div>
<div class='total-row'>
<span>Tax ({invoice.TaxRate:F0}%):</span>
<span>${invoice.Tax:F2}</span>
</div>
<div class='total-row final'>
<span>Total Due:</span>
<span>${invoice.Total:F2}</span>
</div>
</div>
</div>
<div class='payment-terms'>
<h3>Payment Terms & Conditions</h3>
<p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge.
Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
</div>
<div class='footer-note'>
<p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
<p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
</div>
</div>
</body>
</html>";
}
}
// Invoice model classes
public class Invoice
{
public string Number { get; set; }
public DateTime Date { get; set; }
public DateTime DueDate { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
public string CompanyZip { get; set; }
public string CompanyPhone { get; set; }
public string CompanyEmail { get; set; }
public string CompanyWebsite { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerCity { get; set; }
public string CustomerState { get; set; }
public string CustomerZip { get; set; }
public string CustomerEmail { get; set; }
public string PaymentTerms { get; set; }
public List<InvoiceItem> Items { get; set; }
public decimal Subtotal => Items.Sum(i => i.Total);
public decimal TaxRate { get; set; }
public decimal Tax => Subtotal * (TaxRate / 100);
public decimal Total => Subtotal + Tax;
}
public class InvoiceItem
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total => Quantity * UnitPrice;
}
// Usage example
var generator = new InvoiceGenerator();
var invoice = new Invoice
{
Number = "INV-2024-001",
Date = DateTime.Now,
DueDate = DateTime.Now.AddDays(30),
CompanyName = "Your Company Name",
CompanyAddress = "123 Business Street",
CompanyCity = "New York",
CompanyState = "NY",
CompanyZip = "10001",
CompanyPhone = "(555) 123-4567",
CompanyEmail = "billing@yourcompany.com",
CompanyWebsite = "www.yourcompany.com",
CustomerName = "Acme Corporation",
CustomerAddress = "456 Client Avenue",
CustomerCity = "Los Angeles",
CustomerState = "CA",
CustomerZip = "90001",
CustomerEmail = "accounts@acmecorp.com",
PaymentTerms = "Net 30",
TaxRate = 8.5m,
Items = new List<InvoiceItem>
{
new() { Description = "Professional Services - March 2024", Quantity = 40, UnitPrice = 125.00m },
new() { Description = "Software License (Annual)", Quantity = 1, UnitPrice = 2400.00m },
new() { Description = "Technical Support", Quantity = 10, UnitPrice = 150.00m }
}
};
generator.CreateInvoice(invoice);using IronPdf;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class InvoiceGenerator
{
private readonly ChromePdfRenderer _renderer;
public InvoiceGenerator()
{
_renderer = new ChromePdfRenderer();
ConfigureRenderer();
}
private void ConfigureRenderer()
{
// Professional page setup
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
_renderer.RenderingOptions.MarginTop = 25;
_renderer.RenderingOptions.MarginBottom = 25;
_renderer.RenderingOptions.MarginLeft = 25;
_renderer.RenderingOptions.MarginRight = 25;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Add footer with page numbers
_renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
Text = "Page {page} of {total-pages} | Invoice generated on {date}",
FontSize = 9,
Font = "Arial",
CenterText = true
};
}
public void CreateInvoice(Invoice invoice)
{
var html = GenerateInvoiceHtml(invoice);
var pdf = _renderer.RenderHtmlAsPdf(html);
// Add metadata to the final document
pdf.MetaData.Title = $"Invoice {invoice.Number}";
pdf.MetaData.Author = "Your Company Name";
pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}";
pdf.MetaData.Keywords = "invoice, billing, payment";
pdf.MetaData.CreationDate = DateTime.Now;
// Save the PDF document
var fileName = $"Invoice-{invoice.Number}.pdf";
pdf.SaveAs(fileName);
Console.WriteLine($"PDF generated successfully: {fileName}");
}
private string GenerateInvoiceHtml(Invoice invoice)
{
var itemsHtml = string.Join("", invoice.Items.Select(item => $@"
<tr>
<td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
</tr>"));
return $@"
<html>
<head>
<style>
* {{ box-sizing: border-box; }}
body {{
font-family: 'Segoe UI', Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}}
.invoice-container {{
max-width: 800px;
margin: 0 auto;
padding: 40px;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 3px solid #0066cc;
}}
.company-details {{
flex: 1;
}}
.company-details h1 {{
color: #0066cc;
margin: 0 0 10px 0;
font-size: 28px;
}}
.invoice-details {{
flex: 1;
text-align: right;
}}
.invoice-details h2 {{
margin: 0 0 10px 0;
color: #666;
font-size: 24px;
}}
.invoice-number {{
font-size: 18px;
color: #0066cc;
font-weight: bold;
}}
.billing-section {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
}}
.billing-box {{
flex: 1;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-right: 20px;
}}
.billing-box:last-child {{
margin-right: 0;
}}
.billing-box h3 {{
margin: 0 0 15px 0;
color: #0066cc;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
}}
.items-table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
.items-table th {{
background: #0066cc;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
}}
.items-table th:last-child {{
text-align: right;
}}
.totals-section {{
display: flex;
justify-content: flex-end;
margin-bottom: 40px;
}}
.totals-box {{
width: 300px;
}}
.total-row {{
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.total-row.final {{
border-bottom: none;
border-top: 2px solid #0066cc;
margin-top: 10px;
padding-top: 15px;
font-size: 20px;
font-weight: bold;
color: #0066cc;
}}
.payment-terms {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}}
.payment-terms h3 {{
margin: 0 0 10px 0;
color: #0066cc;
}}
.footer-note {{
text-align: center;
color: #666;
font-size: 14px;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
}}
</style>
</head>
<body>
<div class='invoice-container'>
<div class='invoice-header'>
<div class='company-details'>
<h1>{invoice.CompanyName}</h1>
<p>{invoice.CompanyAddress}<br>
{invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
Phone: {invoice.CompanyPhone}<br>
Email: {invoice.CompanyEmail}</p>
</div>
<div class='invoice-details'>
<h2>INVOICE</h2>
<p class='invoice-number'>#{invoice.Number}</p>
<p><strong>Date:</strong> {invoice.Date:MMMM dd, yyyy}<br>
<strong>Due Date:</strong> {invoice.DueDate:MMMM dd, yyyy}</p>
</div>
</div>
<div class='billing-section'>
<div class='billing-box'>
<h3>Bill To</h3>
<p><strong>{invoice.CustomerName}</strong><br>
{invoice.CustomerAddress}<br>
{invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
{invoice.CustomerEmail}</p>
</div>
<div class='billing-box'>
<h3>Payment Information</h3>
<p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
<strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
<strong>Amount Due:</strong> ${invoice.Total:F2}</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Description</th>
<th style='text-align: center;'>Quantity</th>
<th style='text-align: right;'>Unit Price</th>
<th style='text-align: right;'>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='totals-section'>
<div class='totals-box'>
<div class='total-row'>
<span>Subtotal:</span>
<span>${invoice.Subtotal:F2}</span>
</div>
<div class='total-row'>
<span>Tax ({invoice.TaxRate:F0}%):</span>
<span>${invoice.Tax:F2}</span>
</div>
<div class='total-row final'>
<span>Total Due:</span>
<span>${invoice.Total:F2}</span>
</div>
</div>
</div>
<div class='payment-terms'>
<h3>Payment Terms & Conditions</h3>
<p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge.
Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
</div>
<div class='footer-note'>
<p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
<p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
</div>
</div>
</body>
</html>";
}
}
// Invoice model classes
public class Invoice
{
public string Number { get; set; }
public DateTime Date { get; set; }
public DateTime DueDate { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
public string CompanyZip { get; set; }
public string CompanyPhone { get; set; }
public string CompanyEmail { get; set; }
public string CompanyWebsite { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerCity { get; set; }
public string CustomerState { get; set; }
public string CustomerZip { get; set; }
public string CustomerEmail { get; set; }
public string PaymentTerms { get; set; }
public List<InvoiceItem> Items { get; set; }
public decimal Subtotal => Items.Sum(i => i.Total);
public decimal TaxRate { get; set; }
public decimal Tax => Subtotal * (TaxRate / 100);
public decimal Total => Subtotal + Tax;
}
public class InvoiceItem
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Total => Quantity * UnitPrice;
}
// Usage example
var generator = new InvoiceGenerator();
var invoice = new Invoice
{
Number = "INV-2024-001",
Date = DateTime.Now,
DueDate = DateTime.Now.AddDays(30),
CompanyName = "Your Company Name",
CompanyAddress = "123 Business Street",
CompanyCity = "New York",
CompanyState = "NY",
CompanyZip = "10001",
CompanyPhone = "(555) 123-4567",
CompanyEmail = "billing@yourcompany.com",
CompanyWebsite = "www.yourcompany.com",
CustomerName = "Acme Corporation",
CustomerAddress = "456 Client Avenue",
CustomerCity = "Los Angeles",
CustomerState = "CA",
CustomerZip = "90001",
CustomerEmail = "accounts@acmecorp.com",
PaymentTerms = "Net 30",
TaxRate = 8.5m,
Items = new List<InvoiceItem>
{
new() { Description = "Professional Services - March 2024", Quantity = 40, UnitPrice = 125.00m },
new() { Description = "Software License (Annual)", Quantity = 1, UnitPrice = 2400.00m },
new() { Description = "Technical Support", Quantity = 10, UnitPrice = 150.00m }
}
};
generator.CreateInvoice(invoice);Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Linq
Public Class InvoiceGenerator
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
ConfigureRenderer()
End Sub
Private Sub ConfigureRenderer()
' Professional page setup
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
_renderer.RenderingOptions.MarginTop = 25
_renderer.RenderingOptions.MarginBottom = 25
_renderer.RenderingOptions.MarginLeft = 25
_renderer.RenderingOptions.MarginRight = 25
_renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Add footer with page numbers
_renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.Text = "Page {page} of {total-pages} | Invoice generated on {date}",
.FontSize = 9,
.Font = "Arial",
.CenterText = True
}
End Sub
Public Sub CreateInvoice(ByVal invoice As Invoice)
Dim html = GenerateInvoiceHtml(invoice)
Dim pdf = _renderer.RenderHtmlAsPdf(html)
' Add metadata to the final document
pdf.MetaData.Title = $"Invoice {invoice.Number}"
pdf.MetaData.Author = "Your Company Name"
pdf.MetaData.Subject = $"Invoice for {invoice.CustomerName}"
pdf.MetaData.Keywords = "invoice, billing, payment"
pdf.MetaData.CreationDate = DateTime.Now
' Save the PDF document
Dim fileName = $"Invoice-{invoice.Number}.pdf"
pdf.SaveAs(fileName)
Console.WriteLine($"PDF generated successfully: {fileName}")
End Sub
Private Function GenerateInvoiceHtml(ByVal invoice As Invoice) As String
Dim itemsHtml = String.Join("", invoice.Items.Select(Function(item) $"
<tr>
<td style='padding: 12px; border-bottom: 1px solid #eee;'>{item.Description}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: center;'>{item.Quantity}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.UnitPrice:F2}</td>
<td style='padding: 12px; border-bottom: 1px solid #eee; text-align: right;'>${item.Total:F2}</td>
</tr>"))
Return $"
<html>
<head>
<style>
* {{ box-sizing: border-box; }}
body {{
font-family: 'Segoe UI', Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}}
.invoice-container {{
max-width: 800px;
margin: 0 auto;
padding: 40px;
}}
.invoice-header {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 3px solid #0066cc;
}}
.company-details {{
flex: 1;
}}
.company-details h1 {{
color: #0066cc;
margin: 0 0 10px 0;
font-size: 28px;
}}
.invoice-details {{
flex: 1;
text-align: right;
}}
.invoice-details h2 {{
margin: 0 0 10px 0;
color: #666;
font-size: 24px;
}}
.invoice-number {{
font-size: 18px;
color: #0066cc;
font-weight: bold;
}}
.billing-section {{
display: flex;
justify-content: space-between;
margin-bottom: 40px;
}}
.billing-box {{
flex: 1;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
margin-right: 20px;
}}
.billing-box:last-child {{
margin-right: 0;
}}
.billing-box h3 {{
margin: 0 0 15px 0;
color: #0066cc;
font-size: 16px;
text-transform: uppercase;
letter-spacing: 1px;
}}
.items-table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
.items-table th {{
background: #0066cc;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
}}
.items-table th:last-child {{
text-align: right;
}}
.totals-section {{
display: flex;
justify-content: flex-end;
margin-bottom: 40px;
}}
.totals-box {{
width: 300px;
}}
.total-row {{
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}}
.total-row.final {{
border-bottom: none;
border-top: 2px solid #0066cc;
margin-top: 10px;
padding-top: 15px;
font-size: 20px;
font-weight: bold;
color: #0066cc;
}}
.payment-terms {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
}}
.payment-terms h3 {{
margin: 0 0 10px 0;
color: #0066cc;
}}
.footer-note {{
text-align: center;
color: #666;
font-size: 14px;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
}}
</style>
</head>
<body>
<div class='invoice-container'>
<div class='invoice-header'>
<div class='company-details'>
<h1>{invoice.CompanyName}</h1>
<p>{invoice.CompanyAddress}<br>
{invoice.CompanyCity}, {invoice.CompanyState} {invoice.CompanyZip}<br>
Phone: {invoice.CompanyPhone}<br>
Email: {invoice.CompanyEmail}</p>
</div>
<div class='invoice-details'>
<h2>INVOICE</h2>
<p class='invoice-number'>#{invoice.Number}</p>
<p><strong>Date:</strong> {invoice.Date:=MMMM dd, yyyy}<br>
<strong>Due Date:</strong> {invoice.DueDate:=MMMM dd, yyyy}</p>
</div>
</div>
<div class='billing-section'>
<div class='billing-box'>
<h3>Bill To</h3>
<p><strong>{invoice.CustomerName}</strong><br>
{invoice.CustomerAddress}<br>
{invoice.CustomerCity}, {invoice.CustomerState} {invoice.CustomerZip}<br>
{invoice.CustomerEmail}</p>
</div>
<div class='billing-box'>
<h3>Payment Information</h3>
<p><strong>Payment Terms:</strong> {invoice.PaymentTerms}<br>
<strong>Invoice Status:</strong> <span style='color: #ff6b6b;'>Unpaid</span><br>
<strong>Amount Due:</strong> ${invoice.Total:F2}</p>
</div>
</div>
<table class='items-table'>
<thead>
<tr>
<th>Description</th>
<th style='text-align: center;'>Quantity</th>
<th style='text-align: right;'>Unit Price</th>
<th style='text-align: right;'>Total</th>
</tr>
</thead>
<tbody>
{itemsHtml}
</tbody>
</table>
<div class='totals-section'>
<div class='totals-box'>
<div class='total-row'>
<span>Subtotal:</span>
<span>${invoice.Subtotal:F2}</span>
</div>
<div class='total-row'>
<span>Tax ({invoice.TaxRate:F0}%):</span>
<span>${invoice.Tax:F2}</span>
</div>
<div class='total-row final'>
<span>Total Due:</span>
<span>${invoice.Total:F2}</span>
</div>
</div>
</div>
<div class='payment-terms'>
<h3>Payment Terms & Conditions</h3>
<p>Payment is due within {invoice.PaymentTerms}. Late payments are subject to a 1.5% monthly service charge.
Please make checks payable to {invoice.CompanyName} or pay online at {invoice.CompanyWebsite}.</p>
</div>
<div class='footer-note'>
<p>Thank you for your business! This invoice was generated automatically using our C# PDF generation system.</p>
<p>Questions? Contact us at {invoice.CompanyEmail} or {invoice.CompanyPhone}</p>
</div>
</div>
</body>
</html>"
End Function
End Class
' Invoice model classes
Public Class Invoice
Public Property Number() As String
Public Property [Date]() As DateTime
Public Property DueDate() As DateTime
Public Property CompanyName() As String
Public Property CompanyAddress() As String
Public Property CompanyCity() As String
Public Property CompanyState() As String
Public Property CompanyZip() As String
Public Property CompanyPhone() As String
Public Property CompanyEmail() As String
Public Property CompanyWebsite() As String
Public Property CustomerName() As String
Public Property CustomerAddress() As String
Public Property CustomerCity() As String
Public Property CustomerState() As String
Public Property CustomerZip() As String
Public Property CustomerEmail() As String
Public Property PaymentTerms() As String
Public Property Items() As List(Of InvoiceItem)
Public ReadOnly Property Subtotal() As Decimal
Get
Return Items.Sum(Function(i) i.Total)
End Get
End Property
Public Property TaxRate() As Decimal
Public ReadOnly Property Tax() As Decimal
Get
Return Subtotal * (TaxRate / 100)
End Get
End Property
Public ReadOnly Property Total() As Decimal
Get
Return Subtotal + Tax
End Get
End Property
End Class
Public Class InvoiceItem
Public Property Description() As String
Public Property Quantity() As Integer
Public Property UnitPrice() As Decimal
Public ReadOnly Property Total() As Decimal
Get
Return Quantity * UnitPrice
End Get
End Property
End Class
' Usage example
Private generator = New InvoiceGenerator()
Private invoice = New Invoice With {
.Number = "INV-2024-001",
.Date = DateTime.Now,
.DueDate = DateTime.Now.AddDays(30),
.CompanyName = "Your Company Name",
.CompanyAddress = "123 Business Street",
.CompanyCity = "New York",
.CompanyState = "NY",
.CompanyZip = "10001",
.CompanyPhone = "(555) 123-4567",
.CompanyEmail = "billing@yourcompany.com",
.CompanyWebsite = "www.yourcompany.com",
.CustomerName = "Acme Corporation",
.CustomerAddress = "456 Client Avenue",
.CustomerCity = "Los Angeles",
.CustomerState = "CA",
.CustomerZip = "90001",
.CustomerEmail = "accounts@acmecorp.com",
.PaymentTerms = "Net 30",
.TaxRate = 8.5D,
.Items = New List(Of InvoiceItem) From {
New() {
Description = "Professional Services - March 2024",
Quantity = 40,
UnitPrice = 125.00D
},
New() {
Description = "Software License (Annual)",
Quantity = 1,
UnitPrice = 2400.00D
},
New() {
Description = "Technical Support",
Quantity = 10,
UnitPrice = 150.00D
}
}
}
generator.CreateInvoice(invoice)¿Qué funciones avanzadas de PDF ofrece IronPDF?
IronPDF va más allá de la básica creación de PDF en C# para ofrecer características sofisticadas que permiten flujos de trabajo de documentos complejos y funcionalidad de nivel empresarial. Estas capacidades avanzadas te permiten crear formularios interactivos, asegurar documentos sensibles, y manipular PDFs existentes con precisión cuando construyes PDFs en .NET. Estas características son la razón por la que más de 14 millones de desarrolladores en todo el mundo confían enIronPDFpara sus necesidades de generación de PDF críticas. Entender estas características te ayuda a construir soluciones comprensivas de PDF que cumplan incluso con los requisitos más exigentes - desde crear formularios rellenables hasta implementar seguridad de nivel empresarial en tus proyectos de creación de PDF en C#.
Generar formularios PDF interactivos
Crear formularios PDF rellenables programáticamente abre posibilidades para automatizar la recopilación de datos y los flujos de trabajo de documentos.IronPDFpuede transformar formularios HTML en formularios PDF interactivos que los usuarios pueden rellenar en cualquier lector de PDF:
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var renderer = new ChromePdfRenderer();
// Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Create an interactive form with various input types
var formHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type='text'], input[type='email'], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.checkbox-group { margin: 10px 0; }
.submit-section {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #0066cc;
}
</style>
</head>
<body>
<h1>Application Form</h1>
<form>
<div class='form-group'>
<label for='fullName'>Full Name:</label>
<input type='text' id='fullName' name='fullName' required />
</div>
<div class='form-group'>
<label for='email'>Email Address:</label>
<input type='email' id='email' name='email' required />
</div>
<div class='form-group'>
<label for='department'>Department:</label>
<select id='department' name='department'>
<option value=''>Select Department</option>
<option value='sales'>Sales</option>
<option value='marketing'>Marketing</option>
<option value='engineering'>Engineering</option>
<option value='hr'>Human Resources</option>
</select>
</div>
<div class='form-group'>
<label>Interests:</label>
<div class='checkbox-group'>
<label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
<label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
<label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
</div>
</div>
<div class='form-group'>
<label for='comments'>Additional Comments:</label>
<textarea id='comments' name='comments' rows='4'></textarea>
</div>
<div class='submit-section'>
<p><em>Please save this form and email to hr@company.com</em></p>
</div>
</form>
</body>
</html>";
// Create the PDF with form fields
var formPdf = renderer.RenderHtmlAsPdf(formHtml);
// Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith";
formPdf.Form.FindFormField("email").Value = "john.smith@example.com";
formPdf.Form.FindFormField("department").Value = "engineering";
// Save the interactive form
formPdf.SaveAs("application-form.pdf");
// You can also read and process submitted forms
var submittedPdf = PdfDocument.FromFile("submitted-form.pdf");
var name = submittedPdf.Form.FindFormField("fullName").Value;
var email = submittedPdf.Form.FindFormField("email").Value;
Console.WriteLine($"Form submitted by: {name} ({email})");// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var renderer = new ChromePdfRenderer();
// Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Create an interactive form with various input types
var formHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type='text'], input[type='email'], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.checkbox-group { margin: 10px 0; }
.submit-section {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #0066cc;
}
</style>
</head>
<body>
<h1>Application Form</h1>
<form>
<div class='form-group'>
<label for='fullName'>Full Name:</label>
<input type='text' id='fullName' name='fullName' required />
</div>
<div class='form-group'>
<label for='email'>Email Address:</label>
<input type='email' id='email' name='email' required />
</div>
<div class='form-group'>
<label for='department'>Department:</label>
<select id='department' name='department'>
<option value=''>Select Department</option>
<option value='sales'>Sales</option>
<option value='marketing'>Marketing</option>
<option value='engineering'>Engineering</option>
<option value='hr'>Human Resources</option>
</select>
</div>
<div class='form-group'>
<label>Interests:</label>
<div class='checkbox-group'>
<label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
<label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
<label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
</div>
</div>
<div class='form-group'>
<label for='comments'>Additional Comments:</label>
<textarea id='comments' name='comments' rows='4'></textarea>
</div>
<div class='submit-section'>
<p><em>Please save this form and email to hr@company.com</em></p>
</div>
</form>
</body>
</html>";
// Create the PDF with form fields
var formPdf = renderer.RenderHtmlAsPdf(formHtml);
// Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith";
formPdf.Form.FindFormField("email").Value = "john.smith@example.com";
formPdf.Form.FindFormField("department").Value = "engineering";
// Save the interactive form
formPdf.SaveAs("application-form.pdf");
// You can also read and process submitted forms
var submittedPdf = PdfDocument.FromFile("submitted-form.pdf");
var name = submittedPdf.Form.FindFormField("fullName").Value;
var email = submittedPdf.Form.FindFormField("email").Value;
Console.WriteLine($"Form submitted by: {name} ({email})");' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System
Private renderer = New ChromePdfRenderer()
' Enable form creation from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Create an interactive form with various input types
Dim formHtml = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type='text'], input[type='email'], select, textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.checkbox-group { margin: 10px 0; }
.submit-section {
margin-top: 30px;
padding-top: 20px;
border-top: 2px solid #0066cc;
}
</style>
</head>
<body>
<h1>Application Form</h1>
<form>
<div class='form-group'>
<label for='fullName'>Full Name:</label>
<input type='text' id='fullName' name='fullName' required />
</div>
<div class='form-group'>
<label for='email'>Email Address:</label>
<input type='email' id='email' name='email' required />
</div>
<div class='form-group'>
<label for='department'>Department:</label>
<select id='department' name='department'>
<option value=''>Select Department</option>
<option value='sales'>Sales</option>
<option value='marketing'>Marketing</option>
<option value='engineering'>Engineering</option>
<option value='hr'>Human Resources</option>
</select>
</div>
<div class='form-group'>
<label>Interests:</label>
<div class='checkbox-group'>
<label><input type='checkbox' name='interests' value='training' /> Professional Training</label>
<label><input type='checkbox' name='interests' value='conferences' /> Industry Conferences</label>
<label><input type='checkbox' name='interests' value='certification' /> Certification Programs</label>
</div>
</div>
<div class='form-group'>
<label for='comments'>Additional Comments:</label>
<textarea id='comments' name='comments' rows='4'></textarea>
</div>
<div class='submit-section'>
<p><em>Please save this form and email to hr@company.com</em></p>
</div>
</form>
</body>
</html>"
' Create the PDF with form fields
Dim formPdf = renderer.RenderHtmlAsPdf(formHtml)
' Optionally pre-fill form fields programmatically
formPdf.Form.FindFormField("fullName").Value = "John Smith"
formPdf.Form.FindFormField("email").Value = "john.smith@example.com"
formPdf.Form.FindFormField("department").Value = "engineering"
' Save the interactive form
formPdf.SaveAs("application-form.pdf")
' You can also read and process submitted forms
Dim submittedPdf = PdfDocument.FromFile("submitted-form.pdf")
Dim name = submittedPdf.Form.FindFormField("fullName").Value
Dim email = submittedPdf.Form.FindFormField("email").Value
Console.WriteLine($"Form submitted by: {name} ({email})")Asegure sus PDF generados
La seguridad es fundamental cuando se trata de documentos sensibles.IronPDFproporciona características de seguridad comprensivas para proteger tus PDFs del acceso no autorizado o la modificación:
// Namespace: IronPdf
using IronPdf;
// Namespace: IronPdf.Editing
using IronPdf.Editing;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>");
// Apply password protection
pdf.SecuritySettings.UserPassword = "user123"; // Required to open
pdf.SecuritySettings.OwnerPassword = "owner456"; // Required to modify
// Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserFormData = true;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;
// Add digital signature for authenticity
pdf.SignWithFile(
certificatePath: "certificate.pfx",
certificatePassword: "certpass123",
signingReason: "Document Approval",
signingLocation: "New York, NY",
signatureImage: new Signature("signature.png")
{
Width = 150,
Height = 50
}
);
// Apply redaction to hide sensitive information
pdf.RedactTextOnPage(
pageIndex: 0,
searchText: "SSN: ***-**-****",
replacementText: "[REDACTED]",
caseSensitive: false
);
// Save the secured PDF
pdf.SaveAs("secure-confidential.pdf");// Namespace: IronPdf
using IronPdf;
// Namespace: IronPdf.Editing
using IronPdf.Editing;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>");
// Apply password protection
pdf.SecuritySettings.UserPassword = "user123"; // Required to open
pdf.SecuritySettings.OwnerPassword = "owner456"; // Required to modify
// Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserFormData = true;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;
// Add digital signature for authenticity
pdf.SignWithFile(
certificatePath: "certificate.pfx",
certificatePassword: "certpass123",
signingReason: "Document Approval",
signingLocation: "New York, NY",
signatureImage: new Signature("signature.png")
{
Width = 150,
Height = 50
}
);
// Apply redaction to hide sensitive information
pdf.RedactTextOnPage(
pageIndex: 0,
searchText: "SSN: ***-**-****",
replacementText: "[REDACTED]",
caseSensitive: false
);
// Save the secured PDF
pdf.SaveAs("secure-confidential.pdf");' Namespace: IronPdf
Imports IronPdf
' Namespace: IronPdf.Editing
Imports IronPdf.Editing
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Document</h1><p>Sensitive information...</p>")
' Apply password protection
pdf.SecuritySettings.UserPassword = "user123" ' Required to open
pdf.SecuritySettings.OwnerPassword = "owner456" ' Required to modify
' Set detailed permissions
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserFormData = True
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint
' Add digital signature for authenticity
pdf.SignWithFile(certificatePath:= "certificate.pfx", certificatePassword:= "certpass123", signingReason:= "Document Approval", signingLocation:= "New York, NY", signatureImage:= New Signature("signature.png") With {
.Width = 150,
.Height = 50
})
' Apply redaction to hide sensitive information
pdf.RedactTextOnPage(pageIndex:= 0, searchText:= "SSN: ***-**-****", replacementText:= "[REDACTED]", caseSensitive:= False)
' Save the secured PDF
pdf.SaveAs("secure-confidential.pdf")Fusionar y dividir PDF
Combinar múltiples PDFs o extraer páginas específicas es esencial para los flujos de trabajo de gestión de documentos:
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
// Merge multiple PDFs into one document
var coverPage = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Annual Report 2024</h1>");
var introduction = PdfDocument.FromFile("introduction.pdf");
var financials = PdfDocument.FromFile("financials.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");
// Merge all documents
var completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix);
// Add page numbers to the merged document
for (int i = 0; i < completeReport.PageCount; i++)
{
completeReport.AddTextFooterToPage(i,
$"Page {i + 1} of {completeReport.PageCount}",
IronPdf.Font.FontTypes.Arial,
10);
}
completeReport.SaveAs("annual-report-complete.pdf");
// Extract specific pages
var executiveSummary = completeReport.CopyPages(0, 4); // First 5 pages
executiveSummary.SaveAs("executive-summary.pdf");
// Split a large PDF into chapters
var sourcePdf = PdfDocument.FromFile("large-document.pdf");
var chaptersPerFile = 50;
for (int i = 0; i < sourcePdf.PageCount; i += chaptersPerFile)
{
var endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1);
var chapter = sourcePdf.CopyPages(i, endPage);
chapter.SaveAs($"chapter-{(i / chaptersPerFile) + 1}.pdf");
}// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
// Merge multiple PDFs into one document
var coverPage = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Annual Report 2024</h1>");
var introduction = PdfDocument.FromFile("introduction.pdf");
var financials = PdfDocument.FromFile("financials.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");
// Merge all documents
var completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix);
// Add page numbers to the merged document
for (int i = 0; i < completeReport.PageCount; i++)
{
completeReport.AddTextFooterToPage(i,
$"Page {i + 1} of {completeReport.PageCount}",
IronPdf.Font.FontTypes.Arial,
10);
}
completeReport.SaveAs("annual-report-complete.pdf");
// Extract specific pages
var executiveSummary = completeReport.CopyPages(0, 4); // First 5 pages
executiveSummary.SaveAs("executive-summary.pdf");
// Split a large PDF into chapters
var sourcePdf = PdfDocument.FromFile("large-document.pdf");
var chaptersPerFile = 50;
for (int i = 0; i < sourcePdf.PageCount; i += chaptersPerFile)
{
var endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1);
var chapter = sourcePdf.CopyPages(i, endPage);
chapter.SaveAs($"chapter-{(i / chaptersPerFile) + 1}.pdf");
}' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System
' Merge multiple PDFs into one document
Private coverPage = (New ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Annual Report 2024</h1>")
Private introduction = PdfDocument.FromFile("introduction.pdf")
Private financials = PdfDocument.FromFile("financials.pdf")
Private appendix = PdfDocument.FromFile("appendix.pdf")
' Merge all documents
Private completeReport = PdfDocument.Merge(coverPage, introduction, financials, appendix)
' Add page numbers to the merged document
Dim i As Integer = 0
Do While i < completeReport.PageCount
completeReport.AddTextFooterToPage(i, $"Page {i + 1} of {completeReport.PageCount}", IronPdf.Font.FontTypes.Arial, 10)
i += 1
Loop
completeReport.SaveAs("annual-report-complete.pdf")
' Extract specific pages
Dim executiveSummary = completeReport.CopyPages(0, 4) ' First 5 pages
executiveSummary.SaveAs("executive-summary.pdf")
' Split a large PDF into chapters
Dim sourcePdf = PdfDocument.FromFile("large-document.pdf")
Dim chaptersPerFile = 50
For i As Integer = 0 To sourcePdf.PageCount - 1 Step chaptersPerFile
Dim endPage = Math.Min(i + chaptersPerFile - 1, sourcePdf.PageCount - 1)
Dim chapter = sourcePdf.CopyPages(i, endPage)
chapter.SaveAs($"chapter-{(i \ chaptersPerFile) + 1}.pdf")
Next iAñadir marcas de agua y sellos
Marcar PDFs es crucial para el control de documentos y la marca.IronPDFadmite marcas de agua tanto de texto como de imagen:
// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var pdf = PdfDocument.FromFile("document.pdf");
// Add text watermark
pdf.ApplyWatermark(
html: "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>",
rotation: 45,
opacity: 50,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center
);
// Add image watermark (company logo)
pdf.ApplyWatermark(
html: "<img src='logo-watermark.png' style='width: 300px;' />",
rotation: 0,
opacity: 30,
verticalAlignment: VerticalAlignment.Bottom,
horizontalAlignment: HorizontalAlignment.Right
);
// Add stamps for document status
pdf.StampHtml(
Html: @"<div style='border: 3px solid green; padding: 10px;
background: white; font-weight: bold; color: green;'>
APPROVED<br/>
" + DateTime.Now.ToString("MM/dd/yyyy") + @"
</div>",
X: 400,
Y: 100,
Width: 150,
Height: 60,
PageIndex: 0
);
pdf.SaveAs("watermarked-document.pdf");// Namespace: IronPdf
using IronPdf;
// Namespace: System
using System;
var pdf = PdfDocument.FromFile("document.pdf");
// Add text watermark
pdf.ApplyWatermark(
html: "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>",
rotation: 45,
opacity: 50,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center
);
// Add image watermark (company logo)
pdf.ApplyWatermark(
html: "<img src='logo-watermark.png' style='width: 300px;' />",
rotation: 0,
opacity: 30,
verticalAlignment: VerticalAlignment.Bottom,
horizontalAlignment: HorizontalAlignment.Right
);
// Add stamps for document status
pdf.StampHtml(
Html: @"<div style='border: 3px solid green; padding: 10px;
background: white; font-weight: bold; color: green;'>
APPROVED<br/>
" + DateTime.Now.ToString("MM/dd/yyyy") + @"
</div>",
X: 400,
Y: 100,
Width: 150,
Height: 60,
PageIndex: 0
);
pdf.SaveAs("watermarked-document.pdf");' Namespace: IronPdf
Imports IronPdf
' Namespace: System
Imports System
Private pdf = PdfDocument.FromFile("document.pdf")
' Add text watermark
pdf.ApplyWatermark(html:= "<h1 style='color: #ff0000; opacity: 0.5; font-size: 100px;'>DRAFT</h1>", rotation:= 45, opacity:= 50, verticalAlignment:= VerticalAlignment.Middle, horizontalAlignment:= HorizontalAlignment.Center)
' Add image watermark (company logo)
pdf.ApplyWatermark(html:= "<img src='logo-watermark.png' style='width: 300px;' />", rotation:= 0, opacity:= 30, verticalAlignment:= VerticalAlignment.Bottom, horizontalAlignment:= HorizontalAlignment.Right)
' Add stamps for document status
pdf.StampHtml(Html:= "<div style='border: 3px solid green; padding: 10px;
background: white; font-weight: bold; color: green;'>
APPROVED<br/>
" & DateTime.Now.ToString("MM/dd/yyyy") & "
</div>", X:= 400, Y:= 100, Width:= 150, Height:= 60, PageIndex:= 0)
pdf.SaveAs("watermarked-document.pdf")¿Cómo puedo optimizar el rendimiento al generar archivos PDF a gran escala?
Al generar PDFs a escala, el rendimiento se vuelve crítico. Ya sea que estés creando miles de facturas o procesando grandes trabajos por lotes, optimizar tu código de generación de PDF puede mejorar dramáticamente el rendimiento y reducir el consumo de recursos. Las aplicaciones modernas requieren una creación de PDF en C# eficiente que no bloquee hilos ni consuma memoria de manera excesiva. Aquí hay estrategias probadas para maximizar el rendimiento en tus diversas tareas de generación de PDF cuando necesitas producir PDFs en .NET de manera eficiente.
Generación asíncrona de PDF
Las aplicaciones modernas requieren operaciones no bloqueantes para mantener la capacidad de respuesta.IronPDFproporciona métodos asíncronos para todas las operaciones principales:
// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.Collections.Generic
using System.Collections.Generic;
// Namespace: System.Linq
using System.Linq;
// Namespace: System
using System;
// Namespace: System.Threading
using System.Threading;
public class AsyncPdfService
{
private readonly ChromePdfRenderer _renderer;
public AsyncPdfService()
{
_renderer = new ChromePdfRenderer();
// Configure renderer once for reuse
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
// Non-blocking PDF generation
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public async Task GenerateBatchAsync(List<string> htmlDocuments)
{
// Process multiple PDFs concurrently
var tasks = htmlDocuments.Select(async (html, index) =>
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
await pdf.SaveAsAsync($"document-{index}.pdf");
});
await Task.WhenAll(tasks);
}
// Async with cancellation support
public async Task<PdfDocument> GenerateWithTimeoutAsync(string html, int timeoutSeconds)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
try
{
return await _renderer.RenderHtmlAsPdfAsync(html, cts.Token);
}
catch (OperationCanceledException)
{
throw new TimeoutException("PDF generation exceeded timeout");
}
}
}// Namespace: IronPdf
using IronPdf;
// Namespace: System.Threading.Tasks
using System.Threading.Tasks;
// Namespace: System.Collections.Generic
using System.Collections.Generic;
// Namespace: System.Linq
using System.Linq;
// Namespace: System
using System;
// Namespace: System.Threading
using System.Threading;
public class AsyncPdfService
{
private readonly ChromePdfRenderer _renderer;
public AsyncPdfService()
{
_renderer = new ChromePdfRenderer();
// Configure renderer once for reuse
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
}
public async Task<byte[]> GeneratePdfAsync(string html)
{
// Non-blocking PDF generation
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public async Task GenerateBatchAsync(List<string> htmlDocuments)
{
// Process multiple PDFs concurrently
var tasks = htmlDocuments.Select(async (html, index) =>
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
await pdf.SaveAsAsync($"document-{index}.pdf");
});
await Task.WhenAll(tasks);
}
// Async with cancellation support
public async Task<PdfDocument> GenerateWithTimeoutAsync(string html, int timeoutSeconds)
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
try
{
return await _renderer.RenderHtmlAsPdfAsync(html, cts.Token);
}
catch (OperationCanceledException)
{
throw new TimeoutException("PDF generation exceeded timeout");
}
}
}' Namespace: IronPdf
Imports IronPdf
' Namespace: System.Threading.Tasks
Imports System.Threading.Tasks
' Namespace: System.Collections.Generic
Imports System.Collections.Generic
' Namespace: System.Linq
Imports System.Linq
' Namespace: System
Imports System
' Namespace: System.Threading
Imports System.Threading
Public Class AsyncPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Configure renderer once for reuse
_renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
End Sub
Public Async Function GeneratePdfAsync(ByVal html As String) As Task(Of Byte())
' Non-blocking PDF generation
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Function
Public Async Function GenerateBatchAsync(ByVal htmlDocuments As List(Of String)) As Task
' Process multiple PDFs concurrently
Dim tasks = htmlDocuments.Select(Async Function(html, index)
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Await pdf.SaveAsAsync($"document-{index}.pdf")
End Function)
Await Task.WhenAll(tasks)
End Function
' Async with cancellation support
Public Async Function GenerateWithTimeoutAsync(ByVal html As String, ByVal timeoutSeconds As Integer) As Task(Of PdfDocument)
Dim cts = New CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds))
Try
Return Await _renderer.RenderHtmlAsPdfAsync(html, cts.Token)
Catch e1 As OperationCanceledException
Throw New TimeoutException("PDF generation exceeded timeout")
End Try
End Function
End ClassMejores prácticas de procesamiento por lotes
Al procesar múltiples PDFs, la gestión adecuada de recursos y el procesamiento paralelo pueden mejorar significativamente el rendimiento:
using IronPdf;
using System.Threading.Tasks.Dataflow;
public class BatchPdfProcessor
{
private readonly ChromePdfRenderer _renderer;
private readonly ActionBlock<PdfJob> _processingBlock;
public BatchPdfProcessor(int maxConcurrency = 4)
{
_renderer = new ChromePdfRenderer();
// Create a processing pipeline with controlled concurrency
_processingBlock = new ActionBlock<PdfJob>(
async job => await ProcessPdfAsync(job),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = maxConcurrency,
BoundedCapacity = maxConcurrency * 2
});
}
private async Task ProcessPdfAsync(PdfJob job)
{
try
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(job.Html);
await pdf.SaveAsAsync(job.OutputPath);
job.OnSuccess?.Invoke();
}
catch (Exception ex)
{
job.OnError?.Invoke(ex);
}
}
public async Task<bool> QueuePdfAsync(PdfJob job)
{
return await _processingBlock.SendAsync(job);
}
public async Task CompleteAsync()
{
_processingBlock.Complete();
await _processingBlock.Completion;
}
}
public class PdfJob
{
public string Html { get; set; }
public string OutputPath { get; set; }
public Action OnSuccess { get; set; }
public Action<Exception> OnError { get; set; }
}using IronPdf;
using System.Threading.Tasks.Dataflow;
public class BatchPdfProcessor
{
private readonly ChromePdfRenderer _renderer;
private readonly ActionBlock<PdfJob> _processingBlock;
public BatchPdfProcessor(int maxConcurrency = 4)
{
_renderer = new ChromePdfRenderer();
// Create a processing pipeline with controlled concurrency
_processingBlock = new ActionBlock<PdfJob>(
async job => await ProcessPdfAsync(job),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = maxConcurrency,
BoundedCapacity = maxConcurrency * 2
});
}
private async Task ProcessPdfAsync(PdfJob job)
{
try
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(job.Html);
await pdf.SaveAsAsync(job.OutputPath);
job.OnSuccess?.Invoke();
}
catch (Exception ex)
{
job.OnError?.Invoke(ex);
}
}
public async Task<bool> QueuePdfAsync(PdfJob job)
{
return await _processingBlock.SendAsync(job);
}
public async Task CompleteAsync()
{
_processingBlock.Complete();
await _processingBlock.Completion;
}
}
public class PdfJob
{
public string Html { get; set; }
public string OutputPath { get; set; }
public Action OnSuccess { get; set; }
public Action<Exception> OnError { get; set; }
}Imports IronPdf
Imports System.Threading.Tasks.Dataflow
Public Class BatchPdfProcessor
Private ReadOnly _renderer As ChromePdfRenderer
Private ReadOnly _processingBlock As ActionBlock(Of PdfJob)
Public Sub New(Optional ByVal maxConcurrency As Integer = 4)
_renderer = New ChromePdfRenderer()
' Create a processing pipeline with controlled concurrency
_processingBlock = New ActionBlock(Of PdfJob)(Async Function(job) Await ProcessPdfAsync(job), New ExecutionDataflowBlockOptions With {
.MaxDegreeOfParallelism = maxConcurrency,
.BoundedCapacity = maxConcurrency * 2
})
End Sub
Private Async Function ProcessPdfAsync(ByVal job As PdfJob) As Task
Try
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(job.Html)
Await pdf.SaveAsAsync(job.OutputPath)
If job.OnSuccess IsNot Nothing Then
job.OnSuccess.Invoke()
End If
Catch ex As Exception
If job.OnError IsNot Nothing Then
job.OnError.Invoke(ex)
End If
End Try
End Function
Public Async Function QueuePdfAsync(ByVal job As PdfJob) As Task(Of Boolean)
Return Await _processingBlock.SendAsync(job)
End Function
Public Async Function CompleteAsync() As Task
_processingBlock.Complete()
Await _processingBlock.Completion
End Function
End Class
Public Class PdfJob
Public Property Html() As String
Public Property OutputPath() As String
Public Property OnSuccess() As Action
Public Property OnError() As Action(Of Exception)
End ClassTécnicas de optimización de memoria
Para PDFs grandes o procesamiento de alto volumen, la gestión de memoria es crucial:
using IronPdf;
public class MemoryEfficientPdfGenerator
{
private readonly ChromePdfRenderer _renderer;
public MemoryEfficientPdfGenerator()
{
_renderer = new ChromePdfRenderer();
// Optimize for memory usage
_renderer.RenderingOptions.RenderQuality = 90; // Slightly lower quality for smaller size
_renderer.RenderingOptions.ImageQuality = 85; // Compress images
}
// Stream large PDFs instead of loading into memory
public async Task GenerateLargePdfToStreamAsync(string html, Stream outputStream)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
// Write directly to stream without keeping in memory
using (pdf)
{
var bytes = pdf.BinaryData;
await outputStream.WriteAsync(bytes, 0, bytes.Length);
}
}
// Process large HTML in chunks
public async Task<PdfDocument> GenerateFromChunksAsync(List<string> htmlChunks)
{
var pdfs = new List<PdfDocument>();
try
{
// Generate each chunk separately
foreach (var chunk in htmlChunks)
{
var chunkPdf = await _renderer.RenderHtmlAsPdfAsync(chunk);
pdfs.Add(chunkPdf);
}
// Merge all chunks
return PdfDocument.Merge(pdfs.ToArray());
}
finally
{
// Ensure all temporary PDFs are disposed
foreach (var pdf in pdfs)
{
pdf?.Dispose();
}
}
}
}using IronPdf;
public class MemoryEfficientPdfGenerator
{
private readonly ChromePdfRenderer _renderer;
public MemoryEfficientPdfGenerator()
{
_renderer = new ChromePdfRenderer();
// Optimize for memory usage
_renderer.RenderingOptions.RenderQuality = 90; // Slightly lower quality for smaller size
_renderer.RenderingOptions.ImageQuality = 85; // Compress images
}
// Stream large PDFs instead of loading into memory
public async Task GenerateLargePdfToStreamAsync(string html, Stream outputStream)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
// Write directly to stream without keeping in memory
using (pdf)
{
var bytes = pdf.BinaryData;
await outputStream.WriteAsync(bytes, 0, bytes.Length);
}
}
// Process large HTML in chunks
public async Task<PdfDocument> GenerateFromChunksAsync(List<string> htmlChunks)
{
var pdfs = new List<PdfDocument>();
try
{
// Generate each chunk separately
foreach (var chunk in htmlChunks)
{
var chunkPdf = await _renderer.RenderHtmlAsPdfAsync(chunk);
pdfs.Add(chunkPdf);
}
// Merge all chunks
return PdfDocument.Merge(pdfs.ToArray());
}
finally
{
// Ensure all temporary PDFs are disposed
foreach (var pdf in pdfs)
{
pdf?.Dispose();
}
}
}
}Imports IronPdf
Public Class MemoryEfficientPdfGenerator
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Optimize for memory usage
_renderer.RenderingOptions.RenderQuality = 90 ' Slightly lower quality for smaller size
_renderer.RenderingOptions.ImageQuality = 85 ' Compress images
End Sub
' Stream large PDFs instead of loading into memory
Public Async Function GenerateLargePdfToStreamAsync(ByVal html As String, ByVal outputStream As Stream) As Task
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
' Write directly to stream without keeping in memory
Using pdf
Dim bytes = pdf.BinaryData
Await outputStream.WriteAsync(bytes, 0, bytes.Length)
End Using
End Function
' Process large HTML in chunks
Public Async Function GenerateFromChunksAsync(ByVal htmlChunks As List(Of String)) As Task(Of PdfDocument)
Dim pdfs = New List(Of PdfDocument)()
Try
' Generate each chunk separately
For Each chunk In htmlChunks
Dim chunkPdf = Await _renderer.RenderHtmlAsPdfAsync(chunk)
pdfs.Add(chunkPdf)
Next chunk
' Merge all chunks
Return PdfDocument.Merge(pdfs.ToArray())
Finally
' Ensure all temporary PDFs are disposed
For Each pdf In pdfs
If pdf IsNot Nothing Then
pdf.Dispose()
End If
Next pdf
End Try
End Function
End ClassOptimización de plantillas y almacenamiento en caché
Reduce el tiempo de renderizado almacenando en caché elementos comunes y optimizando plantillas:
using IronPdf;
using Microsoft.Extensions.Caching.Memory;
public class CachedPdfService
{
private readonly ChromePdfRenderer _renderer;
private readonly IMemoryCache _cache;
private readonly Dictionary<string, string> _compiledTemplates;
public CachedPdfService(IMemoryCache cache)
{
_renderer = new ChromePdfRenderer();
_cache = cache;
_compiledTemplates = new Dictionary<string, string>();
// Pre-compile common templates
PrecompileTemplates();
}
private void PrecompileTemplates()
{
// Load and cache common CSS
var commonCss = File.ReadAllText("Templates/common.css");
_compiledTemplates["commonCss"] = commonCss;
// Cache logo as Base64
var logoBytes = File.ReadAllBytes("Assets/logo.png");
var logoBase64 = Convert.ToBase64String(logoBytes);
_compiledTemplates["logoData"] = $"data:image/png;base64,{logoBase64}";
}
public async Task<byte[]> GenerateInvoicePdfAsync(string invoiceId, InvoiceData data)
{
// Check cache first
var cacheKey = $"invoice_{invoiceId}";
if (_cache.TryGetValue<byte[]>(cacheKey, out var cachedPdf))
{
return cachedPdf;
}
// Generate PDF with cached templates
var html = BuildHtmlWithCache(data);
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var pdfBytes = pdf.BinaryData;
// Cache for 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
return pdfBytes;
}
private string BuildHtmlWithCache(InvoiceData data)
{
return $@"
<html>
<head>
<style>{_compiledTemplates["commonCss"]}</style>
</head>
<body>
<img src='{_compiledTemplates["logoData"]}' />
<!-- Rest of invoice HTML -->
</body>
</html>";
}
}using IronPdf;
using Microsoft.Extensions.Caching.Memory;
public class CachedPdfService
{
private readonly ChromePdfRenderer _renderer;
private readonly IMemoryCache _cache;
private readonly Dictionary<string, string> _compiledTemplates;
public CachedPdfService(IMemoryCache cache)
{
_renderer = new ChromePdfRenderer();
_cache = cache;
_compiledTemplates = new Dictionary<string, string>();
// Pre-compile common templates
PrecompileTemplates();
}
private void PrecompileTemplates()
{
// Load and cache common CSS
var commonCss = File.ReadAllText("Templates/common.css");
_compiledTemplates["commonCss"] = commonCss;
// Cache logo as Base64
var logoBytes = File.ReadAllBytes("Assets/logo.png");
var logoBase64 = Convert.ToBase64String(logoBytes);
_compiledTemplates["logoData"] = $"data:image/png;base64,{logoBase64}";
}
public async Task<byte[]> GenerateInvoicePdfAsync(string invoiceId, InvoiceData data)
{
// Check cache first
var cacheKey = $"invoice_{invoiceId}";
if (_cache.TryGetValue<byte[]>(cacheKey, out var cachedPdf))
{
return cachedPdf;
}
// Generate PDF with cached templates
var html = BuildHtmlWithCache(data);
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var pdfBytes = pdf.BinaryData;
// Cache for 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
return pdfBytes;
}
private string BuildHtmlWithCache(InvoiceData data)
{
return $@"
<html>
<head>
<style>{_compiledTemplates["commonCss"]}</style>
</head>
<body>
<img src='{_compiledTemplates["logoData"]}' />
<!-- Rest of invoice HTML -->
</body>
</html>";
}
}Imports IronPdf
Imports Microsoft.Extensions.Caching.Memory
Public Class CachedPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Private ReadOnly _cache As IMemoryCache
Private ReadOnly _compiledTemplates As Dictionary(Of String, String)
Public Sub New(ByVal cache As IMemoryCache)
_renderer = New ChromePdfRenderer()
_cache = cache
_compiledTemplates = New Dictionary(Of String, String)()
' Pre-compile common templates
PrecompileTemplates()
End Sub
Private Sub PrecompileTemplates()
' Load and cache common CSS
Dim commonCss = File.ReadAllText("Templates/common.css")
_compiledTemplates("commonCss") = commonCss
' Cache logo as Base64
Dim logoBytes = File.ReadAllBytes("Assets/logo.png")
Dim logoBase64 = Convert.ToBase64String(logoBytes)
_compiledTemplates("logoData") = $"data:image/png;base64,{logoBase64}"
End Sub
Public Async Function GenerateInvoicePdfAsync(ByVal invoiceId As String, ByVal data As InvoiceData) As Task(Of Byte())
' Check cache first
Dim cacheKey = $"invoice_{invoiceId}"
Dim cachedPdf As var
If _cache.TryGetValue(Of Byte())(cacheKey, cachedPdf) Then
Return cachedPdf
End If
' Generate PDF with cached templates
Dim html = BuildHtmlWithCache(data)
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Dim pdfBytes = pdf.BinaryData
' Cache for 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1))
Return pdfBytes
End Function
Private Function BuildHtmlWithCache(ByVal data As InvoiceData) As String
Return $"
<html>
<head>
<style>{_compiledTemplates("commonCss")}</style>ignoreignoreignore</head><body><img src='{_compiledTemplates("logoData")}' /><!-- Rest of invoice HTML --></body></html>"
End Function
End Class¿Cuáles son los problemas más comunes al crear PDF y cómo solucionarlos?
Incluso con una biblioteca .NET PDF robusta como IronPDF, puedes encontrar desafíos durante el desarrollo o despliegue al construir PDFs en C#. Entender problemas comunes y sus soluciones te ayuda a resolver rápidamente problemas y mantener operaciones suaves de generación de PDF. La buena noticia es que con más de 14 millones de desarrolladores usandoIronPDFcomo su generador de PDF en C#, la mayoría de los problemas han sido encontrados y solucionados antes. Esta guía de resolución de problemas cubre los problemas más frecuentes que enfrentan los desarrolladores al crear PDFs en .NET y proporciona soluciones prácticas basadas en la experiencia del mundo real. Recuerda, soporte 24/7 siempre está disponible si necesitas asistencia inmediata con tus desafíos de creación de PDF.
Cuestión 1: Renderizado fallido o PDF en blanco
Uno de los problemas más comunes son los PDFs que aparecen vacíos o no se renderizan adecuadamente. Esto típicamente ocurre cuando los activos no se cargan a tiempo o cuando hay problemas de tiempo de JavaScript:
// Namespace: IronPdf
using IronPdf;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// Problem: PDF is blank or missing content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(complexHtml); // Results in blank PDF
// Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000; // Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = true;
// Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = new WaitFor()
{
JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
WaitForType = WaitForType.JavaScript,
Timeout = 30000 // 30 second timeout
};
// Solution 3: Use base path for local assets
var basePath = Path.GetFullPath("Assets");
var pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath);
// Solution 4: Embed assets as Base64
var imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"));
var htmlWithEmbedded = $@"<img src='data:image/png;base64,{imageBase64}' />";// Namespace: IronPdf
using IronPdf;
// Namespace: System.IO
using System.IO;
// Namespace: System
using System;
// Problem: PDF is blank or missing content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(complexHtml); // Results in blank PDF
// Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000; // Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = true;
// Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = new WaitFor()
{
JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
WaitForType = WaitForType.JavaScript,
Timeout = 30000 // 30 second timeout
};
// Solution 3: Use base path for local assets
var basePath = Path.GetFullPath("Assets");
var pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath);
// Solution 4: Embed assets as Base64
var imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"));
var htmlWithEmbedded = $@"<img src='data:image/png;base64,{imageBase64}' />";' Namespace: IronPdf
Imports IronPdf
' Namespace: System.IO
Imports System.IO
' Namespace: System
Imports System
' Problem: PDF is blank or missing content
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf(complexHtml) ' Results in blank PDF
' Solution 1: Add render delay for JavaScript-heavy content
renderer.RenderingOptions.RenderDelay = 3000 ' Wait 3 seconds
renderer.RenderingOptions.EnableJavaScript = True
' Solution 2: Wait for specific elements
renderer.RenderingOptions.WaitFor = New WaitFor() With {
.JavaScriptQuery = "document.querySelector('#chart-loaded') !== null",
.WaitForType = WaitForType.JavaScript,
.Timeout = 30000
}
' Solution 3: Use base path for local assets
Dim basePath = Path.GetFullPath("Assets")
Dim pdf = renderer.RenderHtmlAsPdf(htmlWithImages, basePath)
' Solution 4: Embed assets as Base64
Dim imageBase64 = Convert.ToBase64String(File.ReadAllBytes("logo.png"))
Dim htmlWithEmbedded = $"<img src='data:image/png;base64,{imageBase64}' />"Para problemas persistentes de renderizado, habilita el registro para diagnosticar el problema:
// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;' Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = True
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log"
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.AllCuestión 2: Renderizado inicial lento
La primera generación de PDF puede ser más lenta debido a la sobrecarga de inicialización. El renderizado inicial deIronPDFpuede tardar de 2-3 segundos en ejecutarse, lo cual es un tiempo de inicio normal similar a abrir Chrome en un entorno de escritorio:
// Problem: First PDF takes too long to generate
public class PdfService
{
private ChromePdfRenderer _renderer;
// Solution 1: Initialize renderer at startup
public void Initialize()
{
_renderer = new ChromePdfRenderer();
// Warm up the renderer
_ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
}
// Solution 2: Use IronPdf.Native packages for faster initialization
// Install-Package IronPdf.Native.Windows.X64
// This includes pre-loaded binaries for your platform
// Solution 3: For cloud deployments, use appropriate packages
// For Linux: Install-Package IronPdf.Linux
// For Docker: Use IronPdf.Linux with proper dependencies
}
// Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = true; // Use only with persistent storage// Problem: First PDF takes too long to generate
public class PdfService
{
private ChromePdfRenderer _renderer;
// Solution 1: Initialize renderer at startup
public void Initialize()
{
_renderer = new ChromePdfRenderer();
// Warm up the renderer
_ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
}
// Solution 2: Use IronPdf.Native packages for faster initialization
// Install-Package IronPdf.Native.Windows.X64
// This includes pre-loaded binaries for your platform
// Solution 3: For cloud deployments, use appropriate packages
// For Linux: Install-Package IronPdf.Linux
// For Docker: Use IronPdf.Linux with proper dependencies
}
// Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = true; // Use only with persistent storage' Problem: First PDF takes too long to generate
Public Class PdfService
Private _renderer As ChromePdfRenderer
' Solution 1: Initialize renderer at startup
Public Sub Initialize()
_renderer = New ChromePdfRenderer()
' Warm up the renderer
'INSTANT VB TODO TASK: Underscore 'discards' are not converted by Instant VB:
'ORIGINAL LINE: _ = _renderer.RenderHtmlAsPdf("<p>Warm up</p>");
underscore = _renderer.RenderHtmlAsPdf("<p>Warm up</p>")
End Sub
' Solution 2: Use IronPdf.Native packages for faster initialization
' Install-Package IronPdf.Native.Windows.X64
' This includes pre-loaded binaries for your platform
' Solution 3: For cloud deployments, use appropriate packages
' For Linux: Install-Package IronPdf.Linux
' For Docker: Use IronPdf.Linux with proper dependencies
End Class
' Solution 4: Skip initialization checks in production
IronPdf.Installation.SkipInitialization = True ' Use only with persistent storageTema 3: Problemas de despliegue en Linux/Docker
IronPDF requiere dependencias específicas de Linux que pueden no estar presentes en imágenes mínimas de Docker. He aquí cómo resolver problemas comunes de despliegue:
# Dockerfile forIronPDFon Linux
FROM mcr.microsoft.com/dotnet/aspnet:8.0
# Install required dependencies
RUN apt-get update && apt-get install -y \
libglib2.0-0 \
libnss3 \
libatk1.0-0 \
libatk-bridge2.0-0 \
libcups2 \
libxkbcommon0 \
libxcomposite1 \
libxdamage1 \
libxrandr2 \
libgbm1 \
libpango-1.0-0 \
libcairo2 \
libasound2 \
libxshmfence1 \
libx11-xcb1
# Copy and run your application
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet", "YourApp.dll"]Para Google Cloud Run específicamente:
// Use 2nd generation execution environment
// Deploy with: gcloud run deploy --execution-environment gen2
// In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;// Use 2nd generation execution environment
// Deploy with: gcloud run deploy --execution-environment gen2
// In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;' Use 2nd generation execution environment
' Deploy with: gcloud run deploy --execution-environment gen2
' In your code, ensure compatibility
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.DisabledNúmero 4: Problemas de memoria y rendimiento
Para la generación de PDF de alto volumen, optimiza el uso de memoria y el rendimiento:
// Problem: High memory usage or slow batch processing
public class OptimizedPdfService
{
private readonly ChromePdfRenderer _renderer;
public OptimizedPdfService()
{
_renderer = new ChromePdfRenderer();
// Optimize for performance
_renderer.RenderingOptions.RenderQuality = 90;
_renderer.RenderingOptions.ImageQuality = 85;
// Disable features you don't need
_renderer.RenderingOptions.EnableJavaScript = false; // If not needed
_renderer.RenderingOptions.RenderDelay = 0; // If content is static
}
// Solution 1: Process large documents in chunks
public async Task<PdfDocument> GenerateLargeReportAsync(List<ReportSection> sections)
{
var pdfs = new List<PdfDocument>();
foreach (var section in sections)
{
var sectionHtml = GenerateSectionHtml(section);
var sectionPdf = await _renderer.RenderHtmlAsPdfAsync(sectionHtml);
pdfs.Add(sectionPdf);
// Force garbage collection after each section
if (pdfs.Count % 10 == 0)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
return PdfDocument.Merge(pdfs.ToArray());
}
// Solution 2: Use streaming for large files
public async Task StreamLargePdfAsync(string html, HttpResponse response)
{
response.ContentType = "application/pdf";
response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf");
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var bytes = pdf.BinaryData;
await response.Body.WriteAsync(bytes, 0, bytes.Length);
await response.Body.FlushAsync();
}
}// Problem: High memory usage or slow batch processing
public class OptimizedPdfService
{
private readonly ChromePdfRenderer _renderer;
public OptimizedPdfService()
{
_renderer = new ChromePdfRenderer();
// Optimize for performance
_renderer.RenderingOptions.RenderQuality = 90;
_renderer.RenderingOptions.ImageQuality = 85;
// Disable features you don't need
_renderer.RenderingOptions.EnableJavaScript = false; // If not needed
_renderer.RenderingOptions.RenderDelay = 0; // If content is static
}
// Solution 1: Process large documents in chunks
public async Task<PdfDocument> GenerateLargeReportAsync(List<ReportSection> sections)
{
var pdfs = new List<PdfDocument>();
foreach (var section in sections)
{
var sectionHtml = GenerateSectionHtml(section);
var sectionPdf = await _renderer.RenderHtmlAsPdfAsync(sectionHtml);
pdfs.Add(sectionPdf);
// Force garbage collection after each section
if (pdfs.Count % 10 == 0)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
return PdfDocument.Merge(pdfs.ToArray());
}
// Solution 2: Use streaming for large files
public async Task StreamLargePdfAsync(string html, HttpResponse response)
{
response.ContentType = "application/pdf";
response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf");
var pdf = await _renderer.RenderHtmlAsPdfAsync(html);
var bytes = pdf.BinaryData;
await response.Body.WriteAsync(bytes, 0, bytes.Length);
await response.Body.FlushAsync();
}
}' Problem: High memory usage or slow batch processing
Public Class OptimizedPdfService
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Optimize for performance
_renderer.RenderingOptions.RenderQuality = 90
_renderer.RenderingOptions.ImageQuality = 85
' Disable features you don't need
_renderer.RenderingOptions.EnableJavaScript = False ' If not needed
_renderer.RenderingOptions.RenderDelay = 0 ' If content is static
End Sub
' Solution 1: Process large documents in chunks
Public Async Function GenerateLargeReportAsync(ByVal sections As List(Of ReportSection)) As Task(Of PdfDocument)
Dim pdfs = New List(Of PdfDocument)()
For Each section In sections
Dim sectionHtml = GenerateSectionHtml(section)
Dim sectionPdf = Await _renderer.RenderHtmlAsPdfAsync(sectionHtml)
pdfs.Add(sectionPdf)
' Force garbage collection after each section
If pdfs.Count Mod 10 = 0 Then
GC.Collect()
GC.WaitForPendingFinalizers()
End If
Next section
Return PdfDocument.Merge(pdfs.ToArray())
End Function
' Solution 2: Use streaming for large files
Public Async Function StreamLargePdfAsync(ByVal html As String, ByVal response As HttpResponse) As Task
response.ContentType = "application/pdf"
response.Headers.Add("Content-Disposition", "attachment; filename=report.pdf")
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(html)
Dim bytes = pdf.BinaryData
Await response.Body.WriteAsync(bytes, 0, bytes.Length)
Await response.Body.FlushAsync()
End Function
End ClassNúmero 5: Problemas de fuentes y codificación
Cuando se trata de contenido internacional o fuentes personalizadas:
// Problem: Fonts not rendering correctly
var renderer = new ChromePdfRenderer();
// Solution 1: Install fonts on the server
// For Linux/Docker, add to Dockerfile:
// RUN apt-get install -y fonts-liberation fonts-noto
// Solution 2: Embed fonts in HTML
var html = @"
<html>
<head>
<style>
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
}
body { font-family: 'CustomFont', Arial, sans-serif; }
</style>
</head>
<body>
<p>Content with custom font</p>
</body>
</html>";
// Solution 3: Use web fonts
var htmlWithWebFont = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
<style>
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<p>日本語のテキスト</p>
</body>
</html>";
// Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8;// Problem: Fonts not rendering correctly
var renderer = new ChromePdfRenderer();
// Solution 1: Install fonts on the server
// For Linux/Docker, add to Dockerfile:
// RUN apt-get install -y fonts-liberation fonts-noto
// Solution 2: Embed fonts in HTML
var html = @"
<html>
<head>
<style>
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
}
body { font-family: 'CustomFont', Arial, sans-serif; }
</style>
</head>
<body>
<p>Content with custom font</p>
</body>
</html>";
// Solution 3: Use web fonts
var htmlWithWebFont = @"
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
<style>
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<p>日本語のテキスト</p>
</body>
</html>";
// Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8;' Problem: Fonts not rendering correctly
Dim renderer = New ChromePdfRenderer()
' Solution 1: Install fonts on the server
' For Linux/Docker, add to Dockerfile:
' RUN apt-get install -y fonts-liberation fonts-noto
' Solution 2: Embed fonts in HTML
Dim html = "
<html>
<head>
<style>
@font-face {
font-family: 'CustomFont';
src: url('data:font/woff2;base64,[base64-encoded-font]') format('woff2');
}
body { font-family: 'CustomFont', Arial, sans-serif; }
</style>
</head>
<body>
<p>Content with custom font</p>
</body>
</html>"
' Solution 3: Use web fonts
Dim htmlWithWebFont = "
<html>
<head>
<link href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP' rel='stylesheet'>
<style>
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<p>日本語のテキスト</p>
</body>
</html>"
' Ensure proper encoding
renderer.RenderingOptions.InputEncoding = Encoding.UTF8Obtener ayuda
Si encuentras problemas no cubiertos aquí,IronPDFproporciona excelentes recursos de soporte:
- Soporte de Chat en Vivo 24/7 - Habla con ingenieros en tiempo real con un tiempo de respuesta de 30 segundos
- Documentación Integral - Referencias y guías de API detalladas
- Base de Conocimientos - Soluciones a problemas comunes
- Ejemplos de Código - Fragmentos de código listos para usar
Al solicitar soporte, incluye:
- Versión de IronPDF
- Versión de .NET y plataforma
- Ejemplo de código mínimo que reproduzca el problema
- Archivos de registro (si disponibles)
- Trazado de pila o mensajes de error
¿Qué plataformas admitenIronPDFpara la generación de PDF?
El soporte multiplataforma deIronPDFasegura que tu código de generación de PDF funcione consistentemente en diferentes entornos. Ya sea que estés desplegando en servidores Windows, contenedores Linux, o plataformas en la nube,IronPDFproporciona la flexibilidad y confiabilidad necesarias para los despliegues de producción de tu generador de PDF en C#. Esta compatibilidad universal es una de las razones por las que organizaciones en más de 50 países confían enIronPDFpara generar millones de PDFs diariamente. Desde empresas Fortune 500 creando informes financieros hasta startups produciendo facturas para clientes,IronPDFescala para satisfacer cualquier demanda de creación de PDF en .NET. Entender las consideraciones específicas de la plataforma ayuda a asegurarse de que los despliegues sean fluidos a través de tu infraestructura - ya sea en servidores locales o entornos en la nube donde necesitas construir PDFs con C#.
Compatibilidad con versiones .NET
IronPDF es compatible con todas las versiones modernas de .NET y se actualiza continuamente para soportar las últimas versiones:
- .NET 8 - Soporte completo con todas las características
- .NET 9 - Totalmente soportado (actualmente la última versión)
- .NET 10 - Compatibilidad previa al lanzamiento disponible (IronPDF ya es compatible para el lanzamiento de noviembre de 2025)
- .NET 7, 6, 5 - Totalmente soportado
- .NET Core 3.1+ - Soportado con todas las características
- .NET Framework 4.6.2+ - Soporte legado mantenido
Soporte para sistemas operativos
Despliega tu solución de generación de PDF en cualquier sistema operativo principal:
Windows
- Windows 11, 10, 8, 7
- Windows Server 2022, 2019, 2016, 2012
Linux
- Ubuntu 20.04, 22.04, 24.04
- Debian 10, 11, 12
- CentOS 7, 8
- Red Hat Enterprise Linux
- Alpine Linux (con configuración adicional)
macOS
- macOS 13 (Ventura) y más reciente
- Soporte nativo para Apple Silicon (M1/M2/M3)
- Macs basados en Intel totalmente soportados
Despliegue de plataformas en la nube
IronPDF funciona sin problemas en todas las principales plataformas en la nube:
Microsoft Azure
// Azure App Service configuration
// Use at least B1 tier for optimal performance
// Enable 64-bit platform in Configuration settings
// For Azure Functions
public static class PdfFunction
{
[FunctionName("GeneratePdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
{
var renderer = new ChromePdfRenderer();
var html = await new StreamReader(req.Body).ReadToEndAsync();
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}// Azure App Service configuration
// Use at least B1 tier for optimal performance
// Enable 64-bit platform in Configuration settings
// For Azure Functions
public static class PdfFunction
{
[FunctionName("GeneratePdf")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
{
var renderer = new ChromePdfRenderer();
var html = await new StreamReader(req.Body).ReadToEndAsync();
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
return new FileContentResult(pdf.BinaryData, "application/pdf");
}
}' Azure App Service configuration
' Use at least B1 tier for optimal performance
' Enable 64-bit platform in Configuration settings
' For Azure Functions
Public Module PdfFunction
<FunctionName("GeneratePdf")>
Public Async Function Run(<HttpTrigger(AuthorizationLevel.Function, "post")> ByVal req As HttpRequest) As Task(Of IActionResult)
Dim renderer = New ChromePdfRenderer()
Dim html = Await (New StreamReader(req.Body)).ReadToEndAsync()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Return New FileContentResult(pdf.BinaryData, "application/pdf")
End Function
End ModuleServicios web de Amazon (AWS)
// AWS Lambda configuration
// Use custom runtime or container deployment
// Ensure Lambda has at least 512MB memory
public class PdfLambdaFunction
{
private readonly ChromePdfRenderer _renderer;
public PdfLambdaFunction()
{
_renderer = new ChromePdfRenderer();
// Configure for Lambda environment
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
}
public async Task<APIGatewayProxyResponse> FunctionHandler(
APIGatewayProxyRequest request,
ILambdaContext context)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(request.Body);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/pdf" }
},
Body = Convert.ToBase64String(pdf.BinaryData),
IsBase64Encoded = true
};
}
}// AWS Lambda configuration
// Use custom runtime or container deployment
// Ensure Lambda has at least 512MB memory
public class PdfLambdaFunction
{
private readonly ChromePdfRenderer _renderer;
public PdfLambdaFunction()
{
_renderer = new ChromePdfRenderer();
// Configure for Lambda environment
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
}
public async Task<APIGatewayProxyResponse> FunctionHandler(
APIGatewayProxyRequest request,
ILambdaContext context)
{
var pdf = await _renderer.RenderHtmlAsPdfAsync(request.Body);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/pdf" }
},
Body = Convert.ToBase64String(pdf.BinaryData),
IsBase64Encoded = true
};
}
}' AWS Lambda configuration
' Use custom runtime or container deployment
' Ensure Lambda has at least 512MB memory
Public Class PdfLambdaFunction
Private ReadOnly _renderer As ChromePdfRenderer
Public Sub New()
_renderer = New ChromePdfRenderer()
' Configure for Lambda environment
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled
End Sub
Public Async Function FunctionHandler(ByVal request As APIGatewayProxyRequest, ByVal context As ILambdaContext) As Task(Of APIGatewayProxyResponse)
Dim pdf = Await _renderer.RenderHtmlAsPdfAsync(request.Body)
Return New APIGatewayProxyResponse With {
.StatusCode = 200,
.Headers = New Dictionary(Of String, String) From {
{"Content-Type", "application/pdf"}
},
.Body = Convert.ToBase64String(pdf.BinaryData),
.IsBase64Encoded = True
}
End Function
End ClassPlataforma en la nube de Google
# app.yaml for App Engine
runtime: aspnetcore
env: flex
# Use 2nd generation for Cloud Run
# Deploy with: gcloud run deploy --execution-environment gen2# app.yaml for App Engine
runtime: aspnetcore
env: flex
# Use 2nd generation for Cloud Run
# Deploy with: gcloud run deploy --execution-environment gen2Despliegue de contenedores (Docker/Kubernetes)
IronPDF está listo para contenedores con soporte completo para Docker y Kubernetes:
# Multi-stage Dockerfile for optimal size
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["YourApp.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
# InstallIronPDFdependencies
RUN apt-get update && apt-get install -y \
libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
libcups2 libxkbcommon0 libxcomposite1 libxdamage1 \
libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "YourApp.dll"]Soporte para aplicaciones de escritorio
IronPDF funciona con los principales marcos .NET de escritorio:
WPF (Windows Presentation Foundation)
public partial class MainWindow : Window
{
private async void GeneratePdfButton_Click(object sender, RoutedEventArgs e)
{
var renderer = new ChromePdfRenderer();
var html = HtmlEditor.Text;
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
var saveDialog = new SaveFileDialog
{
Filter = "PDF files (*.pdf)|*.pdf",
DefaultExt = "pdf"
};
if (saveDialog.ShowDialog() == true)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show("PDF saved successfully!");
}
}
}public partial class MainWindow : Window
{
private async void GeneratePdfButton_Click(object sender, RoutedEventArgs e)
{
var renderer = new ChromePdfRenderer();
var html = HtmlEditor.Text;
var pdf = await renderer.RenderHtmlAsPdfAsync(html);
var saveDialog = new SaveFileDialog
{
Filter = "PDF files (*.pdf)|*.pdf",
DefaultExt = "pdf"
};
if (saveDialog.ShowDialog() == true)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show("PDF saved successfully!");
}
}
}Partial Public Class MainWindow
Inherits Window
Private Async Sub GeneratePdfButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim renderer = New ChromePdfRenderer()
Dim html = HtmlEditor.Text
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(html)
Dim saveDialog = New SaveFileDialog With {
.Filter = "PDF files (*.pdf)|*.pdf",
.DefaultExt = "pdf"
}
If saveDialog.ShowDialog() = True Then
pdf.SaveAs(saveDialog.FileName)
MessageBox.Show("PDF saved successfully!")
End If
End Sub
End ClassWindows Forms
public partial class PdfGeneratorForm : Form
{
private void btnGeneratePdf_Click(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "PDF files|*.pdf";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show($"PDF saved to {saveDialog.FileName}");
}
}
}
}public partial class PdfGeneratorForm : Form
{
private void btnGeneratePdf_Click(object sender, EventArgs e)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "PDF files|*.pdf";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
pdf.SaveAs(saveDialog.FileName);
MessageBox.Show($"PDF saved to {saveDialog.FileName}");
}
}
}
}Partial Public Class PdfGeneratorForm
Inherits Form
Private Sub btnGeneratePdf_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(txtHtml.Text)
Using saveDialog = New SaveFileDialog()
saveDialog.Filter = "PDF files|*.pdf"
If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
pdf.SaveAs(saveDialog.FileName)
MessageBox.Show($"PDF saved to {saveDialog.FileName}")
End If
End Using
End Sub
End ClassMAUI (Multi-platform App UI)
public partial class MainPage : ContentPage
{
public async Task GeneratePdfAsync()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(HtmlContent);
// Save to app's document directory
var documentsPath = FileSystem.Current.AppDataDirectory;
var filePath = Path.Combine(documentsPath, "output.pdf");
await File.WriteAllBytesAsync(filePath, pdf.BinaryData);
await DisplayAlert("Success", $"PDF saved to {filePath}", "OK");
}
}public partial class MainPage : ContentPage
{
public async Task GeneratePdfAsync()
{
var renderer = new ChromePdfRenderer();
var pdf = await renderer.RenderHtmlAsPdfAsync(HtmlContent);
// Save to app's document directory
var documentsPath = FileSystem.Current.AppDataDirectory;
var filePath = Path.Combine(documentsPath, "output.pdf");
await File.WriteAllBytesAsync(filePath, pdf.BinaryData);
await DisplayAlert("Success", $"PDF saved to {filePath}", "OK");
}
}Partial Public Class MainPage
Inherits ContentPage
Public Async Function GeneratePdfAsync() As Task
Dim renderer = New ChromePdfRenderer()
Dim pdf = Await renderer.RenderHtmlAsPdfAsync(HtmlContent)
' Save to app's document directory
Dim documentsPath = FileSystem.Current.AppDataDirectory
Dim filePath = Path.Combine(documentsPath, "output.pdf")
Await File.WriteAllBytesAsync(filePath, pdf.BinaryData)
Await DisplayAlert("Success", $"PDF saved to {filePath}", "OK")
End Function
End ClassCómo empezar a crear PDF
¿Listo para empezar a crear PDFs en tu aplicación C#? Sigue esta guía paso a paso para ir desde la instalación hasta tu primer PDF generado.IronPDFfacilita comenzar, con recursos comprensivos y soporte disponible en cada paso del camino.
Paso 1: Instalar IronPDF
Elige el método de instalación que funcione mejor para tu entorno de desarrollo:
Administrador de paquetes de Visual Studio** (Recomendado)
- Abre tu proyecto en Visual Studio
- Haz clic derecho en tu proyecto en el Explorador de Soluciones
- Selecciona "Gestionar Paquetes NuGet"
- Busca "IronPDF"
- Haz clic en Instalar en el paquete de IronPdf de Iron Software
Consola del Gestor de Paquetes**
Install-Package IronPdf
.NET CLI
dotnet add package IronPdf
El paquete NuGet incluye todo lo necesario para la generación de PDF en Windows, Linux, y macOS. Para despliegues especializados, considera estos paquetes específicos de plataforma que optimizan el tamaño y el rendimiento:
IronPdf.Linux- Optimizado para entornos LinuxIronPdf.MacOs- Soporte nativo para Apple SiliconIronPdf.Slim- Paquete mínimo que descarga dependencias en tiempo de ejecución
Paso 2: Cree su primer PDF
Comienza con un ejemplo simple para verificar que todo esté funcionando:
using IronPdf;
class Program
{
static void Main()
{
// Create a new PDF generator instance
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Welcome to IronPDF!</h1>
<p>This is your first generated PDF document.</p>
<p>Created on: " + DateTime.Now + "</p>"
);
// Save the PDF
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF created successfully!");
}
}using IronPdf;
class Program
{
static void Main()
{
// Create a new PDF generator instance
var renderer = new ChromePdfRenderer();
// Generate PDF from HTML
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Welcome to IronPDF!</h1>
<p>This is your first generated PDF document.</p>
<p>Created on: " + DateTime.Now + "</p>"
);
// Save the PDF
pdf.SaveAs("my-first-pdf.pdf");
Console.WriteLine("PDF created successfully!");
}
}Imports IronPdf
Friend Class Program
Shared Sub Main()
' Create a new PDF generator instance
Dim renderer = New ChromePdfRenderer()
' Generate PDF from HTML
Dim pdf = renderer.RenderHtmlAsPdf("
<h1>Welcome to IronPDF!</h1>
<p>This is your first generated PDF document.</p>
<p>Created on: " & DateTime.Now & "</p>")
' Save the PDF
pdf.SaveAs("my-first-pdf.pdf")
Console.WriteLine("PDF created successfully!")
End Sub
End ClassPaso 3: Explorar ejemplos y tutoriales
IronPDF proporciona extensos recursos para ayudarte a dominar la generación de PDF:
- Ejemplos de Código - Fragmentos de código listos para usar para escenarios comunes
- Tutoriales - Guías paso a paso para características específicas
- Guías Cómo Hacerlo - Soluciones prácticas a problemas del mundo real
- Referencia de API - Documentación comprensiva de todas las clases y métodos
Paso 4: Obtenga ayuda cuando la necesite
IronPDF ofrece múltiples canales de soporte para asegurar tu éxito:
- Soporte de chat en vivo 24/7 - Chatea con ingenieros en tiempo real para obtener asistencia inmediata
- Soporte por correo electrónico - Obtén respuestas detalladas a preguntas complejas
- Stack Overflow - Soporte y soluciones de la comunidad
Paso 5: Desarrollo e implantación
Licencia de desarrollo gratuita
IronPDF es gratuito para desarrollo y pruebas. Puedes explorar todas las características sin limitaciones durante el desarrollo. Las marcas de agua aparecen en los PDFs generados en modo de desarrollo pero no afectan la funcionalidad.
Opciones de despliegue en producción
Cuando estés listo para implementar en producción,IronPDFofrece licencias flexibles:
- Prueba Gratuita - Obtén una licencia de prueba de 30 días para probar en producción sin marcas de agua
- Licencias Comerciales - Comenzando en $799 para despliegue de un solo proyecto
- Soluciones Empresariales - Paquetes personalizados para grandes organizaciones
Para aplicar una licencia en tu código:
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"Paso 6: Manténgase al día
Mantén tus capacidades de generación de PDF actualizadas:
- Suscríbete a las Actualizaciones - Recibe notificaciones sobre nuevas características y mejoras
- Sigue el Blog - Aprende sobre mejores prácticas y nuevas técnicas
- Consulta el Registro de Cambios - Mira qué hay de nuevo en cada lanzamiento
Las actualizaciones regulares aseguran la compatibilidad con las últimas versiones de .NET e incluyen mejoras de rendimiento, nuevas características y actualizaciones de seguridad.
¿Por qué elegirIronPDFpara la generación de PDF en C#?
Después de explorar varios métodos para crear PDFs en C#, podrías preguntarte qué hace deIronPDFla opción preferida para muchos desarrolladores. No se trata solo de características - se trata de la experiencia completa del desarrollador, desde la implementación inicial hasta el mantenimiento a largo plazo cuando necesitas generar PDFs en .NET. Con más de 14 millones de desarrolladores usandoIronPDFglobalmente como su generador de PDF en C#, se ha convertido en el estándar de facto para generación de PDF en aplicaciones .NET. Examinemos por qué los desarrolladores eligenIronPDFpara sus necesidades de creación de PDF en C#.
Renderizado perfecto
A diferencia de otras bibliotecas PDF que producen aproximaciones de tus diseños en HTML,IronPDFutiliza un motor real de Chromium para asegurar que tus PDFs se vean exactamente como lo harían en un navegador web moderno. Esta capacidad de renderización perfecta de píxeles es por lo que las instituciones financieras confían enIronPDFpara generar informes regulatorios donde la precisión importa. Tus diseños de CSS Grid, diseños flexbox y contenido renderizado con JavaScript funcionan perfectamente. No más luchar con motores de diseño propietarios o aceptar resultados "lo suficientemente cercanos" cuando creas documentos PDF.
API fácil de usar para desarrolladores
La API deIronPDFestá diseñada por desarrolladores, para desarrolladores. La simplicidad de la API es por lo que las startups pueden hacer que su generación de PDF funcione en horas, no en días. En lugar de aprender especificaciones complejas de PDF, trabajas con conceptos familiares:
using IronPdf;
// Other libraries might require this:
// document.Add(new Paragraph("Hello World"));
// document.Add(new Table(3, 2));
// cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
// With IronPDF, just use HTML:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Hello World</h1>
<table>
<tr style='background: lightgray;'>
<td>Simple</td>
<td>Intuitive</td>
</tr>
</table>
");using IronPdf;
// Other libraries might require this:
// document.Add(new Paragraph("Hello World"));
// document.Add(new Table(3, 2));
// cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
// With IronPDF, just use HTML:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(@"
<h1>Hello World</h1>
<table>
<tr style='background: lightgray;'>
<td>Simple</td>
<td>Intuitive</td>
</tr>
</table>
");Imports IronPdf
' Other libraries might require this:
' document.Add(new Paragraph("Hello World"));
' document.Add(new Table(3, 2));
' cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
' With IronPDF, just use HTML:
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("
<h1>Hello World</h1>
<table>
<tr style='background: lightgray;'>
<td>Simple</td>
<td>Intuitive</td>
</tr>
</table>
")Características listas para la empresa
IronPDF incluye características que las aplicaciones empresariales demandan, por eso las empresas Fortune 500 confían en él para la generación de documentos crítica:
- Seguridad: Cifrado, firmas digitales y controles de permisos protegen documentos sensibles
- Conformidad: El soporte de PDF/A y PDF/UA asegura que tus PDFs generados cumplan con los requisitos regulatorios
- Rendimiento: Operaciones asíncronas y procesamiento por lotes manejan millones de documentos eficientemente
- Confiabilidad: Extensa gestión de errores y registro ayudan a mantener el tiempo de actividad en producción
Soporte excepcional
Cuando necesitas ayuda, el equipo de soporte deIronPDFestá compuesto por verdaderos ingenieros que entienden tus desafíos. Con soporte de chat en vivo 24/7 y tiempos de respuesta típicos inferiores a 30 segundos, nunca estás esperando respuestas. Este nivel de soporte es por lo que los desarrolladores consistentemente califican aIronPDFcomo el mejor soporte en la industria. El equipo de soporte puede ayudar con todo, desde preguntas básicas hasta desafíos de implementación complejos, asegurando que tus proyectos de generación de PDF tengan éxito.
Precios transparentes
Sin tarifas ocultas, sin costos sorpresa, sin complicaciones de licencias por servidor. El modelo de licencia directo deIronPDFsignifica que sabes exactamente por qué estás pagando. El desarrollo es siempre gratuito, y las licencias de producción son perpetuas - las posees para siempre. Esta transparencia es refrescante en una industria conocida por esquemas de licencia complejos.
Desarrollo Activo
IronPDF es mejorado continuamente con actualizaciones mensuales que agregan características, mejoran el rendimiento y aseguran la compatibilidad con los últimos lanzamientos de .NET. El equipo monitorea activamente la retroalimentación de los clientes e implementa características solicitadas regularmente. Las adiciones recientes incluyen manejo mejorado de formularios, capacidades mejoradas para editar PDFs, y optimizaciones para implementaciones en la nube.
Éxitos reales
Miles de compañías en industrias confían enIronPDFpara generación de PDF crítica:
- Finanzas: Los bancos generan millones de estados e informes mensualmente utilizando las características de documentos seguros de IronPDF
- Salud: Los hospitales crean registros de pacientes y resultados de laboratorio con configuraciones de seguridad compatibles con HIPAA
- Comercio Electrónico: Los minoristas en línea producen facturas y etiquetas de envío a escala, manejando cargas pico sin esfuerzo
- Gobierno: Las agencias generan documentos oficiales y formularios con firmas digitales y cifrado
Estas organizaciones eligenIronPDFporque ofrece resultados consistentes a escala - ya sea generando una sola factura o procesando millones de documentos diariamente.
¿Cómo se comparaIronPDFcon otras bibliotecas de C# PDF?
Elegir la biblioteca PDF correcta es crucial para el éxito de tu proyecto cuando necesitas generar PDFs en C#. Veamos cómoIronPDFse compara con otras opciones populares en el ecosistema .NET para creación de PDF. Esta comparación se basa en el uso en el mundo real, la retroalimentación de los desarrolladores y las capacidades técnicas para aquellos que buscan construir PDFs en .NET. Entender estas diferencias te ayuda a elegir el mejor generador de PDF en C# para tus necesidades específicas.
Tabla comparativa
| Característica | IronPDF | wkhtmltopdf | QuestPDF | iText 7 | PdfSharp | Syncfusion | Aspose.PDF |
|---|---|---|---|---|---|---|---|
| Calidad de HTML a PDF | Perfecta de Píxeles | Estilo Impresión | N/A | Limitado | Sin HTML | Buena | Buena |
| Soporte HTML5/CSS3 | Completo | Desactualizado | Sólo Código | Parcial | Ninguno | Completo | Completo |
| Soporte JavaScript | Completo | No | No | Limitado | No | Limitado | Limitado |
| Facilidad de uso | 3 Líneas | Solo CLI | Código-Primero | Complejo | Bajo Nivel | Buena | Complejo |
| Dependencias del Servidor | Ninguno | Ejecutable | Ninguno | Ninguno | Ninguno | Ninguno | Ninguno |
| Rendimiento | Rápido + Asíncrono | Lento | Rápido | Rápido | Rápido | Rápido | Rápido |
| Desarrollo Activo | Muy Activo | Abandonado | Activo | Activo | Mínimo | Activo | Activo |
| Tipo de Licencia | Comercial | Código Abierto | MIT→Comercial* | AGPL/Comercial | MIT | Comercial | Comercial |
| Precio Inicial | $799 | Gratis | $599+* | $2,399+ | Gratis | $2,995+ | $2,499+ |
*Nota: QuestPDF recientemente cambió de MIT a licencia comercial
Comparaciones detalladas
IronPDFvs wkhtmltopdf
- wkhtmltopdf es gratuito pero fue abandonado en 2020 y produce PDFs con aspecto anticuado
- Requiere ejecutables específicos de plataforma que complican el despliegue
- Sin soporte JavaScript significa que las aplicaciones web modernas no se renderizarán correctamente -IronPDFofrece renderizado moderno sin dependencias externas
IronPDFfrente a QuestPDF
- QuestPDF requiere construir PDFs completamente en código C# sin soporte HTML
- Bueno para creación de PDFs programática pero consume tiempo para diseños complejos
- Cambió recientemente de licencia MIT a comercial -IronPDFte permite usar las habilidades HTML/CSS que ya tienes
IronPDFfrente a iText 7
- iText tiene licencia AGPL que puede 'infectar' tu código fuente
- Licencias comerciales comienzan en $1,999 con precios complejos
- Capacidades limitadas de HTML a PDF con pobre soporte CSS -IronPDFofrece un renderizado HTML superior a un precio más bajo
IronPDFfrente a PdfSharp
- PdfSharp es bueno para manipulación de PDF a nivel bajo pero no tiene soporte HTML
- Requiere posicionar manualmente cada elemento en la página
- Gratis y código abierto pero muy limitado en características -IronPDFmaneja tanto operaciones HTML de alto nivel como PDF de bajo nivel
IronPDFfrente a Syncfusion/Aspose.PDF
- Ambos son opciones empresariales con buenas características pero precios más altos
- Syncfusion comienza en $2,995, Aspose en $2,499
- Ninguno logra el mismo renderizado perfecto de píxeles HTML que IronPDF -IronPDFofrece mejor valor con características empresariales comparables
Vías de migración
Muchos desarrolladores se cambian aIronPDFdesde otras bibliotecas. Aquí está el porqué:
De wkhtmltopdf
- 'Estábamos cansados de lidiar con binarios específicos de plataforma y renderizado anticuado'
- 'IronPDF nos dio soporte CSS moderno y eliminó nuestros dolores de cabeza con Docker'
Desde iTextSharp/iText 7
- 'La curva de aprendizaje estaba matando nuestra productividad -IronPDFnos permitió usar HTML en su lugar'
- 'La licencia AGPL fue un impedimento para nuestro producto comercial'
De PdfSharp
- 'Necesitábamos conversión de HTML a PDF, que PdfSharp simplemente no hace'
- 'Posicionar manualmente cada elemento tomaba una eternidad'
De QuestPDF
- 'Construir diseños en código C# fue tedioso comparado con usar HTML/CSS'
- 'El reciente cambio de licencia nos hizo reconsiderar nuestras opciones'
Conclusión
Crear PDFs en C# no tiene que ser complicado. Con IronPDF, puedes generar documentos PDF profesionales usando las habilidades de HTML y CSS que ya tienes. Ya sea que estés construyendo informes simples o documentos complejos con gráficos y formularios,IronPDFhace el trabajo pesado para que puedas enfocarte en tu lógica de aplicación. Únete a los 14 millones de desarrolladores en todo el mundo que confían enIronPDFcomo su generador de PDF en C# para producir PDFs de manera confiable y eficiente.
A lo largo de esta guía, hemos explorado cómo crear documentos PDF utilizando múltiples enfoques - desde cadenas y URLs HTML hasta convertir archivos existentes como documentos Word y Markdown. Hemos visto cómo el motor de renderizado moderno basado en Chromium de IronPDF produce resultados perfectos de píxeles que realmente se ven como tus diseños web, no impresiones obsoletas. La capacidad de manipular documentos PDF programáticamente, agregar características de seguridad y optimizar el rendimiento hace queIronPDFsea una solución completa para todas tus tareas de generación de PDF en .NET.
Lo que distingue aIronPDFes su enfoque centrado en el desarrollador. Con solo tres líneas de código, puedes generar tu primer PDF. La API intuitiva significa que pasas menos tiempo aprendiendo sintaxis propietaria de PDF y más tiempo construyendo características. Combinado con excelente soporte por parte de ingenieros reales, precios transparentes y actualizaciones continuas (incluyendo apoyo anticipado para .NET 10),IronPDFte da confianza en que tu creación de PDF en C# funcionará hoy y en el futuro.
Comienza a crear PDFs hoy - obtén tu licencia de prueba gratuita y descubre lo fácil que puede ser la generación de PDF en .NET en tus aplicaciones. Con IronPDF, estarás generando PDFs profesionales en minutos, no horas.
¿Listo para construir tu primer PDF? Comienza con IronPDF - es gratuito para el desarrollo, y estarás creando PDFs con C# en minutos.
Preguntas Frecuentes
¿Cómo puedo crear un PDF desde contenido HTML en C#?
Puede crear un PDF desde contenido HTML en C# usando el método RenderHtmlAsPdf de IronPDF. Esto le permite convertir directamente cadenas HTML o URLs en documentos PDF con facilidad.
¿Cuáles son las ventajas de usar una biblioteca PDF comercial sobre una gratuita?
Las bibliotecas PDF comerciales como IronPDF ofrecen funciones robustas, como soporte completo para JavaScript, CSS3 y diseños responsivos. Proporcionan rendimiento confiable, actualizaciones regulares, soporte integral y están optimizadas para crear PDFs de alta calidad.
¿Se puede usar IronPDF para generar PDFs en aplicaciones ASP.NET MVC?
Sí, IronPDF se puede utilizar en aplicaciones ASP.NET MVC para convertir vistas Razor o plantillas HTML en PDFs, permitiéndole integrar sin problemas la generación de PDFs en sus aplicaciones web.
¿Cómo puedo integrar imágenes y CSS en mis documentos PDF usando C#?
Usando IronPDF, puede integrar fácilmente imágenes y CSS en sus documentos PDF. Esto se puede lograr incluyendo etiquetas de imagen y estilos CSS dentro de su contenido HTML antes de convertirlo en PDF utilizando las capacidades de renderizado de IronPDF.
¿Es posible agregar encabezados, pies de página y números de página a PDFs en C#?
Sí, IronPDF proporciona funciones avanzadas que le permiten agregar encabezados, pies de página y numeración de páginas a sus documentos PDF. Esto se puede hacer configurando las opciones del PDF antes de renderizar su contenido HTML.
¿Cómo puedo manejar datos XML al generar PDFs en C#?
Con IronPDF, puede manejar datos XML transformando su XML en HTML o usando XSLT para dar estilo al XML, que luego se puede convertir en un documento PDF utilizando el método RenderHtmlAsPdf de IronPDF.
¿Cuáles son los desafíos comunes al generar PDFs en C#?
Los desafíos comunes incluyen mantener la coherencia del diseño, manejar CSS y JavaScript complejos, y garantizar un renderizado preciso de las tecnologías web. IronPDF aborda estos desafíos con su moderno motor Chromium y su extenso soporte para estándares HTML5 y CSS3.
¿Cómo puedo generar grandes PDFs de manera eficiente con C#?
IronPDF está diseñado para manejar la generación de grandes PDFs de manera eficiente. Utiliza un motor de renderizado de alto rendimiento y admite operaciones asincrónicas para gestionar documentos grandes con facilidad.
¿Puedo probar IronPDF sin una licencia comercial?
Sí, IronPDF ofrece una licencia gratuita para desarrollo y pruebas, permitiéndole evaluar sus características antes de comprar una licencia comercial para uso en producción.
Compatibilidad con .NET 10: ¿Puedo usar IronPDF con .NET 10? ¿Hay alguna consideración especial que deba tener en cuenta?
Sí, IronPDF es totalmente compatible con .NET 10. Es compatible con .NET 10 de fábrica, incluso en proyectos para Windows, Linux, entornos contenedorizados y frameworks web. No requiere ninguna configuración especial: basta con instalar el paquete NuGet de IronPDF más reciente y funcionará a la perfección con .NET 10.






