如何使用 iText 返回 PDF

Ter*_*oll 1 c# itext .net-core

我试图返回带有简单文本的 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);
Run Code Online (Sandbox Code Playgroud)

小智 5

您必须在不关闭底层流的情况下关闭编写器,这将刷新其内部缓冲区。照原样,文档并未完全写入内存流。除了 ms 之外的所有内容也应该在 a 中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);
Run Code Online (Sandbox Code Playgroud)