How can I set two tables parallelly in a 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 下载但显示错误消息“无法加载 PDF 文档”。请帮助我解决错误并获得预期的输出
您的代码中有很多问题。立即可见的:
你没有关闭文档doc
但只有在关闭时才会创建 PDF 的某些重要部分,特别是交叉引用表。因此,您必须在完成其内容后尽快关闭该文档。
-
你尝试写下doc
到响应:
Response.Write(doc);
这是错误的,你必须直接输出PdfWriter
到响应。实际上,您也这样做,有点尝试将 PDF 传输两次:
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
But:
-
您更改响应属性after开始写回应,即您首先创建一个 PDF,并将其流式传输到Response.OutputStream
然后才更改内容类型、内容配置和缓存标头。
这很可能使得Response
忽略您的设置或忘记到目前为止已流入其中的内容。
在解决这些问题之前,我建议您创建一个简单的你好世界PDF 而不是并行表,不会在 PDF 生成中出现问题,也不会在使用 Web 服务类(如Response
互相混合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)