How to Convert HTML to PDF in C# .NET Core
Convertir a PDFs desde varios formatos puede ser un desafío debido a los estrictos estándares del formato PDF. La conversión no puede producir una coincidencia uno a uno en muchos casos, especialmente cuando se trata de estilo HTML y CSS. Sin embargo, en el panorama digital de hoy, la capacidad de convertir URLs y formularios, incluidos aquellos con HTML y CSS, es esencial. Aquí es donde IronPDF sobresale, ofreciendo características intuitivas que permiten a los desarrolladores convertir una amplia gama de formatos a PDF con alta fidelidad, a menudo en solo unas pocas líneas de código.
Con IronPDF, puede convertir fácilmente HTML, DOCX, RTF, Markdown, e incluso imágenes a PDF, asegurando que la integridad de sus documentos se mantenga. También soporta la conversión de páginas web dinámicas de populares frameworks como Razor, CSHTML, ASPX y XAML, eliminando preocupaciones de compatibilidad y convirtiendo IronPDF en su solución integral para todas las necesidades de conversión a PDF.
Además de la conversión directa, IronPDF ofrece potentes opciones de personalización. Puede adaptar su salida PDF con márgenes personalizados, encabezados y pies de página para incluir números de página y ajustar configuraciones de escala de grises para reducir el tamaño del archivo. Mejore sus documentos incorporando características adicionales como una tabla de contenidos, saltos de página automáticos y contenido que se ajusta perfectamente al tamaño de documento deseado.
En este tutorial, exploraremos estas capacidades y más, proporcionando ejemplos de código y destacando las características clave de IronPDF. Prepárese para transformar su proceso de conversión a PDF, lo que le permitirá convertir, personalizar y optimizar sus documentos PDF sin esfuerzo con IronPDF.
Inicio rápido: Convertir HTML a PDF con IronPDF
Comience con IronPDF para convertir HTML a PDF sin esfuerzo en .NET Core. Con solo una línea de código, puede renderizar PDFs con precisión de píxel desde cadenas HTML utilizando la poderosa API de IronPDF. Esta guía le mostrará cómo integrar rápidamente IronPDF en su proyecto, permitiendo una generación de PDFs sin problemas con una configuración mínima. Ya sea que esté convirtiendo HTML, URLs o vistas Razor, IronPDF simplifica el proceso, haciéndolo accesible para desarrolladores de todos los niveles. Comience a convertir hoy y explore características avanzadas cuando esté listo.
-
Instala IronPDF con el Administrador de Paquetes NuGet
PM > Install-Package IronPdf -
Copie y ejecute este fragmento de código.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello, PDF!</h1>"); -
Despliegue para probar en su entorno real
Comienza a usar IronPDF en tu proyecto hoy mismo con una prueba gratuita
Tabla de contenido
- Conversión Versátil de PDF
- PDF desde Cadena HTML
- PDF desde Archivo HTML
- PDF desde URL
- Imagen a PDF
- Imagen desde PDF
- Convertir DOCX a PDF
- Convertir RTF a PDF
- Convertir MD a PDF
- Convertir XML a PDF
- PDF a HTML
- Página Web Dinámica a PDFs
- PDF desde Páginas ASPX
- XAML a PDF (MAUI)
- Generar Reportes PDF
- Crear PDFs en Servidores Blazor
- Razor a PDF (Servidor Blazor)
- Resumen de CSHTML a PDF
- CSHTML a PDF (Páginas Razor)
- CSHTML a PDF (MVC Core)
- CSHTML a PDF (MVC Framework)
- CSHTML a PDF (Sin Interfaz)
- Accesibilidad Web
- Inicio de sesión en sitios web y sistemas TLS
- Cookies
- Cabecera de Solicitud HTTP
- Conversión de PDF Personalizada
- Opciones de Renderizado
- Establecer Márgenes Personalizados
- Escala de Grises
- Refinar el Diseño del PDF
- Agregar Una Tabla de Contenidos
- Salto de Página
- Ajuste al Papel y Zoom
Conversión versátil de PDF
PDF a partir de cadena HTML
Para convertir un PDF a partir de una cadena HTML, podemos utilizar el método RenderHtmlAsPdf para transformar rápidamente la cadena HTML en un PDF con píxeles perfectos.
:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
' Export to a file or Stream
pdf.SaveAs("output.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
PDF a partir de HTML
Convierta fácilmente un archivo HTML a PDF con nuestro método RenderHtmlAsPdf y guarde rápidamente su PDF con píxeles perfectos.
:path=/static-assets/pdf/content-code-examples/how-to/html-file-to-pdf.cs
using IronPdf;
using IronPdf.Engines.Chrome;
using IronPdf.Rendering;
var renderer = new ChromePdfRenderer
{
RenderingOptions = new ChromePdfRenderOptions
{
CssMediaType = PdfCssMediaType.Print,
MarginBottom = 0,
MarginLeft = 0,
MarginRight = 0,
MarginTop = 0,
Timeout = 120,
},
};
renderer.RenderingOptions.WaitFor.RenderDelay(50);
// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports IronPdf.Engines.Chrome
Imports IronPdf.Rendering
Private renderer = New ChromePdfRenderer With {
.RenderingOptions = New ChromePdfRenderOptions With {
.CssMediaType = PdfCssMediaType.Print,
.MarginBottom = 0,
.MarginLeft = 0,
.MarginRight = 0,
.MarginTop = 0,
.Timeout = 120
}
}
renderer.RenderingOptions.WaitFor.RenderDelay(50)
' Create a PDF from an existing HTML file using C#
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")
' Export to a file or Stream
pdf.SaveAs("output.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
PDF desde URL
Convierta la URL a PDF rápidamente con RenderUrlAsPdf en solo unas pocas líneas. Introduzca la URL como parámetro y guárdela fácilmente.
:path=/static-assets/pdf/content-code-examples/how-to/url-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a URL or local file path
Private pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
' Export to a file or Stream
pdf.SaveAs("url.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Imagen a PDF
¿Tiene una imagen que desea mostrar como PDF? Conviértala rápidamente con nuestra clase ImageToPdfConverter y llame al método ImageToPdf.
:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image.cs
using IronPdf;
string imagePath = "meetOurTeam.jpg";
// Convert an image to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath);
// Export the PDF
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf
Private imagePath As String = "meetOurTeam.jpg"
' Convert an image to a PDF
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath)
' Export the PDF
pdf.SaveAs("imageToPdf.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Imagen del PDF
Para lo opuesto al ejemplo anterior, primero podemos convertir la entrada en un PDF y luego usar el método RasterizeToImageFiles para convertir el PDF en imágenes.
:path=/static-assets/pdf/content-code-examples/how-to/rasterize-pdf-to-images-rasterize.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render PDF from web URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
// Export images from PDF
pdf.RasterizeToImageFiles("wikipage_*.png");
Imports IronPdf
' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()
' Render PDF from web URL
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
' Export images from PDF
pdf.RasterizeToImageFiles("wikipage_*.png")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Convertir DOCX a PDF
¿Alguna vez ha necesitado convertir un archivo DOCX, como un currículum, a PDF fácilmente? IronPDF le tiene cubierto. Simplemente llame al método RenderDocxAsPDF para convertir.
:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-from-file.cs
using IronPdf;
// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();
// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");
// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()
' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")
' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Convertir RTF a PDF
Para convertir un archivo RTF a PDF, llamamos al método RenderRtfFileAsPdf con el archivo RTF como entrada.
:path=/static-assets/pdf/content-code-examples/how-to/rtf-to-pdf-from-file.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render from RTF file
PdfDocument pdf = renderer.RenderRtfFileAsPdf("sample.rtf");
// Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Render from RTF file
Private pdf As PdfDocument = renderer.RenderRtfFileAsPdf("sample.rtf")
' Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Convertir MD a PDF
Para convertir un MD a un PDF, podemos llamar al método RenderMarkdownFileAsPdf con el archivo MD como entrada.
:path=/static-assets/pdf/content-code-examples/how-to/md-to-pdf-from-file.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render from markdown file
PdfDocument pdf = renderer.RenderMarkdownFileAsPdf("sample.md");
// Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Render from markdown file
Private pdf As PdfDocument = renderer.RenderMarkdownFileAsPdf("sample.md")
' Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Convertir XML a PDF
Aunque convertir XML a PDF puede ser bastante desafiante, IronPDF aún está a la altura del desafío y ayuda a convertir XML a PDF en unos pocos pasos. Comenzamos con una plantilla XLST y luego convertimos el XML a PDF a través de HTML mediante transformaciones XLST. A continuación se presenta una versión abreviada del fragmento de código para ayudarle a comenzar.
// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
text-align: center;
padding: 20px;
border: 1px solid #CDE7F0;
}
th{
color: white;
padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
<table style='border-collapse: collapse;'>
<thead>
<tr>
<th colspan='3'>
<img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
</th>
</tr>
</thead>
<tbody>
<tr bgcolor='#9acd32'>
<th bgcolor='#32ab90'>Title</th>
<th bgcolor='#f49400'>Feature</th>
<th bgcolor='#2a95d5'>Compatible</th>
</tr>
<xsl:for-each select='catalog/cd'>
<tr>
<td style='font-weight: bold;'><xsl:value-of select='title'/></td>
<td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
<td><xsl:value-of select='compatible'/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";
[...]
// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();
// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
transform.Load(reader);
}
// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
transform.Transform(reader, null, results);
}
// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
text-align: center;
padding: 20px;
border: 1px solid #CDE7F0;
}
th{
color: white;
padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
<table style='border-collapse: collapse;'>
<thead>
<tr>
<th colspan='3'>
<img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
</th>
</tr>
</thead>
<tbody>
<tr bgcolor='#9acd32'>
<th bgcolor='#32ab90'>Title</th>
<th bgcolor='#f49400'>Feature</th>
<th bgcolor='#2a95d5'>Compatible</th>
</tr>
<xsl:for-each select='catalog/cd'>
<tr>
<td style='font-weight: bold;'><xsl:value-of select='title'/></td>
<td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
<td><xsl:value-of select='compatible'/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";
[...]
// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();
// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
transform.Load(reader);
}
// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
transform.Transform(reader, null, results);
}
// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
Imports System.Xml
Imports System.IO
Imports System.Xml.Xsl
Imports IronPdf
' XSLT template that defines the transformation from XML to HTML
Dim xslt As String = "<?xml version='1.0' encoding='UTF-8'?>" & _
"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" & _
"<xsl:template match='/'>" & _
"<html>" & _
"<style>" & _
"td{" & _
" text-align: center;" & _
" padding: 20px;" & _
" border: 1px solid #CDE7F0;" & _
"}" & _
"th{" & _
" color: white;" & _
" padding: 20px;" & _
"}" & _
"</style>" & _
"<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>" & _
" <table style='border-collapse: collapse;'>" & _
" <thead>" & _
" <tr>" & _
" <th colspan='3'>" & _
" <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>" & _
" </th>" & _
" </tr>" & _
" </thead>" & _
" <tbody>" & _
" <tr bgcolor='#9acd32'>" & _
" <th bgcolor='#32ab90'>Title</th>" & _
" <th bgcolor='#f49400'>Feature</th>" & _
" <th bgcolor='#2a95d5'>Compatible</th>" & _
" </tr>" & _
" <xsl:for-each select='catalog/cd'>" & _
" <tr>" & _
" <td style='font-weight: bold;'><xsl:value-of select='title'/></td>" & _
" <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>" & _
" <td><xsl:value-of select='compatible'/></td>" & _
" </tr>" & _
" </xsl:for-each>" & _
" </tbody>" & _
" </table>" & _
"</body>" & _
"</html>" & _
"</xsl:template>" & _
"</xsl:stylesheet>"
[...]
' Create an instance of XslCompiledTransform
Dim transform As New XslCompiledTransform()
' Load the XSLT from a string
Using reader As XmlReader = XmlReader.Create(New StringReader(xslt))
transform.Load(reader)
End Using
' Transform the XML to HTML
Dim results As New StringWriter()
Using reader As XmlReader = XmlReader.Create(New StringReader(xml))
transform.Transform(reader, Nothing, results)
End Using
' Create a renderer for converting HTML to PDF
Dim renderer As New ChromePdfRenderer()
' Options, headers, and footers may be set here if needed
' Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
PDF a HTML
Además de convertir varios formatos a PDFs, IronPDF también soporta la operación inversa de convertir PDFs en HTML. Aquí hay un fragmento de código rápido para demostrar la funcionalidad.
:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-html.cs
using IronPdf;
using System;
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");
// Convert PDF to HTML string
string html = pdf.ToHtmlString();
Console.WriteLine(html);
// Convert PDF to HTML file
pdf.SaveAsHtml("myHtml.html");
Imports IronPdf
Imports System
Dim pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")
' Convert PDF to HTML string
Dim html As String = pdf.ToHtmlString()
Console.WriteLine(html)
' Convert PDF to HTML file
pdf.SaveAsHtml("myHtml.html")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Página web dinámica a PDF
¿Necesita que su página web dinámica se conserve y convierta a PDFs mientras se preserva el diseño y formato exacto? No busque más allá de IronPDF, que convierte rápidamente una variedad de populares frameworks de páginas web dinámicas a PDFs.
PDF a partir de páginas ASPX
Aquí hay un breve fragmento de código sobre la conversión de Páginas ASPX como PDF en Páginas de Servidor Activo.
:path=/static-assets/pdf/content-code-examples/how-to/aspx-to-pdf-2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPdf;
namespace AspxToPdfTutorial
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports IronPdf
Namespace AspxToPdfTutorial
Partial Public Class Invoice
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser)
End Sub
End Class
End Namespace
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
XAML a PDF (MAUI)
Para los desarrolladores que buscan construir aplicaciones multiplataforma, .NET MAUI es una elección popular entre los frameworks. IronPDF soporta por completo la conversión de XAML a PDF con unos pocos pasos.
:path=/static-assets/pdf/content-code-examples/how-to/xaml-to-pdf-maui-mainpage-xaml-cs.cs
using IronPdf.Extensions.Maui;
namespace mauiSample;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void PrintToPdf(object sender, EventArgs e)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply HTML header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
HtmlFragment = "<h1>Header</h1>",
};
// Render PDF from Maui Page
PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result;
pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf");
}
}
Imports IronPdf.Extensions.Maui
Namespace mauiSample
Partial Public Class MainPage
Inherits ContentPage
Public Sub New()
InitializeComponent()
End Sub
Private Sub PrintToPdf(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer As New ChromePdfRenderer()
' Apply HTML header
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"}
' Render PDF from Maui Page
Dim pdf As PdfDocument = renderer.RenderContentPageToPdf(Of MainPage, App)().Result
pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf")
End Sub
End Class
End Namespace
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Generar informes en PDF
Cuando se trata de generar reportes PDF, las dimensiones y el formato exactos son fundamentales. IronPDF le permite generar PDFs sin problemas con solo un par de pasos.
:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-html-file.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
Imports IronPdf
Private renderer As New ChromePdfRenderer()
renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Crear PDF en servidores Blazor
IronPDF soporta .NET 6, y como incluye tipos de proyecto como Blazor, este fragmento de código proporciona un breve ejemplo de cómo crear PDFs en Servidor Blazor.
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
@code {
// Model to bind user input
private InputHTMLModel _InputMsgModel = new InputHTMLModel();
private async Task SubmitHTML()
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Create a renderer to convert HTML to PDF
var render = new IronPdf.ChromePdfRenderer();
// Render the HTML input into a PDF document
var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
var fileName = "iron.pdf";
// Create a stream reference for the PDF content
using var streamRef = new DotNetStreamReference(stream: doc.Stream);
// Invoke JavaScript function to download the PDF in the browser
await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
}
public class InputHTMLModel
{
public string HTML { get; set; } = "My new message";
}
}
code
If True Then
' Model to bind user input
private InputHTMLModel _InputMsgModel = New InputHTMLModel()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' private async Task SubmitHTML()
' {
' ' Set your IronPDF license key
' IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
'
' ' Create a renderer to convert HTML to PDF
' var render = New IronPdf.ChromePdfRenderer();
'
' ' Render the HTML input into a PDF document
' var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
'
' var fileName = "iron.pdf";
'
' ' Create a stream reference for the PDF content
' var streamRef = New DotNetStreamReference(stream: doc.Stream);
'
' ' Invoke JavaScript function to download the PDF in the browser
' await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
' }
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' public class InputHTMLModel
' {
' public string HTML
' {
' get;
' set;
' } = "My new message";
' }
End If
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Razor a PDF (Servidores Blazor)
Aparte de crear PDFs en Servidores Blazor, IronPDF también soporta la generación de documentos PDF desde componentes Razor dentro de una página Blazor. Haciendo la creación de archivos y páginas PDF mucho más eficiente.
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
protected override async Task OnInitializedAsync()
{
persons = new List<PersonInfo>
{
new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
}
private async void PrintToPdf()
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Apply text footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
LeftText = "{date} - {time}",
DrawDividerLine = true,
RightText = "Page {page} of {total-pages}",
Font = IronSoftware.Drawing.FontTypes.Arial,
FontSize = 11
};
Parameters.Add("persons", persons);
// Render razor component to PDF
PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
<Parameter>
Public Property persons() As IEnumerable(Of PersonInfo)
Public Property Parameters() As New Dictionary(Of String, Object)()
Protected Overrides Async Function OnInitializedAsync() As Task
persons = New List(Of PersonInfo) From {
New PersonInfo With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New PersonInfo With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New PersonInfo With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
End Function
Private Async Sub PrintToPdf()
Dim renderer As New ChromePdfRenderer()
' Apply text footer
renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
.LeftText = "{date} - {time}",
.DrawDividerLine = True,
.RightText = "Page {page} of {total-pages}",
.Font = IronSoftware.Drawing.FontTypes.Arial,
.FontSize = 11
}
Parameters.Add("persons", persons)
' Render razor component to PDF
Dim pdf As PdfDocument = renderer.RenderRazorComponentToPdf(Of Person)(Parameters)
File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)
End Sub
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
CSHTML a PDF
Convertir CSHTML (Razor) a PDF le permite generar documentos profesionales y listos para imprimir directamente desde sus aplicaciones web. Esto es útil para facturas, informes, contratos o cualquier contenido dinámico. IronPDF soporta Razor Pages, MVC Core y MVC Framework, además de renderizado sin interfaz, lo que facilita la integración de la generación de PDFs en sus aplicaciones .NET con solo unas pocas líneas de código.
CSHTML a PDF (Razor Pages)
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
using IronPdf.Razor.Pages;
public IActionResult OnPostAsync()
{
persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
ViewData["personList"] = persons;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor Page to PDF document
PdfDocument pdf = renderer.RenderRazorToPdf(this);
Response.Headers.Add("Content-Disposition", "inline");
return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
Imports IronPdf.Razor.Pages
Public Function OnPostAsync() As IActionResult
persons = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
ViewData("personList") = persons
Dim renderer As New ChromePdfRenderer()
' Render Razor Page to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)
Response.Headers.Add("Content-Disposition", "inline")
Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")
End Function
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
CSHTML a PDF (MVC Core)
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
public async Task<IActionResult> Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render View to PDF document
PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
Response.Headers.Add("Content-Disposition", "inline");
// Output PDF document
return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
}
return View(persons);
}
Public Async Function Persons() As Task(Of IActionResult)
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
Dim persons_Conflict = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then
Dim renderer As New ChromePdfRenderer()
' Render View to PDF document
Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons_Conflict)
Response.Headers.Add("Content-Disposition", "inline")
' Output PDF document
Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
End If
Return View(persons_Conflict)
End Function
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
CSHTML a PDF (Marco MVC)
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
public ActionResult Persons()
{
var persons = new List<Person>
{
new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
};
if (HttpContext.Request.HttpMethod == "POST")
{
// Provide the path to your view file
var viewPath = "~/Views/Home/Persons.cshtml";
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render Razor view to PDF document
PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
Response.Headers.Add("Content-Disposition", "inline");
// View the PDF
return File(pdf.BinaryData, "application/pdf");
}
return View(persons);
}
Public Function Persons() As ActionResult
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
Dim persons_Conflict = New List(Of Person) From {
New Person With {
.Name = "Alice",
.Title = "Mrs.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Bob",
.Title = "Mr.",
.Description = "Software Engineer"
},
New Person With {
.Name = "Charlie",
.Title = "Mr.",
.Description = "Software Engineer"
}
}
If HttpContext.Request.HttpMethod = "POST" Then
' Provide the path to your view file
Dim viewPath = "~/Views/Home/Persons.cshtml"
Dim renderer As New ChromePdfRenderer()
' Render Razor view to PDF document
Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)
Response.Headers.Add("Content-Disposition", "inline")
' View the PDF
Return File(pdf.BinaryData, "application/pdf")
End If
Return View(persons_Conflict)
End Function
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
CSHTML a PDF (sin encabezado)
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", async () =>
{
// Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
// Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
// Render the Razor view to an HTML string
string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");
// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Render the HTML string as a PDF document
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");
// Return the PDF file as a response
return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", Async Function()
' Set your IronPDF license key
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
' Enable detailed logging for troubleshooting
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
' Render the Razor view to an HTML string
Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")
' Create a new instance of ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Render the HTML string as a PDF document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")
' Return the PDF file as a response
Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Accesibilidad web
Inicio de sesión en sitios web y sistemas TLS
IronPDF ofrece una solución sencilla para convertir páginas web que requieren autenticación. Con sus opciones de representación, los usuarios pueden omitir el nombre de usuario y la contraseña utilizando la propiedad ChromeHttpLoginCredntials.
:path=/static-assets/pdf/content-code-examples/how-to/logins-username-password.cs
using IronPdf;
using System;
ChromePdfRenderer renderer = new ChromePdfRenderer
{
// setting login credentials to bypass basic authentication
LoginCredentials = new ChromeHttpLoginCredentials()
{
NetworkUsername = "testUser",
NetworkPassword = "testPassword"
}
};
var uri = new Uri("http://localhost:51169/Invoice");
// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);
// Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf");
Imports IronPdf
Imports System
Private renderer As New ChromePdfRenderer With {
.LoginCredentials = New ChromeHttpLoginCredentials() With {
.NetworkUsername = "testUser",
.NetworkPassword = "testPassword"
}
}
Private uri = New Uri("http://localhost:51169/Invoice")
' Render web URL to PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)
' Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Cookies
Aplique cookies a la solicitud de inicio de sesión adicional para asegurar que su sesión se guarde. Esto facilitará la renderización de recursos adicionales dentro del dominio bloqueado, todo dentro de IronPDF.
:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-cookies.cs
using IronPdf;
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global;
ChromeHttpLoginCredentials credentials = new ChromeHttpLoginCredentials() {
NetworkUsername = "testUser",
NetworkPassword = "testPassword"
};
string uri = "http://localhost:51169/Invoice";
// Apply cookies
renderer.ApplyCookies(uri, credentials);
Imports IronPdf
' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global
Dim credentials As New ChromeHttpLoginCredentials() With {
.NetworkUsername = "testUser",
.NetworkPassword = "testPassword"
}
Dim uri As String = "http://localhost:51169/Invoice"
' Apply cookies
renderer.ApplyCookies(uri, credentials)
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Cabecera de solicitud HTTP
Además de las cookies, IronPDF también permite a los usuarios personalizar la cabecera de su solicitud HTTP con tokens de autorización y otros campos relacionados comunes.
:path=/static-assets/pdf/content-code-examples/how-to/http-request-header.cs
using IronPdf;
using System.Collections.Generic;
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer test-token-123" }
};
// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports System.Collections.Generic
Private renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
{"Authorization", "Bearer test-token-123"}
}
' Render PDF from authenticated page
Dim pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer")
pdf.SaveAs("output.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Conversión de PDF a medida
Opciones de renderización
IronPDF permite a los usuarios personalizar la apariencia y formato de sus PDFs generados. La clase ChromePdfRender que se utiliza para convertir varias entradas en PDF también incluye la propiedad RenderingOptions, que permite a los usuarios controlar cómo se ve la salida.
:path=/static-assets/pdf/content-code-examples/how-to/rendering-options-render.cs
using IronPdf;
// Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
// to render HTML/CSS as a PDF document.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure rendering options
// Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
// HTML fragment to add a header at the top of every page in the PDF.
HtmlFragment = "<h1>Header Content</h1>"
};
// Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150);
// Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0;
// Define a Markdown string that will be rendered as a PDF.
// Markdown text allows basic formatting like bold and italic styles.
string md = "This is some **bold** and *italic* text.";
// Render the Markdown string to a PDF document.
// The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
PdfDocument pdf = renderer.RenderMarkdownStringAsPdf(md);
// Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf");
Imports IronPdf
' Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
' to render HTML/CSS as a PDF document.
Private renderer As New ChromePdfRenderer()
' Configure rendering options
' Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {.HtmlFragment = "<h1>Header Content</h1>"}
' Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150)
' Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0
' Define a Markdown string that will be rendered as a PDF.
' Markdown text allows basic formatting like bold and italic styles.
Dim md As String = "This is some **bold** and *italic* text."
' Render the Markdown string to a PDF document.
' The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
Dim pdf As PdfDocument = renderer.RenderMarkdownStringAsPdf(md)
' Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Configurar margen personalizado
Puede adaptar aún más la apariencia de su PDF de salida ajustando los márgenes, lo que le permite controlar exactamente el diseño y el espacio.
:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-set-margins.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.MarginBottom = 40;
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
renderer.RenderingOptions.MarginBottom = 40
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Escala de grises
Para generar un PDF en escala de grises, establecemos la propiedad GrayScale dentro de RenderingOptions como verdadera.
:path=/static-assets/pdf/content-code-examples/how-to/color-grayscale-grayscale.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Set GrayScale to true
renderer.RenderingOptions.GrayScale = true;
PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironsoftware.com/");
pdf.CopyPage(0).SaveAs("test.pdf");
Imports IronPdf
Dim renderer As New ChromePdfRenderer()
' Set GrayScale to true
renderer.RenderingOptions.GrayScale = True
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironsoftware.com/")
pdf.CopyPage(0).SaveAs("test.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Refine el diseño de su PDF
Añadir un índice
Cree una tabla de contenidos dinámica con IronPDF para ayudar a los lectores a navegar fácilmente por su documento. IronPDF maneja automáticamente la tabla de contenidos con hipervínculos a encabezados como h1 y h2. Además, también puede personalizar el estilo de la tabla de contenidos con HTML y CSS.
:path=/static-assets/pdf/content-code-examples/how-to/table-of-contents.cs
using IronPdf;
// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure render options
renderer.RenderingOptions = new ChromePdfRenderOptions
{
// Enable table of content feature
TableOfContents = TableOfContentsTypes.WithPageNumbers,
};
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("tableOfContent.html");
pdf.SaveAs("tableOfContents.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer As New ChromePdfRenderer()
' Configure render options
renderer.RenderingOptions = New ChromePdfRenderOptions With {.TableOfContents = TableOfContentsTypes.WithPageNumbers}
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("tableOfContent.html")
pdf.SaveAs("tableOfContents.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Salto de página
Agregue saltos de página entre secciones para separar claramente el contenido y mejorar la legibilidad de su documento. Con IronPDF, simplemente use el HTML div style= page-break-after para lograr ese efecto.
:path=/static-assets/pdf/content-code-examples/how-to/html-to-pdf-page-breaks-page-break.cs
using IronPdf;
const string html = @"
<table style='border: 1px solid #000000'>
<tr>
<th>Company</th>
<th>Product</th>
</tr>
<tr>
<td>Iron Software</td>
<td>IronPDF</td>
</tr>
<tr>
<td>Iron Software</td>
<td>IronOCR</td>
</tr>
</table>
<div style='page-break-after: always;'> </div>
<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Page_Break.pdf");
Imports IronPdf
Private Const html As String = "
<table style='border: 1px solid #000000'>
<tr>
<th>Company</th>
<th>Product</th>
</tr>
<tr>
<td>Iron Software</td>
<td>IronPDF</td>
</tr>
<tr>
<td>Iron Software</td>
<td>IronOCR</td>
</tr>
</table>
<div style='page-break-after: always;'> </div>
<img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>"
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("Page_Break.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Ajuste a página y zoom
¿Necesita ayuda para determinar las dimensiones del contenido para que se ajuste a un tamaño de papel específico? IronPDF le ayuda con el UseChromeDefault, que imita cómo la vista previa de impresión de Google Chrome ajusta el contenido para que se ajuste a la página.
:path=/static-assets/pdf/content-code-examples/how-to/viewport-zoom-default-chrome.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering();
// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
pdf.SaveAs("chromeDefault.pdf");
Imports IronPdf
Private renderer As New ChromePdfRenderer()
' Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering()
' Render web URL to PDF
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")
pdf.SaveAs("chromeDefault.pdf")
Para una explicación más detallada de este fragmento de código y para explorar su funcionalidad adicional, consulte nuestra exhaustiva guía práctica.
Conclusión
Los ejemplos anteriores muestran las impresionantes capacidades y características destacadas que puede aprovechar al convertir varios formatos a PDFs usando IronPDF.
Si desea solicitar una característica o tiene preguntas generales sobre IronPDF o licencias, contacte a nuestro equipo de soporte. Estaremos encantados de ayudarle.
Preguntas Frecuentes
¿Cómo convierto HTML a PDF en .NET Core?
Para convertir HTML a PDF en .NET Core, utiliza la biblioteca IronPDF. Primero, instala el paquete a través de NuGet. Luego, crea una instancia de ChromePdfRenderer y utiliza el método RenderHtmlAsPdf para convertir cadenas HTML al formato PDF.
¿Cómo puedo convertir una URL en vivo a un documento PDF?
Puedes convertir una URL en vivo a un documento PDF usando IronPDF instalando la biblioteca desde NuGet, creando una instancia de ChromePdfRenderer y llamando al método RenderUrlAsPdf con la URL de la página web que deseas convertir.
¿Cuáles son los pasos para convertir vistas Razor a PDF?
Para convertir vistas Razor a PDF, renderiza la vista en una cadena HTML y luego pásala al método RenderHtmlAsPdf de IronPDF. Esto permite crear PDFs dinámicos desde vistas MVC con vinculación de datos completa.
¿Pueden modificarse los archivos PDF existentes?
Sí, los archivos PDF existentes pueden modificarse usando IronPDF. Usa PdfDocument.FromFile para cargar un PDF, y luego aplica modificaciones como unir, agregar encabezados/pies de página o alterar configuraciones de seguridad.
¿Qué opciones están disponibles para renderizar PDFs?
IronPDF proporciona varias opciones de renderizado a través de ChromePdfRenderOptions. Puedes personalizar el tamaño del papel, la orientación, los márgenes y más, asegurando que tus PDFs cumplan con requisitos específicos de diseño y estilo.
¿Cómo pueden desplegarse PDFs en un entorno Docker?
Despliega PDFs en un entorno Docker configurando las dependencias de Linux dentro de tu Dockerfile. Usa IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig de IronPDF para gestionar automáticamente las dependencias en aplicaciones contenedorizadas.
¿Es posible añadir firmas digitales a archivos PDF?
Sí, se pueden añadir firmas digitales a archivos PDF utilizando la clase PdfSignature. Al utilizar el método Sign y un archivo de certificado, puedes garantizar la autenticidad e integridad del documento.
¿Qué características de seguridad ofrece IronPDF para PDFs?
IronPDF ofrece robustas características de seguridad incluyendo protección con contraseña, cifrado y control de acceso. Establece estas características a través de la propiedad SecuritySettings para gestionar permisos de visualización, impresión y edición.
¿Cómo pueden extraerse texto e imágenes de documentos PDF?
Texto e imágenes pueden extraerse de documentos PDF utilizando los métodos ExtractAllText y ExtractAllImages de IronPDF. Estos permiten procesar datos de documentos enteros o páginas específicas.
¿Cómo aplico marcas de agua a los archivos PDF?
Las marcas de agua pueden aplicarse a archivos PDF usando la propiedad Watermark de IronPDF con objetos HtmlStamp. Para necesidades más avanzadas, la clase HtmlStamper soporta estampados basados en HTML con estilos personalizables.
¿IronPDF es compatible con .NET 10 y cómo lo uso en un proyecto .NET 10?
Sí, IronPDF es totalmente compatible con .NET 10 gracias a su compatibilidad multiplataforma con versiones modernas de .NET. Para usarlo en un proyecto .NET 10, instale el paquete NuGet IronPDF , haga referencia a él en el archivo de proyecto que tenga como destino net10.0 y, a continuación, utilice clases como ChromePdfRenderer y métodos como RenderHtmlAsPdf tal como lo haría en versiones anteriores de .NET. Disfrute de un mejor rendimiento, uso de memoria y mejoras en el tiempo de ejecución inherentes a .NET 10 al renderizar o manipular archivos PDF.

