Cómo exportar un PDF en C#

Cómo exportar y guardar PDFs en IronPDF C

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

IronPDF exporta un PdfDocument renderizado a PDF en C# a través de SaveAs para disco, las propiedades Stream y BinaryData para memoria, y SaveAsPdfA, SaveAsPdfUA, y SaveAsRevision para salida archivada, accesible y versionada. Cada método toma un documento que ya has renderizado y lo escribe en el destino que tu aplicación necesita, ya sea una ruta de archivo, un buffer en memoria, o una respuesta HTTP.

Esta guía recorre cada objetivo de exportación, desde un guardado de archivo de una línea hasta servir un PDF directamente a un navegador, y los métodos que producen salida con etiquetas de conformidad.

Inicio rápido: Exportar HTML a PDF en C#

Renderiza HTML y escribe el resultado en disco en una sola declaración. La llamada RenderHtmlAsPdf devuelve un PdfDocument, y SaveAs lo persiste.

  1. Instala IronPDF con el Administrador de Paquetes NuGet

    PM > Install-Package IronPdf
  2. Copie y ejecute este fragmento de código.

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
  3. Despliegue para probar en su entorno real

    Comienza a usar IronPDF en tu proyecto hoy mismo con una prueba gratuita

    arrow pointer


¿Cuáles son las opciones para guardar PDFs?

IronPDF guarda un PdfDocument en cuatro tipos de destino: un archivo en disco, un MemoryStream en memoria, un byte[] en bruto, y un archivo con etiquetas de conformidad para archivado, accesibilidad o revisión incremental. Las siguientes secciones cubren cada objetivo con un ejemplo probado, comenzando con el guardado de archivo más simple y terminando con los métodos de exportación especializados.

Cómo guardar un PDF en disco

Utiliza el método SaveAs para escribir un PdfDocument en una ruta de archivo. Esta es la ruta directa para aplicaciones de escritorio o cualquier proceso del servidor que mantenga PDFs en el sistema de archivos.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-2.cs
// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
Imports IronPdf

' Initialize the Chrome PDF renderer
Dim renderer As New ChromePdfRenderer()

' Create HTML content with styling
Dim htmlContent As String = "
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " & DateTime.Now.ToString("yyyy-MM-dd") & "</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>"

' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

' Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf")

' Save with password protection for sensitive documents
pdf.Password = "secure123"
pdf.SaveAs("protected_invoice_12345.pdf")
$vbLabelText   $csharpLabel

El mismo ejemplo también establece la propiedad Password antes de un segundo guardado, lo que cifra el archivo para que no pueda abrirse sin esa contraseña. Para un control más fino sobre lo que un destinatario puede hacer con el archivo, consulta la guía sobre permisos y contraseñas de PDF.

Salida

Cómo guardar un PDF en un MemoryStream

La propiedad Stream devuelve el documento como un System.IO.MemoryStream. Recurre a ello cuando necesites entregarle el PDF a otro método, cargarlo o enviarlo por correo electrónico sin escribir primero un archivo temporal. Lee más sobre trabajando con streams de memoria PDF.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-3.cs
// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
Imports IronPdf
Imports System.IO

' Example: Save PDF to MemoryStream
Dim renderer As New ChromePdfRenderer()

' Render HTML content
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>")

' Get the PDF as a MemoryStream
Dim stream As MemoryStream = pdf.Stream

' Example: Upload to cloud storage or database
' UploadToCloudStorage(stream)

' Example: Email as attachment without saving to disk
' EmailService.SendWithAttachment(stream, "report.pdf")

' Remember to dispose of the stream when done
stream.Dispose()
$vbLabelText   $csharpLabel

Salida

Cómo guardar en datos binarios

La propiedad BinaryData devuelve el documento como un byte[]. Un arreglo de bytes se adapta a columnas de base de datos, entradas de caché, y APIs que aceptan bytes en bruto en lugar de un stream.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-4.cs
// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' Configure rendering options for better quality
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
    .MarginTop = 20,
    .MarginBottom = 20,
    .MarginLeft = 10,
    .MarginRight = 10,
    .PaperSize = IronPdf.Rendering.PdfPaperSize.A4
}

' Render content to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>")

' Get binary data
Dim binaryData As Byte() = pdf.BinaryData

' Example: Store in database
' database.StorePdfDocument(documentId, binaryData)

' Example: Send via API
' apiClient.UploadDocument(binaryData)
$vbLabelText   $csharpLabel

Cuando necesites la dirección inversa, cargando bytes de nuevo en un documento editable, la guía sobre convertir PDFs en un MemoryStream lo cubre.

Salida

