iTextSharp 生成无效的 PDF

iTextSharp produces invalid PDF

使用 itextsharp 4.2.0,我做了以下函数在内存中生成一个虚拟 PDF 并将其发送回客户端:

internal override byte[] GeneratePDFDocument(pdfContent content)
{
    Document document = new Document(PageSize.A4, 30f, 30f, 30f, 30f);

    MemoryStream output = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, output);
    document.Open();
    document.Add(new Paragraph("Hello World"));
    byte[] response = output.ToArray();
    document.Close();
    return response;
}

从静态函数调用:

public static byte[] Print(string jsonData)
{
    PDFGeneratorBase generator;
    generator = new ITextSharpGenerator();
    return generator.GeneratePDFDocument(view.GetViewData());
}

从 WebAPI 控制器调用:

public HttpResponseMessage PrintPDF(HttpRequestMessage req)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    byte[] pdfData = PrintReport.Print(printJobString);
    result.Content = new ByteArrayContent(pdfData);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "PrintPDF.pdf";
    return result;
}

如果我在 Foxit Reader 7.2 中打开生成的 PDF,错误消息是 "Format error: not a PDF or corrupted"。

我做错了什么?

抓取字节数组前需要关闭文档。关闭文档会刷新 "finishes" 文档的内部缓冲区。交换这个:

byte[] response = output.ToArray();
document.Close();

有了这个:

document.Close();
byte[] response = output.ToArray();