2017-06-22 52 views
-3

我想利用iText生成像这样的表利用iText:表生成在给定的格式

enter image description here

当第一列数字1,2,3一样.....第二列具有属性名称,如名称,卷号等等,最后一列具有与每个属性相对应的实际数据。

+3

[为什么“有人可以帮我吗?”不是一个实际的问题?](http://meta.stackoverflow.com/q/284236) – EJoshuaS

+1

你到目前为止尝试过什么? – scsere

+0

您是否阅读过文档? http://developers.itextpdf.com/content/itext-7-building-blocks/chapter-5-adding-abstractelement-objects-part-2 –

回答

1

由于您是iText的新手,您应该使用最新版本的iText。这是iText的7.0.3:https://github.com/itext/itext7/releases

你想创建一个表,看起来像这样: enter image description here

这表是使用下面的代码创建:

public static void main(String[] args) throws IOException { 
    PdfDocument pdf = new PdfDocument(new PdfWriter("table.pdf")); 
    Document document = new Document(pdf); 
    Table table = new Table(new float[]{1, 4, 4}); 
    table.setWidthPercent(50); 
    table 
     .addHeaderCell(
       new Cell().add("A") 
        .setTextAlignment(TextAlignment.CENTER)) 
     .addHeaderCell(
       new Cell().add("B") 
        .setTextAlignment(TextAlignment.CENTER)) 
     .addHeaderCell(
       new Cell().add("C") 
        .setTextAlignment(TextAlignment.CENTER)); 
    for (int i = 1; i < 11; i++) { 
     table 
      .addCell(
        new Cell().add(String.format("%s.", i)) 
        .setTextAlignment(TextAlignment.RIGHT) 
        .setBorderTop(Border.NO_BORDER) 
        .setBorderBottom(Border.NO_BORDER)) 
      .addCell(
        new Cell().add(String.format("key %s", i)) 
        .setBorderTop(Border.NO_BORDER) 
        .setBorderBottom(Border.NO_BORDER)) 
      .addCell(
        new Cell().add(String.format("value %s", i)) 
        .setBorderTop(Border.NO_BORDER) 
        .setBorderBottom(Border.NO_BORDER)); 
    } 
    table 
     .addFooterCell(
      new Cell().add("A") 
       .setTextAlignment(TextAlignment.CENTER)) 
     .addFooterCell(
      new Cell().add("B") 
       .setTextAlignment(TextAlignment.CENTER)) 
     .addFooterCell(
      new Cell().add("C") 
       .setTextAlignment(TextAlignment.CENTER)); 
    document.add(table); 
    document.close(); 
} 

pdf对象是低将PDF语法写入PdfWriter的级别PDF文档。我们使用pdf对象创建一个名为documentDocument实例。这是我们可以添加各种构建块的高级文档,如Paragraph,Image,List和其他高级对象。

就你而言,我们想添加一个表格,因此我们创建了一个Table实例。我们通过一个float阵列三个元素,因为我们需要三列。第一列的宽度是第二列和第三列宽度的1/4。我们希望表格在页面上占用50%的可用宽度。

现在我们要添加单元格。您可以添加三种类型的细胞:

  • 头细胞:使用addHeaderCell()方法,
  • 体细胞:使用addCell()方法,并
  • 脚注单元:使用addFooterCell()方法。

如果一个表格不适合页面,它将分布在不同的页面上,页眉和页脚单元格将被重复。

传递给这些方法之一的参数是Cell。我们可以改变每个单元格的对齐方式,边界等等。有关可用属性的更多信息,请阅读tutorialAPI documentation