Cómo renderizar una cadena HTML en PDF en C# | IronPDF

How to Convert HTML String to PDF in C#

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

IronPDF allows developers to create PDF documents easily in C#, F#, and VB.NET for .NET Core and .NET Framework. IronPdf supports rendering any HTML string into a PDF, and the rendering process is undertaken by a fully functional version of the Google Chromium engine.

Quickstart: Convert HTML String to PDF in Seconds

Effortlessly transform HTML strings into PDF files using IronPDF. This guide demonstrates how to quickly convert an HTML string to a PDF document in C# with just a couple of lines of code. Perfect for developers looking to integrate efficient PDF rendering capabilities into their projects.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    IronPdf.ChromePdfRender.StaticRenderHtmlAsPdf("<p>Hello World</p>").SaveAs("string-to-pdf.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


HTML String to PDF Example

Here we have an example of IronPDF rendering an HTML string into a PDF by using the RenderHtmlAsPdf method. The parameter is an HTML string to be rendered as a PDF.

: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")
$vbLabelText   $csharpLabel

The RenderHtmlAsPdf method returns a PdfDocument object, which is a class used to hold PDF information.

In cases where an HTML string is obtained from an external source, and disabling local disk access or cross-origin requests is desired, the ChromePdfRenderer.EnableWebSecurity property can be set to true to achieve that.

Result

This is the file that the code produced:

Advanced HTML to PDF Example

Here we have an example of IronPDF loading an external image asset from an optional BasePath. Setting the BaseUrlOrPath property gives the relative file path or URL context for hyperlinks, images, CSS, and JavaScript files.

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-2.cs
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Advanced Example with HTML Assets
// Load external html assets: Images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Advanced Example with HTML Assets
' Load external html assets: Images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Private myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
$vbLabelText   $csharpLabel

This is the file that the code produced:

Preguntas Frecuentes

¿Cómo convierto una cadena HTML a un documento PDF en C#?

Para convertir una cadena HTML a PDF en C#, puedes usar el método StaticRenderHtmlAsPdf de la clase IronPdf.ChromePdfRender. Este método toma una cadena HTML, la renderiza como PDF y te permite guardarla como archivo.

¿Qué pasos están involucrados en renderizar una cadena HTML a PDF?

Los pasos para renderizar una cadena HTML a PDF usando IronPDF incluyen descargar la biblioteca de IronPDF desde NuGet, instanciar el renderizador de PDF, pasar la cadena HTML, configurar opciones de renderizado como BasePath para recursos externos y guardar el PDF generado.

¿Puedo incluir imágenes y CSS externos en el PDF?

Sí, IronPDF te permite incluir imágenes y CSS externos en tu PDF configurando la propiedad BaseUrlOrPath. Esta propiedad proporciona un contexto para cargar recursos como imágenes, CSS y archivos JavaScript al renderizar HTML a PDF.

¿Cómo puedo mejorar la seguridad al renderizar HTML desde fuentes externas?

Para mejorar la seguridad al renderizar HTML desde fuentes externas, puedes establecer la propiedad ChromePdfRenderer.EnableWebSecurity en true en IronPDF. Esto desactiva el acceso al disco local y las solicitudes de origen cruzado.

¿Cuál es el propósito de establecer la propiedad BaseUrlOrPath en IronPDF?

La propiedad BaseUrlOrPath en IronPDF se utiliza para definir la ruta base o el contexto URL para cargar recursos externos como imágenes, CSS y archivos JavaScript. Asegura que estos recursos se referencian correctamente al renderizar HTML a PDF.

¿Qué método se usa para guardar un PDF renderizado en IronPDF?

Después de renderizar una cadena HTML a PDF usando IronPDF, puedes guardar el PDF llamando al método SaveAs en el objeto PdfDocument, especificando la ruta de archivo deseada.

¿Dónde puedo descargar la biblioteca IronPDF?

Puedes descargar la biblioteca IronPDF para C# desde NuGet. Para hacerlo, visita el sitio web de NuGet y busca IronPDF para encontrar el paquete.

¿Cómo puedo renderizar una cadena HTML con recursos externos en un PDF?

IronPDF permite renderizar HTML con recursos externos configurando la propiedad BaseUrlOrPath. Puedes cargar imágenes, CSS y JavaScript desde URLs o rutas especificadas y renderizarlos en el PDF.

¿IronPDF es compatible con .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10, así como con .NET 9, 8, 7, 6 y .NET Core. Funciona de inmediato en proyectos .NET 10 sin necesidad de ninguna configuración especial. Las plataformas compatibles incluyen Windows, Linux, macOS y entornos contenedorizados.

Regan Pun
Ingeniero de Software
Regan se graduó de la Universidad de Reading, con una licenciatura en Ingeniería Electrónica. Antes de unirse a Iron Software, sus roles anteriores lo tenían enfocado en tareas individuales; y lo que más disfruta en Iron Software es la variedad de trabajos que puede realizar, ya ...
Leer más
¿Listo para empezar?
Nuget Descargas 16,133,208 | Versión: 2025.11 recién lanzado