iText 7 - HTML to PDF write to MemoryStream instead of file

Phil picture Phil · Feb 6, 2019 · Viewed 7.8k times · Source

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");
    }
}

Answer

mkl picture mkl · Feb 6, 2019

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.