首页 iText学习笔记之PdfPTable

iText学习笔记之PdfPTable

举报
开通vip

iText学习笔记之PdfPTableiText学习笔记之PdfPTable iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 PdfPTable PdfPTable 当你想使用iText制作账单、发票、清单、报表等电子表单时,你很可能需 要将数据放置在表格当中,这就是下面要介绍的PdfPTable对象和PdfPCell对象。 这两个类使用起来都非常方便:构建一张指定列数的表,然后添加单元格: PdfPTable table = new PdfPTable(3); PdfPCel...

iText学习笔记之PdfPTable
iText学习笔记之PdfPTable iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 PdfPTable PdfPTable 当你想使用iText制作账单、发票、清单、报 关于同志近三年现实表现材料材料类招标技术评分表图表与交易pdf视力表打印pdf用图表说话 pdf 等电子表单时,你很可能需 要将数据放置在表格当中,这就是下面要介绍的PdfPTable对象和PdfPCell对象。 这两个类使用起来都非常方便:构建一张指定列数的表,然后添加单元格: PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3")); cell.setColspan(3); table.addCell(cell); table.addCell("1.1"); table.addCell("2.1"); table.addCell("3.1"); table.addCell("1.2"); table.addCell("2.2"); table.addCell("3.2"); document.add(table); PdfPTable是一个强大而灵活的对象,但PdfPTable只用于生成PDF,如果你需要生成HTML或RTF文档,那么只能使用Table对象了(Table对象现在已不被支持)。 通过Document.add()方法添加PdfPTable对象,其默认宽度是页面可编辑空 间的80%并居中对齐,要想改变这些默认值,可使用setWidthPercentage和setHorizontalAlignment方法。 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 // step1 Document document = new Document(PageSize.A4); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("TableWidthAlignment.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3")); cell.setColspan(3); table.addCell(cell); table.addCell("1.1"); table.addCell("2.1"); table.addCell("3.1"); table.addCell("1.2"); table.addCell("2.2"); table.addCell("3.2"); cell = new PdfPCell(new Paragraph("cell test1")); cell.setBorderColor(new Color(255, 0, 0)); table.addCell(cell); cell = new PdfPCell(new Paragraph("cell test2")); cell.setColspan(2); cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0)); table.addCell(cell); document.add(table); table.setWidthPercentage(100); document.add(table); table.setWidthPercentage(50); table.setHorizontalAlignment(Element.ALIGN_RIGHT); document.add(table); table.setHorizontalAlignment(Element.ALIGN_LEFT); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 上面的例子运行效果如下: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 我们在表格中定义了很多列,iText自动计算各列的绝对宽度,每个单元格 的默认宽度是:表格的绝对宽度/列数,同一表格中的所有列的宽度相同。当然 你可能需要改变列的宽度,方法有如下的几种: 1)使用另外一个构造器函数:PdfPTable(float[] relativeWidths)。例如,如果你想构造的表中,前两个采用默认的宽度,第三列是默认宽度的两倍,可以使用 float数组{1f,1f,2f}作为相对宽度relativeWidths参数,iText会自动为你计算绝对宽度。 你可以通过setWidths方法来改变已经构建的PdfPTable中各列的宽度。在下例中,百分比从(10%,10%,5%75%)变为(20%,20%,10%,50%),因而第二张表的样式完全不同。 2)如果你想指定各列的绝对宽度,那么你首先得让iText计算表格宽度在页面中占用的百分比。这种情况下,你应该使用setWidthPercentage(float[] columnWidths, Rectancle pageSize)。在下例中可以看到,你需要先做些计算来获 取正确的pageSize。 如果将表格的宽度锁定为“total width”,使用绝对宽度其实更加方便,需要 用到的方法是setTotalWidths和setLockedWidth。下例中,各列的宽度仍然是10%、10%、5%、75%,因而各列的实际宽度分别是30pt、30pt、15pt、225pt。 // step1 Document document = new Document(PageSize.A4, 36, 36, 36, 36); try { // step2 PdfWriter.getInstance(document, iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 new FileOutputStream("CellWidths.pdf")); // step3 document.open(); // step4 float[] widths = {0.1f, 0.1f, 0.05f, 0.75f}; PdfPTable table = new PdfPTable(widths); table.addCell("10%"); table.addCell("10%"); table.addCell("5%"); table.addCell("75%"); table.addCell("aa"); table.addCell("aa"); table.addCell("a"); table.addCell("aaaaaaaaaaaaaaa"); table.addCell("bb"); table.addCell("bb"); table.addCell("b"); table.addCell("bbbbbbbbbbbbbbb"); table.addCell("cc"); table.addCell("cc"); table.addCell("c"); table.addCell("ccccccccccccccc"); document.add(table); document.add(new Paragraph("We change the percentages:\n\n")); widths[0] = 20f; widths[1] = 20f; widths[2] = 10f; widths[3] = 50f; table.setWidths(widths); document.add(table); widths[0] = 40f; widths[1] = 40f; widths[2] = 20f; widths[3] = 300f; Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72)); table.setWidthPercentage(widths, r); document.add(new Paragraph("We change the percentage using absolute widths:\n\n")); document.add(table); document.add(new Paragraph("We use a locked width:\n\n")); table.setTotalWidth(300); table.setLockedWidth(true); document.add(table); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 上面的例子运行效果如下: 如果你不改变默认设置,所有表格都会前后紧贴在一起,除非有新增的行被添加进去。要想避免这种情况,可以使用方法setSpacingBefore和setSpacingAfter。 // step1 Document document = new Document(PageSize.A4); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("TableSpacing.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3")); cell.setColspan(3); table.addCell(cell); table.addCell("1.1"); table.addCell("2.1"); table.addCell("3.1"); table.addCell("1.2"); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 table.addCell("2.2"); table.addCell("3.2"); cell = new PdfPCell(new Paragraph("cell test1")); cell.setBorderColor(new Color(255, 0, 0)); table.addCell(cell); cell = new PdfPCell(new Paragraph("cell test2")); cell.setColspan(2); cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0)); table.addCell(cell); table.setWidthPercentage(50); document.add(new Paragraph("We add 2 tables:")); document.add(table); document.add(table); document.add(new Paragraph("They are glued to eachother")); document.add(table); document.add(new Paragraph("This is not very nice. Turn to the next page to see how we solved this")); document.newPage(); document.add(new Paragraph("We add 2 tables, but with a certain 'SpacingBefore':")); table.setSpacingBefore(15f); document.add(table); document.add(table); document.add(new Paragraph("Unfortunately, there was no spacing after.")); table.setSpacingAfter(15f); document.add(table); document.add(new Paragraph("This is much better, don't you think so?")); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果如下: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 PdfPCells 在表格中添加单元格的最简单的方法是使用addCell(String text)。在文档的第一个例子“MyFirstTable”中,我们使用了addCell(PdfPCell cell)方法,那是因为我们想为新的PdfPCell设置一些属性。如果我们使用addCell(String text)添加 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 一个新的PdfPCell,iText将会以text作为内容,而使用默认的单元格“default cell” 的样式作为当前添加的单元格的样式,我们可通过方法getDefaultCell来改变默 认单元格的样式属性。此功能对addCell(Phrase phrase)也一样有效。 table.getDefaultCell().setGrayFill(0.8f); table.getDefaultCell().setBorderColor(new Color(255, 0, 0)); table.getDefaultCell().setColspan(2); 举例如下: // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream("DefaultCell.pdf")); // step 3: we open the document document.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3")); cell.setColspan(3); table.addCell(cell); table.addCell("1.1"); table.addCell("2.1"); table.addCell("3.1"); table.getDefaultCell().setGrayFill(0.8f); table.addCell("1.2"); table.addCell("2.2"); table.addCell("3.2"); table.getDefaultCell().setGrayFill(0f); table.getDefaultCell().setBorderColor(new Color(255, 0, 0)); table.addCell("cell test1"); table.getDefaultCell().setColspan(2); table.getDefaultCell().setBackgroundColor(new Color(0xC0, 0xC0, 0xC0)); table.addCell("cell test2"); document.add(table); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); 运行结果: 在以上例子当中,我们通过setColspan方法可以改变单元格所跨的表格列 数,可惜的是,由于PdfPTable底层设计的局限性原因,iText并不提供setRowspan 方法,所以必须采用一种变通的方法实现此功能――嵌套表,即使用 addCell(PdfPTable table)方法。 // step1 Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("NestedTables.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(4); PdfPTable nested1 = new PdfPTable(2); nested1.addCell("1.1"); nested1.addCell("1.2"); PdfPTable nested2 = new PdfPTable(1); nested2.addCell("2.1"); nested2.addCell("2.2"); for (int k = 0; k < 24; ++k) { if (k == 1) { iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 table.addCell(nested1); } else if (k == 20) { table.addCell(nested2); } else { table.addCell("cell " + k); } } document.add(table); // step 5: we close the document document.close(); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行效果: PdfPCell 使用的方法addCell(Image image)可实现向PdfPTable中添加图像,为适应单 元格的大小,图像会自动被缩放。此方法类似于PdfPCell(Image image)和 PdfPCell(Image image, boolean fit)方法,但他们也存在一些细微的区别,举例如 下: // step 1: creation of a document-object Document document = new Document(); try { // step 2: PdfWriter.getInstance(document, new FileOutputStream("ImageCell.pdf")); // step 3: we open the document iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 document.open(); Image image = Image.getInstance("otsoe.jpg"); float[] widths = {1f, 4f}; PdfPTable table = new PdfPTable(widths); table.addCell("This is my dog"); table.addCell(image); table.addCell("This two"); table.addCell(new PdfPCell(image, true)); table.addCell("This three"); table.addCell(new PdfPCell(image, false)); document.add(table); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); 运行结果: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 单元格中的内容在默认情况下是自动换行的,要想改变默认值可使用方法 setNoWrap(true),不过这样可能会使结果看上去很丑,所以要慎用。如果采用了 默认值设置,表格每行的高度是由iText自动计算取得的,计算依据来自以下参 数:内容的行数、行间距、补白值等。有些情况下你可能想自己设置行的高度为 固定值,可以通过方法setFixedHeight来实现。当然,如果单元格中的内容超出 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 了你所设置的高度,那么会使内容有丢失。 如果想设置行的最小高度可使用方法setMinimumHeight,可实现行的高度不 小于所设置的值,即使单元格的内容不够多。还有个常用的方法 setExtendLastRow,可将表格的最后一行填充到页面的最底部。 // step1 Document document = new Document(PageSize.A4); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("CellHeights.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(2); table.setExtendLastRow(true); PdfPCell cell; // wrap / nowrap cell = new PdfPCell(new Paragraph("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah")); table.addCell("wrap"); cell.setNoWrap(false); table.addCell(cell); table.addCell("no wrap"); cell.setNoWrap(true); table.addCell(cell); // height cell = new PdfPCell(new Paragraph("1. blah blah\n2. blah blah blah\n3. blah blah\n4. blah blah blah\n5. blah blah\n6. blah blah blah\n7. blah blah\n8. blah blah blah")); table.addCell("height"); table.addCell(cell); table.addCell("fixed height"); cell.setFixedHeight(50f); table.addCell(cell); table.addCell("minimum height"); cell = new PdfPCell(new Paragraph("x")); cell.setMinimumHeight(50f); table.addCell(cell); table.addCell("extend last row"); cell = new PdfPCell(new Paragraph("almost no content, but the row is iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 extended")); table.addCell(cell); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 下例解释了方法setHorizontalAlignment和setVerticalAlignment的用法,对 于水平方向对齐,可选择的对齐方式有: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 o Element.ALIGN_LEFT o Element.ALIGN_CENTER o Element.ALIGN_RIGHT o Element.ALIGN_JUSTIFIED 对于垂直方向的对齐,可选择的对齐方式有: o Element.ALIGN_TOP o Element.ALIGN_MIDDLE o Element.ALIGN_BOTTOM o Element.ALIGN_BASELINE // step1 Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("Alignment.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(2); PdfPCell cell; Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog."); table.addCell("default alignment"); cell = new PdfPCell(p); table.addCell(cell); table.addCell("centered alignment"); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); table.addCell("right alignment"); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell); table.addCell("justified alignment"); cell = new PdfPCell(p); cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); table.addCell(cell); table.addCell("blah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\n"); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BASELINE); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 table.addCell("baseline"); table.addCell("blah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\n"); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell("bottom"); table.addCell("blah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\n"); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell("middle"); table.addCell("blah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\nblah\n"); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); table.addCell("top"); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果: 补白值表示单元格内容距单元格外边框的距离,设置该距离的方法有:setPadding、setPaddingTop、setPaddingRight、setPaddingLeft、setPaddingBottom。 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 行间距是单元格内容中行与行之间的距离,设置行间距的方法是setLeading(float,float),第一个float参数表示行间距的值,第二个float参数表示 字体大小的倍数。 // step1 Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("PaddingLeading.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(2); PdfPCell cell; Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog."); table.addCell("default"); table.addCell(p); table.addCell("padding 10"); cell = new PdfPCell(p); cell.setPadding(10f); table.addCell(cell); table.addCell("no padding at all"); cell = new PdfPCell(p); cell.setPadding(0f); table.addCell(cell); table.addCell("no padding at the top; large padding at the left"); cell = new PdfPCell(p); cell.setPaddingTop(0f); cell.setPaddingLeft(20f); table.addCell(cell); document.add(table); document.newPage(); table = new PdfPTable(2); table.addCell("no leading at all"); table.getDefaultCell().setLeading(0f, 0f); table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n"); table.getDefaultCell().setLeading(14f, 0f); table.addCell("fixed leading of 14pt"); table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n"); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 table.addCell("relative leading of 1.0 times the fontsize"); table.getDefaultCell().setLeading(0f, 1.0f); table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n"); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果: 在设置补白时,单元格并没有将边框的宽度计算在内,通过方法setUseBorderPadding(true)可强制将宽度计算在补白值内。在下例中,某些单元格 被设置了边框颜色和灰色填充,可以看出,绿色单元格的补白没有将洋红色边框 的宽度计算在内;而在蓝色单元格中,文字“blue”没有和青绿色的边框重叠。 // step1 Document document = new Document(PageSize.A4); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("CellColors.pdf")); // step3 document.open(); // step4 PdfPTable table = new PdfPTable(4); PdfPCell cell; iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 cell = new PdfPCell(new Paragraph("test colors:")); table.addCell(cell); cell = new PdfPCell(new Paragraph("red")); cell.setBorder(Rectangle.NO_BORDER); cell.setBackgroundColor(Color.red); table.addCell(cell); cell = new PdfPCell(new Paragraph("green")); cell.setBorder(Rectangle.BOTTOM); cell.setBorderColorBottom(Color.magenta); cell.setBorderWidthBottom(10f); cell.setBackgroundColor(Color.green); table.addCell(cell); cell = new PdfPCell(new Paragraph("blue")); cell.setBorder(Rectangle.TOP); cell.setUseBorderPadding(true); cell.setBorderWidthTop(5f); cell.setBorderColorTop(Color.cyan); cell.setBackgroundColor(Color.blue); table.addCell(cell); cell = new PdfPCell(new Paragraph("test GrayFill:")); table.addCell(cell); cell = new PdfPCell(new Paragraph("0.25")); cell.setBorder(Rectangle.NO_BORDER); cell.setGrayFill(0.25f); table.addCell(cell); cell = new PdfPCell(new Paragraph("0.5")); cell.setBorder(Rectangle.NO_BORDER); cell.setGrayFill(0.5f); table.addCell(cell); cell = new PdfPCell(new Paragraph("0.75")); cell.setBorder(Rectangle.NO_BORDER); cell.setGrayFill(0.75f); table.addCell(cell); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 最后一组影响单元格中内容的位置的方法是setUserAscender()和 setUserDescender(),举例说明他们的差别: package com.lowagie.examples.objects.tables; import java.awt.Color; import java.io.FileOutputStream; import com.lowagie.text.BadElementException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; /** * Demonstrates different borderstyles. */ public class TableBorders { /** * Demonstrates different borderstyles. * * @param args * the number of rows for each table fragment. */ public static void main(String[] args) { System.out.println("Table Borders"); // step1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TableBorders.pdf")); // step3 document.open(); // step4 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 // page 1 Font tableFont = FontFactory.getFont("Helvetica", 8, Font.BOLD, Color.BLACK); float padding = 0f; Rectangle border = new Rectangle(0f, 0f); border.setBorderWidthLeft(6f); border.setBorderWidthBottom(5f); border.setBorderWidthRight(4f); border.setBorderWidthTop(2f); border.setBorderColorLeft(Color.RED); border.setBorderColorBottom(Color.ORANGE); border.setBorderColorRight(Color.YELLOW); border.setBorderColorTop(Color.GREEN); makeTestPage(tableFont, border, writer, document, padding, true, true); Font font = FontFactory.getFont("Helvetica", 10); Paragraph p; p = new Paragraph("\nVarious border widths and colors\nuseAscender=true, useDescender=true", font); document.add(p); document.newPage(); // page 2 padding = 2f; border = new Rectangle(0f, 0f); border.setBorderWidthLeft(1f); border.setBorderWidthBottom(2f); border.setBorderWidthRight(1f); border.setBorderWidthTop(2f); border.setBorderColor(Color.BLACK); makeTestPage(tableFont, border, writer, document, padding, true, true); p = new Paragraph("More typical use - padding of 2\nuseBorderPadding=true, useAscender=true, useDescender=true", font); document.add(p); document.newPage(); // page 3 padding = 0f; border = new Rectangle(0f, 0f); border.setBorderWidthLeft(1f); border.setBorderWidthBottom(2f); border.setBorderWidthRight(1f); border.setBorderWidthTop(2f); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 border.setBorderColor(Color.BLACK); makeTestPage(tableFont, border, writer, document, padding, false, true); p = new Paragraph("\nuseBorderPadding=true, useAscender=false, useDescender=true", font); document.add(p); document.newPage(); // page 4 padding = 0f; border = new Rectangle(0f, 0f); border.setBorderWidthLeft(1f); border.setBorderWidthBottom(2f); border.setBorderWidthRight(1f); border.setBorderWidthTop(2f); border.setBorderColor(Color.BLACK); makeTestPage(tableFont, border, writer, document, padding, false, false); p = new Paragraph("\nuseBorderPadding=true, useAscender=false, useDescender=false", font); document.add(p); document.newPage(); // page 5 padding = 0f; border = new Rectangle(0f, 0f); border.setBorderWidthLeft(1f); border.setBorderWidthBottom(2f); border.setBorderWidthRight(1f); border.setBorderWidthTop(2f); border.setBorderColor(Color.BLACK); makeTestPage(tableFont, border, writer, document, padding, true, false); p = new Paragraph("\nuseBorderPadding=true, useAscender=true, useDescender=false", font); document.add(p); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); } iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 private static void makeTestPage(Font tableFont, Rectangle borders, PdfWriter writer, Document document, float padding, boolean ascender, boolean descender) throws BadElementException, DocumentException { document.newPage(); PdfPTable table = null; table = new PdfPTable(4); table.setWidthPercentage(100f); float leading = tableFont.getSize() * 1.2f; table.addCell(makeCell("1-Top", Element.ALIGN_TOP, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("2-Middle", Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("3-Bottom", Element.ALIGN_BOTTOM, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("4-Has a y", Element.ALIGN_TOP, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("5-Abcdy", Element.ALIGN_TOP, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("6-Abcdy", Element.ALIGN_MIDDLE, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("7-Abcdy", Element.ALIGN_BOTTOM, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); table.addCell(makeCell("8-This\nis\na little\ntaller", Element.ALIGN_TOP, Element.ALIGN_LEFT, tableFont, leading, padding, borders, ascender, descender)); document.add(table); } private static PdfPCell makeCell(String text, int vAlignment, int hAlignment, Font font, float leading, float padding, Rectangle borders, boolean ascender, boolean descender) { Paragraph p = new Paragraph(text, font); p.setLeading(leading); PdfPCell cell = new PdfPCell(p); cell.setLeading(leading, 0); cell.setVerticalAlignment(vAlignment); cell.setHorizontalAlignment(hAlignment); cell.cloneNonPositionParameters(borders); cell.setUseAscender(ascender); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 cell.setUseDescender(descender); cell.setUseBorderPadding(true); cell.setPadding(padding); return cell; } } 运行结果: 第一页 第二页 第三页 第四页 第五页 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 如果你的表格非常大,无法在同一页显示完,iText会为表格自动分页显示。 如果你的表格有标题行而且需要在每页都显示,你得告诉iText标题行的行数, 调用的方法是setHeaderRows。 // step1 Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); try { // step2 PdfWriter.getInstance(document, new FileOutputStream("AddBigTable.pdf")); // step3 document.open(); // step4 String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD", "119000", "96 06", "2001-08-13", "4350", "6011648299", "FLFLMTGP", "153", "119000.00" }; int NumColumns = 12; PdfPTable datatable = new PdfPTable(NumColumns); int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage datatable.setWidths(headerwidths); datatable.setWidthPercentage(100); // percentage datatable.getDefaultCell().setPadding(3); datatable.getDefaultCell().setBorderWidth(2); datatable.getDefaultCell().setHorizontalAlignment( Element.ALIGN_CENTER); datatable.addCell("Clock #"); datatable.addCell("Trans Type"); datatable.addCell("Cusip"); datatable.addCell("Long Name"); datatable.addCell("Quantity"); datatable.addCell("Fraction Price"); datatable.addCell("Settle Date"); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 datatable.addCell("Portfolio"); datatable.addCell("ADP Number"); datatable.addCell("Account ID"); datatable.addCell("Reg Rep ID"); datatable.addCell("Amt To Go "); datatable.setHeaderRows(1); // this is the end of the table header datatable.getDefaultCell().setBorderWidth(1); for (int i = 1; i < 750; i++) { if (i % 2 == 1) { datatable.getDefaultCell().setGrayFill(0.9f); } for (int x = 0; x < NumColumns; x++) { datatable.addCell(bogusData[x]); } if (i % 2 == 1) { datatable.getDefaultCell().setGrayFill(1); } } document.add(datatable); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 前面的例子当中,每一行中的文本内容只有一行。如果出现某些行中的文本 非常大,那么iText将按照“行优先”的方式对表格进行分页处理,所谓“行优 先”是说:当遇到无法在当前页显示完整的一行时,该行将被放到下一页进行显 示,而只有当一整业都无法显示完此行时,iText才会将此行拆开显示在两页中。 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 如果不想使用“行优先”的方式,而是想采用“页优先”方式(保证填满当前页 面的前提下,决定是否需要分拆行)显示,可使用方法setSplitLate(false)。 如果的确不想让行分拆,可以使用方法setSplitRows(false),但这种情况可能会导致数据丢失。 PdfPTable 使用方法writeSelectedRows可实现在指定的位置添加表格,需要传递的参 数如下: rowStart – 要写入的第一行,起始值为0 rowEnd – 要写入的最后一行+1。如果为-1,表示添加所有行 xPos – 表格左上角的x坐标值 yPos – 表格左上角的y坐标值(0表示页面的最底部) canvas – 需要被写入到表格的行内容(PdfContentByte) 下例演示怎样添加绝对位置的表格: // step 1 Document document = new Document(PageSize.A4); try { // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("tables.pdf")); float width = document.getPageSize().getWidth(); float height = document.getPageSize().getHeight(); // step 3 document.open(); // step 4 float[] columnDefinitionSize = { 33.33F, 33.33F, 33.33F }; float pos = height / 2; PdfPTable table = null; PdfPCell cell = null; table = new PdfPTable(columnDefinitionSize); table.getDefaultCell().setBorder(0); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 table.setHorizontalAlignment(0); table.setTotalWidth(width - 72); table.setLockedWidth(true); cell = new PdfPCell(new Phrase("Table added with document.add()")); cell.setColspan(columnDefinitionSize.length); table.addCell(cell); table.addCell(new Phrase("Louis Pasteur", font8)); table.addCell(new Phrase("Albert Einstein", font8)); table.addCell(new Phrase("Isaac Newton", font8)); table.addCell(new Phrase("8, Rabic street", font8)); table.addCell(new Phrase("2 Photons Avenue", font8)); table.addCell(new Phrase("32 Gravitation Court", font8)); table.addCell(new Phrase("39100 Dole France", font8)); table.addCell(new Phrase("12345 Ulm Germany", font8)); table.addCell(new Phrase("45789 Cambridge England", font8)); document.add(table); table = new PdfPTable(columnDefinitionSize); table.getDefaultCell().setBorder(0); table.setHorizontalAlignment(0); table.setTotalWidth(width - 72); table.setLockedWidth(true); cell = new PdfPCell(new Phrase("Table added with writeSelectedRows")); cell.setColspan(columnDefinitionSize.length); table.addCell(cell); table.addCell(new Phrase("Louis Pasteur", font8)); table.addCell(new Phrase("Albert Einstein", font8)); table.addCell(new Phrase("Isaac Newton", font8)); table.addCell(new Phrase("8, Rabic street", font8)); table.addCell(new Phrase("2 Photons Avenue", font8)); table.addCell(new Phrase("32 Gravitation Court", font8)); table.addCell(new Phrase("39100 Dole France", font8)); table.addCell(new Phrase("12345 Ulm Germany", font8)); table.addCell(new Phrase("45789 Cambridge England", font8)); table.writeSelectedRows(0, -1, 50, pos, writer.getDirectContent()); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 } // step 5 document.close(); 运行结果如下: 使用writeSelectedRows方法有几个问题需要注意。当你使用document.add()添加表格时,iText会根据指定的百分比自动设置表格的宽度,但如果你使用绝 对位置进行添加,iText无法帮你决定表格有多宽、需要留多大的空白,所以需 要通过setTotalWidth(float totalWidth)或setTotalWidth(float[] ColumnWidth)方法设置表格的总宽度。 同时,你还得人工的检查表格的高度是否适合当前页面,如果表格太高,超 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 出页面的部分将丢失,而不会自动分页。 如果表格的行数太多而无法在同一页中显示,那么只能通过设置 writeSelectedRows方法中的rowStart(起始行)和rowEnd(结束行)参数实现分 页;而如果表格太宽,也可以按列进行分页,使用的方法是writeSelectedRows(int colStart, int colEnd, int rowStart, int rowEnd, float xPos, float yPos, PdfContentByte canvas),如下例: System.out.println("Split Table"); // step1 Document document = new Document(PageSize.A4, 10, 10, 10, 10); try { // step2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream( "SplitTable.pdf")); // step3 document.open(); // step4 PdfContentByte cb = writer.getDirectContent(); PdfPTable table = new PdfPTable(10); for (int k = 1; k <= 100; ++k) { table.addCell("The number " + k); } table.setTotalWidth(800); table.writeSelectedRows(0, 5, 0, -1, 50, 650, cb); document.newPage(); table.writeSelectedRows(5, -1, 0, -1, 50, 650, cb); document.close(); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 运行结果如下: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 当向对象中添加对象时,添加的对象将被写入到输出流,已经写入到输出留 的对象是可以被回收的。然而,当你构建一个PdfPTable,然后向表格中不断的添加单元格却一直没有将表格添加到文档中时,PdfPTable对象占用的内存会无限制的扩大,无法被释放。所以对于特大的表格来说,这可能会导致系统崩溃。 解决办法是,将一张特大的表格分解成若干个表格,这些表格首尾相连(前 提是不使用setSpacingBefore和setSpacingAfter方法),输出的结果外观与一张表 格并无区别。见下例: System.out.println("FragmentTable"); int fragmentsize = Integer.parseInt(args[0]);//args是main方法的参数 // step1 Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); try { // step2 PdfWriter.getInstance(document,new FileOutputStream("FragmentTable.pdf")); // step3 document.open(); // step4 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 Font font = FontFactory.getFont("Helvetica", 8, Font.BOLD, Color.BLACK); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100f); PdfPCell h1 = new PdfPCell(new Paragraph("Header 1", font)); PdfPCell h2 = new PdfPCell(new Paragraph("Header 2", font)); table.setHeaderRows(1); table.addCell(h1); table.addCell(h2); PdfPCell cell; for (int row = 1; row <= 2000; row++) { if (row % fragmentsize == fragmentsize - 1) { document.add(table); table.deleteBodyRows(); table.setSkipFirstHeader(true); } cell = new PdfPCell(new Paragraph(String.valueOf(row), font)); table.addCell(cell); cell = new PdfPCell( new Paragraph("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla mauris nibh, ultricies nec, adipiscing eget.", font)); table.addCell(cell); } document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); 在单元格被添加到表格上后,我们可以通过扩展类PdfpCellEvent,重写其 中的cellLayout(PdfPCell cell, Rectangle postion, PdfContentByte[] canvases)方法, 对单元格做一些个性化的处理,比如在单元格上画一个斜线等。cellLayout方法 的参数解释如下: cell - 单元格自身 iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 position - 单元格对象所覆盖位置的Rectangle对象 canvases - 有下列几种值:PdfPTable.BASECANVAS(原始的 PdfContentByte,在这里写入的内容直接显示在表格层的下一层);PdfPTable.BACKGROUNDCANVAS(单元格的背景层);PdfPTable.LINECANVAS (线条所在的层);PdfPTable.TEXTCANVAS(文本内容所在的层,在这里写入 的内容将显示的表格层的上一层)。 举例如下: import java.io.FileOutputStream; import com.lowagie.text.Document; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPCellEvent; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; /** * General example using CellEvents. */ public class CellEvents implements PdfPCellEvent { /** * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell, * com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[]) */ public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfContentByte cb = canvases[PdfPTable.TEXTCANVAS]; cb.moveTo(position.getLeft(), position.getBottom()); cb.lineTo(position.getRight(), position.getTop()); cb.stroke(); } /** * General example using cell events. * * @param args iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 * no arguments needed */ public static void main(String[] args) { System.out.println("CellEvents"); // step1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("CellEvents.pdf")); // step3 document.open(); // step4 CellEvents event = new CellEvents(); Image im = Image.getInstance("otsoe.jpg"); im.setRotationDegrees(30); PdfPTable table = new PdfPTable(4); table.addCell("text 1"); PdfPCell cell = new PdfPCell(im, true); cell.setCellEvent(event); table.addCell(cell); table.addCell("text 3"); im.setRotationDegrees(0); table.addCell(im); table.setTotalWidth(300); PdfContentByte cb = writer.getDirectContent(); table.writeSelectedRows(0, -1, 50, 600, cb); table.setHeaderRows(3); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step5 document.close(); } } 运行结果如下: iText学习笔记之PdfPTable Email:cmliu2004@163.com QQ:27236220 如果想将类似的功能在表格上实现,会略微有点复杂,你需要实现 PdfPTableEvent接口中的tableLayout方法。
本文档为【iText学习笔记之PdfPTable】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_721103
暂无简介~
格式:doc
大小:430KB
软件:Word
页数:53
分类:
上传时间:2018-03-09
浏览量:107