¿Cómo sirvo un PDF desde un servidor web al navegador?

Para devolver un PDF por HTTP envías los bytes como una respuesta de archivo, no como HTML. Tanto Stream como BinaryData se conectan directamente a los tipos de resultado de archivo que ASP.NET proporciona, por lo que el controlador renderiza un documento y lo devuelve sin tocar nunca el disco.

¿Cómo exporto un PDF en MVC?

En ASP.NET Core MVC, envuelve el Stream en un FileStreamResult para solicitar una descarga, o pasa BinaryData a File para mostrar el PDF en línea. Las dos acciones a continuación muestran ambos. Esto complementa naturalmente la renderización de vistas CSHTML a PDF.

// MVC controller methods for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Render the PDF with IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Take the PDF stream and rewind it
    MemoryStream stream = pdf.Stream;
    stream.Position = 0;

    // Returning a FileStreamResult prompts a download in the browser
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Returning BinaryData with no filename displays the PDF inline
    return File(pdf.BinaryData, "application/pdf");
}
// MVC controller methods for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Render the PDF with IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Take the PDF stream and rewind it
    MemoryStream stream = pdf.Stream;
    stream.Position = 0;

    // Returning a FileStreamResult prompts a download in the browser
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Returning BinaryData with no filename displays the PDF inline
    return File(pdf.BinaryData, "application/pdf");
}
Imports System.IO
Imports Microsoft.AspNetCore.Mvc

' MVC controller methods for PDF export
Public Class InvoiceController
    Inherits Controller

    Public Function DownloadInvoice(invoiceId As Integer) As IActionResult
        ' Generate your HTML content
        Dim htmlContent As String = GenerateInvoiceHtml(invoiceId)

        ' Render the PDF with IronPDF
        Dim renderer As New ChromePdfRenderer()
        Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

        ' Take the PDF stream and rewind it
        Dim stream As MemoryStream = pdf.Stream
        stream.Position = 0

        ' Returning a FileStreamResult prompts a download in the browser
        Return New FileStreamResult(stream, "application/pdf") With {
            .FileDownloadName = $"invoice_{invoiceId}.pdf"
        }
    End Function

    Public Function ViewInvoice(invoiceId As Integer) As IActionResult
        Dim renderer As New ChromePdfRenderer()
        Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId))

        ' Returning BinaryData with no filename displays the PDF inline
        Return File(pdf.BinaryData, "application/pdf")
    End Function

    Private Function GenerateInvoiceHtml(invoiceId As Integer) As String
        ' Placeholder for the method that generates HTML content
        Return String.Empty
    End Function
End Class
$vbLabelText   $csharpLabel

¿Cómo exporto un PDF en ASP.NET WebForms?

Las aplicaciones tradicionales de ASP.NET WebForms escriben los bytes a través del objeto Response en su lugar. Configura las opciones de renderización una vez, extrae BinaryData, y transmítelo al cliente.

// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Render from custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieve the PDF bytes
    byte[] Binary = MyPdfDocument.BinaryData;

    // Write the bytes to the response as a download
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition",
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
    Response.Flush();
    Response.End();
}
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Render from custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieve the PDF bytes
    byte[] Binary = MyPdfDocument.BinaryData;

    // Write the bytes to the response as a download
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition",
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
    Response.Flush();
    Response.End();
}
' ASP.NET WebForms PDF export
Protected Sub ExportButton_Click(sender As Object, e As EventArgs)
    Dim renderer As New ChromePdfRenderer()

    ' Configure rendering options
    renderer.RenderingOptions = New ChromePdfRenderOptions() With {
        .PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        .PrintHtmlBackgrounds = True,
        .CreatePdfFormsFromHtml = True
    }

    ' Render from custom HTML
    Dim MyPdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml())

    ' Retrieve the PDF bytes
    Dim Binary As Byte() = MyPdfDocument.BinaryData

    ' Write the bytes to the response as a download
    Response.Clear()
    Response.ContentType = "application/octet-stream"
    Response.AddHeader("Content-Disposition", "attachment; filename=report_" & DateTime.Now.ToString("yyyyMMdd") & ".pdf")
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length)
    Response.Flush()
    Response.End()
End Sub
$vbLabelText   $csharpLabel
Icon Quote related to ¿Cómo exporto un PDF en ASP.NET WebForms?

Mi biblioteca favorita de este tipo es IronPDF. Permite una manipulación rápida y eficiente de archivos PDF. También tiene muchas funciones valiosas, como exportar al formato PDF/A y firmar documentos PDF digitalmente.

Milan Jovanovic related to ¿Cómo exporto un PDF en ASP.NET WebForms?

