在MVC和.NET中使用iText 7生成要下载的PDF [英] Generate PDF for Download using iText 7 in MVC and .NET
问题描述
我一直在尝试获取MVC应用程序以生成PDF(填充数据)并提示将其下载给用户.我已经设置了一个测试方法来查看它的完成方式,并且我试图在内存中创建文档,因为我知道浏览器并不总是知道如果只将字节流传递给它,该怎么办.>
这是我使用的方法:
//Test Report
public ActionResult Report()
{
MemoryStream stream = new MemoryStream();
PdfWriter wri = new PdfWriter(stream);
PdfDocument pdf = new PdfDocument(wri);
Document doc = new Document(pdf);
doc.Add(new Paragraph("Hello World!"));
doc.Close();
return new FileStreamResult(stream, "application/pdf");
}
每次尝试加载Report()方法时,都会收到一条错误消息,指出该流已关闭,因此无法访问.我研究了为什么这样做的几种不同解释,但它们似乎都是针对iTextSharp和iText 5的,因此解决方案不起作用.
这是我在做错什么吗?
尝试处置任何IDisposable对象并返回原始数组
public ActionResult Report()
{
byte[] pdfBytes;
using (var stream = new MemoryStream())
using (var wri = new PdfWriter(stream))
using (var pdf = new PdfDocument(wri))
using (var doc = new Document(pdf))
{
doc.Add(new Paragraph("Hello World!"));
doc.Flush();
pdfBytes = stream.ToArray();
}
return new FileContentResult(pdfBytes, "application/pdf");
}
I have been trying to get an MVC application to generate a PDF(populated with data) and prompt to download it to the user. I've setup a test method just to see how it would be done, and I'm trying to create the document in memory since I know browsers don't always know what to do if you just pass it a byte stream.
Here is the method I'm using:
//Test Report
public ActionResult Report()
{
MemoryStream stream = new MemoryStream();
PdfWriter wri = new PdfWriter(stream);
PdfDocument pdf = new PdfDocument(wri);
Document doc = new Document(pdf);
doc.Add(new Paragraph("Hello World!"));
doc.Close();
return new FileStreamResult(stream, "application/pdf");
}
Every time I attempt to load the Report() method, I get an error saying that the stream cannot be accessed because it's closed. I've looked into a few different explanations into why this is, but all of them seem to be for iTextSharp and iText 5, so the solutions don't work.
What am I doing wrong, here?
try to dispose any IDisposable object and return a raw array
public ActionResult Report()
{
byte[] pdfBytes;
using (var stream = new MemoryStream())
using (var wri = new PdfWriter(stream))
using (var pdf = new PdfDocument(wri))
using (var doc = new Document(pdf))
{
doc.Add(new Paragraph("Hello World!"));
doc.Flush();
pdfBytes = stream.ToArray();
}
return new FileContentResult(pdfBytes, "application/pdf");
}
这篇关于在MVC和.NET中使用iText 7生成要下载的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!