如何使用 iText return PDF
How to return PDF using iText
我正在尝试 return 带有简单文本的 PDF,但在下载文档时出现以下错误:加载 PDF 文档失败。任何有关如何解决此问题的想法都将受到赞赏。
MemoryStream ms = new MemoryStream();
PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
Document document = new Document(pdfDocument);
document.Add(new Paragraph("Hello World"));
//document.Close();
//writer.Close();
ms.Position = 0;
string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
return File(ms, "application/pdf", pdfName);
您必须在不关闭底层流的情况下关闭编写器,这将刷新其内部缓冲区。照原样,文档并没有被完整地写入内存流。除了 ms 之外的所有内容也应该在 using
中。
您可以通过检查代码中 ms
的长度与下面的代码来验证是否发生这种情况。
当 using (PdfWriter writer =...)
关闭时,它会关闭编写器,这会导致它将其挂起的写入刷新到基础流 ms
。
MemoryStream ms = new MemoryStream();
using (PdfWriter writer = new PdfWriter(ms))
using (PdfDocument pdfDocument = new PdfDocument(writer))
using (Document document = new Document(pdfDocument))
{
/*
* Depending on iTextSharp version, you might instead use:
* writer.SetCloseStream(false);
*/
writer.CloseStream = false;
document.Add(new Paragraph("Hello World"));
}
ms.Position = 0;
string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
return File(ms, "application/pdf", pdfName);
我正在尝试 return 带有简单文本的 PDF,但在下载文档时出现以下错误:加载 PDF 文档失败。任何有关如何解决此问题的想法都将受到赞赏。
MemoryStream ms = new MemoryStream();
PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
Document document = new Document(pdfDocument);
document.Add(new Paragraph("Hello World"));
//document.Close();
//writer.Close();
ms.Position = 0;
string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
return File(ms, "application/pdf", pdfName);
您必须在不关闭底层流的情况下关闭编写器,这将刷新其内部缓冲区。照原样,文档并没有被完整地写入内存流。除了 ms 之外的所有内容也应该在 using
中。
您可以通过检查代码中 ms
的长度与下面的代码来验证是否发生这种情况。
当 using (PdfWriter writer =...)
关闭时,它会关闭编写器,这会导致它将其挂起的写入刷新到基础流 ms
。
MemoryStream ms = new MemoryStream();
using (PdfWriter writer = new PdfWriter(ms))
using (PdfDocument pdfDocument = new PdfDocument(writer))
using (Document document = new Document(pdfDocument))
{
/*
* Depending on iTextSharp version, you might instead use:
* writer.SetCloseStream(false);
*/
writer.CloseStream = false;
document.Add(new Paragraph("Hello World"));
}
ms.Position = 0;
string pdfName = $"IP-Report-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
return File(ms, "application/pdf", pdfName);