Milan Jovanovic

Microsoft MVP

Ver estudio de caso
Icon Quote related to ¿Cómo exporto un PDF en ASP.NET WebForms?

IronOCR significa que podemos ahorrar $40,000 anualmente en el procesamiento manual, mientras mejoramos la productividad y liberamos recursos para tareas de alto impacto. Lo recomendaría encarecidamente.

Brent Matzelle related to ¿Cómo exporto un PDF en ASP.NET WebForms?

Brent Matzelle

Director de Tecnología, OPYN

Ver estudio de caso
Icon Quote related to ¿Cómo exporto un PDF en ASP.NET WebForms?

El Iron Suite juega un papel crucial en nuestras operaciones. Estas son herramientas que aumentan la eficiencia en toda la empresa, incluyendo la creación de planos y la mejora en la gestión de inventario.

David Jones related to ¿Cómo exporto un PDF en ASP.NET WebForms?

David Jones

Ingeniero de Software Principal, Agorus Build

Ver estudio de caso

¿Cómo exporto PDF/A, PDF/UA y revisiones?

Más allá de los objetivos de guardado general, IronPDF escribe tres formatos específicos de conformidad. SaveAsPdfA produce un archivo de archivo, SaveAsPdfUA produce un archivo accesible etiquetado, y SaveAsRevision anexa una revisión incremental a un documento existente.

Cómo guardar un archivo de archivo PDF/A

SaveAsPdfA escribe un archivo autónomo que cumple con el estándar ISO PDF/A para almacenamiento a largo plazo, incrustando las fuentes y datos de color que un lector necesita en el futuro. El argumento PdfAVersions selecciona el nivel de conformidad, como PdfA3b.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-pdfa.cs
using IronPdf;

var renderer = new ChromePdfRenderer();

// Render the document you want to archive
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>");

// Save as a PDF/A-3b file for long-term archiving.
// PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).
pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b);
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' Render the document you want to archive
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Archived Document</h1>")

' Save as a PDF/A-3b file for long-term archiving.
' PdfAVersions controls the conformance level (PdfA1b, PdfA2b, PdfA3b, PdfA4, and others).
pdf.SaveAsPdfA("archive-pdfa.pdf", IronPdf.PdfAVersions.PdfA3b)
$vbLabelText   $csharpLabel

Salida

Cómo guardar un archivo PDF/UA accesible

SaveAsPdfUA escribe un PDF etiquetado que cumple con el estándar de accesibilidad PDF/UA, del que los lectores de pantalla dependen para navegar por el documento. El tercer argumento establece el idioma del documento para que la tecnología de asistencia lo lea con la voz correcta.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-pdfua.cs
using IronPdf;

var renderer = new ChromePdfRenderer();

// Render content that should be tagged for assistive technology
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>");

// Save as a PDF/UA-1 file. The last argument sets the document's primary
// language, which screen readers use to choose the correct voice.
pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom);
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' Render content that should be tagged for assistive technology
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Accessible Document</h1><p>Tagged for screen readers.</p>")

' Save as a PDF/UA-1 file. The last argument sets the document's primary
' language, which screen readers use to choose the correct voice.
pdf.SaveAsPdfUA("accessible-pdfua.pdf", IronPdf.PdfUAVersions.PdfUA1, IronPdf.NaturalLanguages.English_UnitedKingdom)
$vbLabelText   $csharpLabel

Salida

Cómo guardar una revisión incremental

SaveAsRevision añade cambios a un archivo en lugar de reescribirlo, por lo que las revisiones anteriores, incluidas las firmas digitales, se mantienen intactas. El documento debe ser abierto con ChangeTrackingModes.EnableChangeTracking para que funcione el guardado incremental.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-revision.cs
using IronPdf;
using IronPdf.Rendering;

var renderer = new ChromePdfRenderer();

// Create and save the original revision of the document
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>");
pdf.SaveAs("revision-base.pdf");

// Re-open with change tracking enabled so the next save appends a revision
// instead of rewriting the file. This preserves earlier signed revisions.
PdfDocument loaded = PdfDocument.FromFile("revision-base.pdf", null, null, ChangeTrackingModes.EnableChangeTracking);

// Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf");
Imports IronPdf
Imports IronPdf.Rendering

Dim renderer As New ChromePdfRenderer()

' Create and save the original revision of the document
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Versioned Document</h1>")
pdf.SaveAs("revision-base.pdf")

' Re-open with change tracking enabled so the next save appends a revision
' instead of rewriting the file. This preserves earlier signed revisions.
Dim loaded As PdfDocument = PdfDocument.FromFile("revision-base.pdf", Nothing, Nothing, ChangeTrackingModes.EnableChangeTracking)

