如何使用Java為PDF中的表設定背景?

2019-10-16 22:25:01

如何使用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.yiibai;

import com.itextpdf.kernel.color.Color;
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.border.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;

public class BackgroundToTable {
    public static void main(String args[]) throws Exception {
        String file = "backgroundToTable.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 row 1 to the table
        Cell c1 = new Cell();

        c1.add("姓名");
        c1.setBackgroundColor(Color.PINK);
        c1.setBorder(Border.NO_BORDER);
        c1.setTextAlignment(TextAlignment.CENTER);
        table.addCell(c1);

        Cell c2 = new Cell();
        c2.add("蘇小牛");
        c2.setBackgroundColor(Color.GRAY);
        c2.setBorder(Border.NO_BORDER);
        c2.setTextAlignment(TextAlignment.CENTER);
        table.addCell(c2);

        // Adding row 2 to the table
        Cell c3 = new Cell();

        c3.add("編號");
        c3.setBackgroundColor(Color.WHITE);
        c3.setBorder(Border.NO_BORDER);
        c3.setTextAlignment(TextAlignment.CENTER);
        table.addCell(c3);

        Cell c4 = new Cell();
        c4.add("1001");
        c4.setBackgroundColor(Color.WHITE);
        c4.setBorder(Border.NO_BORDER);
        c4.setTextAlignment(TextAlignment.CENTER);
        table.addCell(c4);

        // Adding row 3 to the table
        Cell c5 = new Cell();

        c5.add("職位");
        c5.setBackgroundColor(Color.ORANGE);
        c5.setBorder(Border.NO_BORDER);
        c5.setTextAlignment(TextAlignment.CENTER);
        table.addCell(c5);

        Cell c6 = new Cell();
        c6.add("Java開發工程師");
        c6.setBackgroundColor(Color.CYAN);
        c6.setBorder(Border.NO_BORDER);
        c6.setTextAlignment(TextAlignment.CENTER);
        table.addCell(c6);

        // 支援文中字型顯示
        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("Background added successfully..");
    }
}

執行上面範例程式碼,得到以下結果 -

Background added successfully..

輸出檔案內容如下所示 -