iText 7-HTML到PDF写入MemoryStream而不是文件 [英] iText 7 - HTML to PDF write to MemoryStream instead of file
问题描述
我正在使用iText 7(特别是HtmlConverter.ConvertToDocument
方法)将HTML转换为PDF.问题是,我真的不希望在服务器上创建PDF文件,而是希望在内存中做所有事情,然后将其发送给用户浏览器,以便他们下载.
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.
任何人都可以向我展示一个如何使用此库的示例,而不是将文件写入到MemoryStream中,这样我就可以将其直接发送给浏览器了吗?
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");
}
}
推荐答案
在document
和pdfWriter
在其中完成结果创建之前,您要插入workStream
.此外,干预的意图还不清楚,首先要从内存流中检索字节,然后再将其写回内存中……?
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");
}
顺便说一句,由于您对HtmlConverter.ConvertToDocument
返回的document
本质上没有做任何特别的事情,因此您可以使用其他HtmlConverter
方法,而代码开销更少.
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.
这篇关于iText 7-HTML到PDF写入MemoryStream而不是文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!