' Write an incremental revision on top of the existing bytes
loaded.SaveAsRevision("revision-v2.pdf")
$vbLabelText   $csharpLabel

Salida

¿Cómo exporto un PDF de forma asincrónica?

La renderización bloquea el hilo de llamada hasta que el motor Chromium finaliza. En una solicitud web o una interfaz de usuario de escritorio, llama RenderHtmlAsPdfAsync en su lugar y espéralo, luego guarda el documento devuelto con el mismo método SaveAs. Esto mantiene el hilo libre mientras se ejecuta la renderización.

:path=/static-assets/pdf/content-code-examples/how-to/export-save-pdf-csharp-async.cs
using IronPdf;
using System.Threading.Tasks;

var renderer = new ChromePdfRenderer();

// Render off the calling thread so a web request or UI stays responsive
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>");

// SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf");
Imports IronPdf
Imports System.Threading.Tasks

Dim renderer As New ChromePdfRenderer()

' Render off the calling thread so a web request or UI stays responsive
Dim pdf As PdfDocument = Await renderer.RenderHtmlAsPdfAsync("<h1>Async Generated PDF</h1>")

' SaveAs writes the finished document to disk once the render completes
pdf.SaveAs("async-render.pdf")
$vbLabelText   $csharpLabel

Salida

Conclusión

IronPDF exporta un PdfDocument renderizado a disco, memoria, una respuesta HTTP, o un archivo con etiquetas de conformidad, cada uno a través de un único método en el documento que ya construiste. Elige el objetivo que coincida con a dónde deben ir los bytes, y aplica SaveAsPdfA, SaveAsPdfUA, o SaveAsRevision cuando la salida deba cumplir con un estándar de archivado, accesibilidad o versionado.

Desde aquí, mantén los bytes fuera del disco por completo con el flujo de trabajo de stream de memoria PDF, o asegura un archivo guardado usando permisos y contraseñas de PDF.

Preguntas Frecuentes

¿Cómo se exporta contenido HTML a PDF en C#?

Puede exportar HTML a PDF en C# utilizando la clase ChromePdfRenderer de IronPDF. Basta con crear una instancia del renderizador, utilizar el método RenderHtmlAsPdf() para convertir el contenido HTML y, a continuación, guardarlo mediante el método SaveAs(). IronPDF facilita la conversión de cadenas HTML, archivos o URL directamente en documentos PDF.

¿Cuáles son los diferentes métodos para guardar un PDF utilizando C#?

IronPDF ofrece varios métodos para guardar archivos PDF: SaveAs() para guardar en disco, Stream para servir PDFs en aplicaciones web sin crear archivos temporales, y BinaryData para obtener el PDF como una matriz de bytes. Cada método de IronPDF sirve para diferentes casos de uso, desde el simple almacenamiento de archivos hasta la entrega dinámica a través de la web.

¿Puedo guardar un PDF en la memoria en lugar de en el disco?

Sí, IronPDF le permite guardar archivos PDF en la memoria utilizando System.IO.MemoryStream. Esto es útil para aplicaciones web en las que desea servir archivos PDF directamente a los usuarios sin crear archivos temporales en el servidor. Puede utilizar la propiedad Stream o convertir el PDF en datos binarios.

¿Cómo puedo proteger un PDF con una contraseña?

IronPDF permite la protección mediante contraseña estableciendo la propiedad Password en el objeto PdfDocument antes de guardarlo. Simplemente asigne una cadena de contraseña a pdf.Password y luego utilice SaveAs() para crear un archivo PDF protegido que requiera la contraseña para abrirse.

¿Puedo servir un PDF directamente a navegadores web sin guardarlo en disco?

Sí, IronPDF le permite servir archivos PDF directamente a los navegadores web como datos binarios. Puede utilizar la propiedad BinaryData para obtener el PDF como una matriz de bytes y servirlo a través del flujo de respuesta de su aplicación web, eliminando la necesidad de almacenar archivos temporales.

¿Cuál es la forma más sencilla de convertir y guardar HTML como PDF en una sola línea?

IronPDF proporciona una solución de una sola línea: new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Tu HTML").SaveAs("output.pdf"). Esto crea un renderizador, convierte HTML a PDF, y lo guarda en el disco en una sola sentencia.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 20,296,129 | Versión: 2026.7 recién publicada
Still Scrolling Icon

¿Aún desplazándote?

¿Quieres una prueba rápida? PM > Install-Package IronPdf
ejecutar una muestra Mira cómo tu HTML se convierte en PDF.