C# 如何在itextsharp文档中并行设置两个表?
如何在一个文档中并行设置两个表 生成pdf的示例代码是C# 如何在itextsharp文档中并行设置两个表?,c#,itextsharp,C#,Itextsharp,如何在一个文档中并行设置两个表 生成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)
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文档失败”。请帮助我解决此错误并获得预期输出。您的代码中存在许多问题。立即可见的:
- 您不关闭文档
,而只在关闭时创建PDF的某些重要部分,特别是交叉引用表。因此,您必须在完成文档内容后尽快关闭文档doc
- 您尝试将
写入响应:文档
这是错误的,您必须将Response.Write(doc);
的输出指向响应。实际上,您也在尝试两次传输PDF:PdfWriter
但是:PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
- 在开始编写响应后更改响应属性,即首先创建一个PDF,将其流式传输到
,然后才更改内容类型、内容配置和缓存头 这很可能会使response.OutputStream
响应忽略您的设置,或者忘记在此之前已传输到其中的内容
在您解决这些问题之前,我建议您创建一个简单的HelloWorld PDF而不是并行表,这样在生成PDF时就不会出现问题,在使用web服务类时也不会出现问题,例如
Response
会相互混叠。您的代码中存在许多问题。立即可见的:
- 您不关闭文档
,而只在关闭时创建PDF的某些重要部分,特别是交叉引用表。因此,您必须在完成文档内容后尽快关闭文档doc
- 您尝试将
写入响应:文档
这是错误的,您必须将Response.Write(doc);
的输出指向响应。实际上,您也在尝试两次传输PDF:PdfWriter
但是:PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
- 在开始编写响应后更改响应属性,即首先创建一个PDF,将其流式传输到
,然后才更改内容类型、内容配置和缓存头 这很可能会使response.OutputStream
响应忽略您的设置,或者忘记在此之前已传输到其中的内容
Response
相互混合