Java如何在iText中设置单元格边框的宽度和颜色?

下面的示例向您展示如何设置单元格的边框宽度和颜色属性。我们可以使用setBorderWidth()和一次设置宽度和颜色setBorderColor()。或者,您可以为单元格边框的每一侧分别设置它。您也可以使用setBackgroundColor()方法设置单元格的背景色。

package org.nhooo.example.itextpdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class TableCellBorderDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableCellBorder.pdf"));
            doc.open();

            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));
            cell1.setUseBorderPadding(true);

            // 设置单元格的边框宽度和颜色
            cell1.setBorderWidth(5f);
            cell1.setBorderColor(BaseColor.BLUE);
            table.addCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
            cell2.setUseBorderPadding(true);

            // 设置单元格的背景色
            cell2.setBackgroundColor(BaseColor.GRAY);

            // 设置单元格的单个边框颜色
            cell2.setBorderWidthTop(1f);
            cell2.setBorderColorTop(BaseColor.RED);
            cell2.setBorderColorRight(BaseColor.GREEN);
            cell2.setBorderColorBottom(BaseColor.BLUE);
            cell2.setBorderColorLeft(BaseColor.BLACK);
            table.addCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));
            cell3.setUseBorderPadding(true);

            // 设置单元格的单个边框宽度
            cell3.setBorderWidthTop(2f);
            cell3.setBorderWidthRight(1f);
            cell3.setBorderWidthBottom(2f);
            cell3.setBorderWidthLeft(1f);
            table.addCell(cell3);
            table.completeRow();

            doc.add(table);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven依赖

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>