C&num de MemoryStream a PDF;
Podemos cargar, crear y exportar MemoryStream a archivos PDF en C# .NET sin siquiera tocar el sistema de archivos. Esto es posible a través del objeto MemoryStream presente dentro del espacio de nombres System.IO .NET. Siga el siguiente tutorial para averiguar cómo exportar HTML a PDF en su proyecto C#.
Cómo convertir PDF a MemoryCorriente en C#
- Descargar la biblioteca C# para convertir PDF a MemoryCorriente
- Cargar un PDF existente como DocumentoPdf objeto
- Crear un nuevo PDF a partir de una URL o una cadena/archivo HTML
- Convierta el PDF en un flujo utilizando la función
Corriente
método y DatosBinarios propiedad - Serve the MemoryCorriente to the web, including MVC and ASP.NET
Primer paso
1. Instalar IronPDF
En este tutorial, usaremos la librería C# PDF de IronPDF para guardar archivos MemoryStream a PDF en C#. Puede descargarlo gratis o instalar en Visual Studio con NuGet.
Install-Package IronPdf
Tutorial
2. Cargar un PDF desde la memoria
Se puede inicializar una nueva instancia de IronPdf.PdfDocument
en cualquiera de estos objetos de memoria .NET:
- Un MemoryStream
- A FileSteam
Datos binarios como matriz de bytes (byte [])
He aquí un ejemplo de lectura de una URL directamente en un flujo y, a continuación, guardado del archivo PDF en el disco utilizando C#:
/**
Load PDF from Memory
anchor-load-a-pdf-from-memory
**/
private void ReadViaMemStream()
{
//Conversión de la URL en PDF
var Renderer = new IronPdf.ChromePdfRenderer();
Uri url = new Uri("https://ironpdf.com/how-to/pdf-memory-stream/");
MemoryStream rend = Renderer.RenderUrlAsPdf(url).Stream; //Leer flujo
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf"); //Descargar
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Print.pdf; size={1}", "attachment", rend.Length.ToString()));
// Escribir búfer PDF en respuesta HTTP
HttpContext.Current.Response.BinaryWrite(rend.ToArray());
// Detener el procesamiento de páginas
HttpContext.Current.Response.End();
}
/**
Load PDF from Memory
anchor-load-a-pdf-from-memory
**/
private void ReadViaMemStream()
{
//Conversión de la URL en PDF
var Renderer = new IronPdf.ChromePdfRenderer();
Uri url = new Uri("https://ironpdf.com/how-to/pdf-memory-stream/");
MemoryStream rend = Renderer.RenderUrlAsPdf(url).Stream; //Leer flujo
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf"); //Descargar
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Print.pdf; size={1}", "attachment", rend.Length.ToString()));
// Escribir búfer PDF en respuesta HTTP
HttpContext.Current.Response.BinaryWrite(rend.ToArray());
// Detener el procesamiento de páginas
HttpContext.Current.Response.End();
}
'''
'''Load PDF from Memory
'''anchor-load-a-pdf-from-memory
'''*
Private Sub ReadViaMemStream()
var Renderer = New IronPdf.ChromePdfRenderer()
Uri url = New Uri("https://ironpdf.com/how-to/pdf-memory-stream/")
MemoryStream rend = Renderer.RenderUrlAsPdf(url).Stream 'Leer flujo
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf") 'Descargar
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Print.pdf; size={1}", "attachment", rend.Length.ToString()))
HttpContext.Current.Response.BinaryWrite(rend.ToArray())
HttpContext.Current.Response.End()
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' }
3. Guardar un PDF en la memoria
Un documento IronPdf.PdfDocument puede guardarse directamente en la memoria de dos maneras:
- IronPdf.PdfDocument.Stream exporta el PDF como System.IO.MemoryStream
- IronPdf.PdfDocument.BinaryData exporta el PDF como matriz de bytes (byte [])
4. Servir un PDF a la Web desde la memoria
Para servir o exportar un PDF a la web, es necesario enviar el archivo PDF como datos binarios en lugar de HTML. Aquí encontrará más información sobre guardar y exportar documentos PDF en C#.
He aquí un ejemplo rápido para MVC y ASP.NET:
4.1. Exportar un PDF con MVC
/**
Export PDF with MVC
anchor-export-a-pdf-with-mvc
**/
return new FileStreamResult(stream, “application/pdf”)
{
FileDownloadName = “downloadedfile.pdf”
};
/**
Export PDF with MVC
anchor-export-a-pdf-with-mvc
**/
return new FileStreamResult(stream, “application/pdf”)
{
FileDownloadName = “downloadedfile.pdf”
};
'''
'''Export PDF with MVC
'''anchor-export-a-pdf-with-mvc
'''*
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Return New FileStreamResult(stream, "application/pdf”) { FileDownloadName = "downloadedfile.pdf” };
4.1. Exportar un PDF con ASP.NET
/**
Export PDF with ASPNET
anchor-export-a-pdf-with-asp-net
**/
byte [] Binary = MyPDFDocument.BinaryData;
Response.Clear();
Response.ContentType = “application/octet-stream”;
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();
/**
Export PDF with ASPNET
anchor-export-a-pdf-with-asp-net
**/
byte [] Binary = MyPDFDocument.BinaryData;
Response.Clear();
Response.ContentType = “application/octet-stream”;
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();
'''
'''Export PDF with ASPNET
'''anchor-export-a-pdf-with-asp-net
'''*
Dim Binary() As Byte = MyPDFDocument.BinaryData
Response.Clear()
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Response.ContentType = "application/octet-stream”; Context.Response.OutputStream.Write(Binary, 0, Binary.Length); Response.Flush();