iText 7 - HTML to PDF write to MemoryStream instead of file
Asked Answered
M

2

4

I'm using iText 7, specifically the HtmlConverter.ConvertToDocument method, to convert HTML to PDF. The problem is, I would really rather not create a PDF file on my server, I'd rather do everything in memory and just send it to the users browser so they can download it.

Could anyone show me an example of how to use this library but instead of writing to file write to a MemoryStream so I can send it directly to the browser?

I've been looking for examples and all I can seem to find are those which refer to file output.

I've tried the following, but keep getting an error about cannot access a closed memory stream.

public FileStreamResult pdf() {
    using (var workStream = new MemoryStream())
    using (var pdfWriter = new PdfWriter(workStream)) {
        pdfWriter.SetCloseStream(false);
        using (var document = HtmlConverter.ConvertToDocument(html, pdfWriter)) {
            //Returns the written-to MemoryStream containing the PDF.   
            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return new FileStreamResult(workStream, "application/pdf");
        }
        //return new FileStreamResult(workStream, "application/pdf");
    }
}
Merat answered 6/2, 2019 at 14:50 Comment(0)
A
6

You meddle with the workStream before the document and pdfWriter have finished creating the result in it. Furthermore, the intent of your meddling is unclear, first you retrieve the bytes from the memory stream, then you write them back into it...?

public FileStreamResult pdf()
{
    var workStream = new MemoryStream())

    using (var pdfWriter = new PdfWriter(workStream))
    {
        pdfWriter.SetCloseStream(false);
        using (var document = HtmlConverter.ConvertToDocument(html, pdfWriter))
        {
        }
    }

    workStream.Position = 0;
    return new FileStreamResult(workStream, "application/pdf");
}

By the way, as you are essentially doing nothing special with the document returned by HtmlConverter.ConvertToDocument, you probably could use a different HtmlConverter method with less overhead in your code.

Amice answered 6/2, 2019 at 15:49 Comment(2)
Is there a way to set the document page size if following this method?Ezzo
I would think by setting css media attributes accordingly.Amice
T
1

Generally this approach works

using (var ms = new MemoryStream())
{
    //yourStream.Seek(0, SeekOrigin.Begin)
    yourStream.CopyTo(ms);
}
Thyroiditis answered 6/2, 2019 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.