如何使用Java将嵌套表添加到PDF?

如何使用Java将嵌套表添加到PDF?

注:iText开发环境设置,下载iText7 jar(社区版:http://github.com/itext/itext7/releases/tag/7.0.4 ) ,创建一个工程:java_itext,并将下载的itext7 jar包和slf4j( http://www.slf4j.org/download.html )工具包添加到构建路径中。项目结构如下图所示 -

以下是使用Java将嵌套表添加到PDF的程序。

package com.zaixian;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;

import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;

public class AddNestedTablesPdf {
    public static void main(String args[]) throws Exception {
        String file = "addingNestedTableToPDF.pdf";

        // Creating a PdfDocument object
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));

        // Creating a Document object
        Document doc = new Document(pdfDoc);

        // Creating a table
        Table table = new Table(2);

        // Adding cells to the table
        table.addCell(new Cell().add("姓名"));
        table.addCell(new Cell().add("苏小牛"));
        table.addCell(new Cell().add("编号"));
        table.addCell(new Cell().add("1001"));
        table.addCell(new Cell().add("职位"));
        table.addCell(new Cell().add("Java开发工程师"));

        // Creating table for contact
        Table contact = new Table(2);

        // Adding table within a table
        contact.addCell(new Cell().add("电话"));
        contact.addCell(new Cell().add("Email"));
        contact.addCell(new Cell().add("地址"));
        contact.addCell(new Cell().add("13800138000"));
        contact.addCell(new Cell().add("xxxx@xuhuhu.com"));
        contact.addCell(new Cell().add("海南-海口"));

        // Adding table to the cell
        table.addCell(new Cell().add("详细联系方式"));
        table.addCell(new Cell().add(contact));
        // 中文支持
        PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", false);
        table.setFont(font);
        // Adding table to the document
        doc.add(table);

        // Closing the document
        doc.close();
        System.out.println("Nested Table Added successfully..");
    }
}

执行上面示例代码,得到以下结果 -

Nested Table Added successfully..

输出文件内容如下所示 -


上一篇: Java iText示例 下一篇:无