2012-10-23 174 views
0

我有一个List<object>这个列表包含数千条记录。我想用itextsharp生成pdf。和Pdfptable生成PDF它工作正常,但我只想在pdf中每页10条记录。
我该怎么做?设置固定的每页行数,使用itextsharp生成PDF

+0

怎么样一个循环检索(最多)从该列表中10项,创建这些项目表,增加了表格文档,并进入下一页?或者我误解了你的问题? – mkl

+0

是的。这工作得很好,但我表只覆盖了一半的PDF页面,另一半仍然是空白的,我想表格10行将覆盖整个PDF页面..它是如何做到的..? – SST

回答

2

另一种方式来设置每页行数:

using System.Diagnostics; 
using System.IO; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

namespace RowsCountSample 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (var pdfDoc = new Document(PageSize.A4)) 
      { 
       var pdfWriter = PdfWriter.GetInstance(pdfDoc, new FileStream("Test.pdf", FileMode.Create)); 
       pdfDoc.Open(); 

       var table1 = new PdfPTable(3); 
       table1.HeaderRows = 2; 
       table1.FooterRows = 1; 

       //header row 
       var headerCell = new PdfPCell(new Phrase("header")); 
       headerCell.Colspan = 3; 
       headerCell.HorizontalAlignment = Element.ALIGN_CENTER; 
       table1.AddCell(headerCell); 

       //footer row 
       var footerCell = new PdfPCell(new Phrase("footer")); 
       footerCell.Colspan = 3; 
       footerCell.HorizontalAlignment = Element.ALIGN_CENTER; 
       table1.AddCell(footerCell); 

       //adding some rows 
       for (int i = 0; i < 70; i++) 
       { 
        //adds a new row 
        table1.AddCell(new Phrase("Cell[0], Row[" + i + "]")); 
        table1.AddCell(new Phrase("Cell[1], Row[" + i + "]")); 
        table1.AddCell(new Phrase("Cell[2], Row[" + i + "]")); 

        //sets the number of rows per page 
        if (i > 0 && table1.Rows.Count % 7 == 0) 
        { 
         pdfDoc.Add(table1); 
         table1.DeleteBodyRows(); 
         pdfDoc.NewPage(); 
        } 
       } 

       pdfDoc.Add(table1); 
      } 

      //open the final file with adobe reader for instance. 
      Process.Start("Test.pdf"); 
     } 
    } 
} 
2

在最新版本的iTextSharp的的(5.3.3),加入新的功能,允许你定义的断点:SetBreakPoints(int[] breakPoints) 如果定义的10的倍数的数组,你可以用它来获得预期的效果。

如果您有较旧的版本,您应该遍历列表并为每10个对象创建一个新的PdfPTable。请注意,如果您想要将应用程序的内存使用量保持在较低水平,则这是更好的解决方案。

+0

是的。第二个选项对我来说工作正常...这工作正常,但我表只涵盖了一半的PDF页面另一半仍然是空白的,我想表10行将覆盖整个PDF页..如何做到..? – SST

+0

我不确定你的意思。有一种方法可以扩展最后一行,但是最后一行会有很多空白。还有一种设置固定行高的方法,但如果内容比行高更多,则不适合的内容将会丢失。最后,有一种方法可以设置最小高度(可以使用页面高度/ 10),但是如果有更多内容,则该行将超过最小高度,并且表格将被拆分并分布在两页上。对你的需求的描述对于人们能够回答是不够的。 –