如何在 itextsharp 文档中并行设置两个表?

How to set two tables parallelly in itextsharp document?

如何在一个文档中同时设置两个表格

我生成 pdf 的示例代码是,

         Document doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
        doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());

        PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);

        doc.Open();

        PdfPTable table = new PdfPTable(3);
        table.TotalWidth = 144f;
        table.LockedWidth = true;
        PdfPCell cell = new PdfPCell(new Phrase("This is table 1"));
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1;
        table.AddCell(cell);
        table.AddCell("Col 1 Row 1");
        table.AddCell("Col 2 Row 1");
        table.AddCell("Col 3 Row 1");
        table.AddCell("Col 1 Row 2");
        table.AddCell("Col 2 Row 2");
        table.AddCell("Col 3 Row 2");
        table.WriteSelectedRows(0, -1, doc.Left, doc.Top, writer.DirectContent);


        table = new PdfPTable(3);
        table.TotalWidth = 144f;
        table.LockedWidth = true;
        cell = new PdfPCell(new Phrase("This is table 2"));
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1;
        table.AddCell(cell);
        table.AddCell("Col 1 Row 1");
        table.AddCell("Col 2 Row 1");
        table.AddCell("Col 3 Row 1");
        table.AddCell("Col 1 Row 2");
        table.AddCell("Col 2 Row 2");
        table.AddCell("Col 3 Row 2");
        table.WriteSelectedRows(0, -1, doc.Left + 200, doc.Top, writer.DirectContent);
        doc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;" + "filename=Sample .pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(doc);
        Response.End();

当运行此代码时,pdf下载但显示错误消息"Failed to load PDF document"。请帮助我解决错误并获得预期的输出

您的代码中存在许多问题。立即可见的:

  • 您没有关闭文档 doc 但只有在关闭时才会创建 PDF 的某些重要部分,尤其是十字参考 table。因此,您必须在完成其内容后尽快关闭文档。

  • 您尝试将 doc 写入响应:

    Response.Write(doc);
    

    这是错误的,您必须将 PdfWriter 的输出定向到响应。您实际上也这样做了,有点试图传输 PDF 两次:

    PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
    

    但是:

  • 您在开始编写响应后更改响应属性,即您首先创建一个 PDF 流式传输到Response.OutputStream 之后才更改内容类型、内容配置和缓存 headers。

    这很可能会导致 Response 忽略您的设置或忘记之前流入其中的内容。

在您解决这些问题之前,我建议您创建一个简单的 HelloWorld PDF 而不是并行 tables,这样 PDF 生成和问题就不会出现问题在网络服务的使用上类喜欢Response相互交织