PdfPTable作为iTextSharp中的标题

我需要一个包含大约12个单元格的表格作为标题显示。 以下代码无法执行此操作。 我知道table2没有12个单元格。 在第二页上,仅显示“测试”。 我错过了什么?

提前致谢!

Document document = new Document(); try { PdfWriter.GetInstance(document, new FileStream("TableTest.pdf", FileMode.Create)); document.Open(); PdfPTable table = new PdfPTable(1); table.WidthPercentage = 100; PdfPTable table2 = new PdfPTable(2); //logo PdfPCell cell2 = new PdfPCell(Image.GetInstance(@"C:\path\to\file.gif")); cell2.Colspan = 2; table2.AddCell(cell2); //title cell2 = new PdfPCell(new Phrase("\nTITLE TEXT", new Font(Font.HELVETICA, 16, Font.BOLD | Font.UNDERLINE))); cell2.HorizontalAlignment = Element.ALIGN_CENTER; cell2.Colspan = 2; table2.AddCell(cell2); PdfPCell cell = new PdfPCell(table2); table.HeaderRows = 1; table.AddCell(cell); table.AddCell(new PdfPCell(new Phrase(""))); document.Add(table); document.Add(new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntesting")); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); 

答对了! PdfPageEventHandler类为我工作。

我使用PdfPageEventHelper重写OnEndPage方法:

 class _events : PdfPageEventHelper { public override void OnEndPage(PdfWriter writer, Document document) { PdfPTable table = new PdfPTable(1); //table.WidthPercentage = 100; //PdfPTable.writeselectedrows below didn't like this table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; //this centers [table] PdfPTable table2 = new PdfPTable(2); //logo PdfPCell cell2 = new PdfPCell(Image.GetInstance(@"C:\path\to\file.gif")); cell2.Colspan = 2; table2.AddCell(cell2); //title cell2 = new PdfPCell(new Phrase("\nTITLE", new Font(Font.HELVETICA, 16, Font.BOLD | Font.UNDERLINE))); cell2.HorizontalAlignment = Element.ALIGN_CENTER; cell2.Colspan = 2; table2.AddCell(cell2); PdfPCell cell = new PdfPCell(table2); table.AddCell(cell); table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 36, writer.DirectContent); } } 

然后,建立pdf

 Document document = new Document(PageSize.A4, 36, 36, 36 + , 36); // note height should be set here _events e = new _events(); PdfWriter pw = PdfWriter.GetInstance(document, new FileStream("TableTest.pdf", FileMode.Create)); pw.PageEvent = e; document.Open(); for(int i=0;i<100;i++) { document.Add(new Phrase("TESTING\n")); } document.Close(); 

当使用’n’行创建PdfPTable时,我使用了一种非常简单的方法在每个页面上添加标题行,其中’n’可以是任何整数。 我使用的是iTextSharp 4.0.4.0。

因此,您可以创建一个包含1000行或2行或5000行的表,但iTextSharp会自动为您输出页面。 iTextSharp不会做的是自动添加标题以开始每个页面。

为了为每个页面添加一个标题行,我所做的就是在创建包含其所有行和单元格的PdfPTable后添加单行代码 ,然后iTextSharp自动将标题行分页输出。 ‘table’是我在设置其HeaderRows属性之前在我的代码中创建的PdfPTable的实例。

 table.HeaderRows = 1; //this will automatically insert a header row //at start of every page. The first row you created //in your code will be used as the header row in this case. 

如果您有多个页面,这将无效。 如果您有多个页面,则需要使用OnStartPage事件而不是onEndPage事件。