Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

itext

itext7

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");
    }
}
like image 246
Phil Avatar asked Nov 05 '25 06:11

Phil


2 Answers

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.

like image 197
mkl Avatar answered Nov 06 '25 21:11

mkl


Generally this approach works

using (var ms = new MemoryStream())
{
    //yourStream.Seek(0, SeekOrigin.Begin)
    yourStream.CopyTo(ms);
}
like image 33
Derviş Kayımbaşıoğlu Avatar answered Nov 06 '25 21:11

Derviş Kayımbaşıoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!