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

风流意气都作罢 提交于 2021-01-24 09:26:12

问题


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

回答1:


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.




回答2:


Generally this approach works

using (var ms = new MemoryStream())
{
    //yourStream.Seek(0, SeekOrigin.Begin)
    yourStream.CopyTo(ms);
}


来源:https://stackoverflow.com/questions/54556348/itext-7-html-to-pdf-write-to-memorystream-instead-of-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!