如何使用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 java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

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 AddingTableToPDF {
    public static void main(String args[]) throws Exception {
        String file = "addingTableToPDF.pdf";

        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("Maxsu"));
        table.addCell(new Cell().add("编号"));
        table.addCell(new Cell().add("10010"));
        table.addCell(new Cell().add("职位"));
        table.addCell(new Cell().add("Java Developer"));
        // 支持文中字体显示
        PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", false);
        table.setFont(font);

        // Adding Table to document
        doc.add(table);

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

}

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

Table created successfully..

输出文件内容如下所示 -


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