【问题标题】:How to set two tables parallelly in itextsharp document?如何在itextsharp文档中并行设置两个表?
【发布时间】:2016-06-24 19:12:19
【问题描述】:

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

我生成 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 下载但显示错误消息“无法加载 PDF 文档”。请帮助我解决错误并获得预期的输出

【问题讨论】:

    标签: c# itextsharp


    【解决方案1】:

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

    • 您不会关闭文档doc,而是仅在关闭时创建 PDF 的某些重要部分,尤其是交叉引用表。因此,您必须在完成其内容后尽快关闭文档。

    • 您尝试将doc 写入响应

      Response.Write(doc);
      

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

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

      但是:

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

      这很可能使Response 忽略您的设置,或者忘记到那时为止已流入其中的内容。

    在您解决这些问题之前,我建议您创建一个简单的 HelloWorld PDF,而不是您的并行表,以免在 PDF 生成和使用 Web 服务类(如 @987654328)时出现问题@相互交融。

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多