Alex
Alex

Reputation: 35781

Aspose - convert HTML string to PDF byte array

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

Answers (3)

Marinpietri
Marinpietri

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

Marinpietri
Marinpietri

Reputation: 122

That's a only approach it works fine.

  1. consider using .net 8 c# visual studio 2022

  2. 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

Alex
Alex

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

Related Questions