Reputation: 35781
In an ASP.NET MVC 4.8 C# app, I have an HTML string in memory that needs to be converted to a PDF byte array using Aspose's library. All the processing occurs in-memory and nothing is saved to disk. The HTML is generated on the fly and PDF isn't saved to disk but will be attached to an email and sent.
The Aspose docs explain how to load an HTML from disk and save a PDF to disk. I can't find anything on how to do this all in-memory.
Thank you.
Upvotes: 0
Views: 872
Reputation: 122
public static async Task<byte[]> ConvertHtmlStringToPdfAsync(string stringHtml, PaperSize paper)
{
return await Task.Run(() =>
{
// Conversão síncrona sendo executada em uma tarefa separada
var pdf = Pdf
.From(stringHtml)
.OfSize(paper)
.WithoutOutline()
.WithMargins(0.5.Centimeters())
.Portrait()
.Comressed()
.Content();
return pdf;
});
}
Nops !!! but a have anolther approach for that. Note: download by nuget NuGet\Install-Package OpenHtmlToPdf -Version 1.12.0
Upvotes: 1
Reputation: 122
That's a only approach it works fine.
consider using .net 8 c# visual studio 2022
Install NuGet Package OpenHtmltoPdf
public byte [] ConvertHtmlToPdf(string html){ return Pdf.From(html) .OfSize(PaperSize.A4) .WithTitle(title) .WithoutOutline() .WithMargins(2.Millimeters()) .Portrait() .Content(); }
public async Task MyController(string html) { var pdfArray = ConvertHtmlToPdf(html); return File(pdfArray, "application/pdf", $"MyFile.pdf");
}
Upvotes: 1
Reputation: 35781
Here's the answer with the relevant code:
byte[] pdfBytes = null;
using (var ms = new MemoryStream())
{
var pdfDocument = new Document();
var htmlFragment = new HtmlFragment(myHtmlString);
pdfDocument.Pages.Add().Paragraphs.Add(htmlFragment);
pdfDocument.Save(ms);
pdfDocument.Dispose();
pdfBytes = ms.ToArray();
}
Upvotes: 1