如何使用 Java 格式化表格中单元格的内容
问题描述
如何使用 Java 格式化表格中单元格的内容。
解决方案
以下是使用 Java 格式化表格中单元格的内容的程序。
import com.itextpdf.kernel.color.Color;
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 {
//创建 PdfWriter 对象
String dest = "C:/itextExamples/addingBackground.pdf";
PdfWriter writer = new PdfWriter(dest);
//创建 PdfDocument 对象
PdfDocument pdfDoc = new PdfDocument(writer);
//创建 Document 对象
Document doc = new Document(pdfDoc);
//创建表格
float [] pointColumnWidths = {200F, 200F};
Table table = new Table(pointColumnWidths);
//填充第 1 行并将其添加到表格中
Cell c1 = new Cell(); //创建 cell1
c1.add("Name"); //将名称添加到 cell1
c1.setBackgroundColor(Color.DARK_GRAY); //设置背景颜色
c1.setBorder(Border.NO_BORDER); //设置边框
c1.setTextAlignment(TextAlignment.CENTER); //设置文本对齐方式
table.addCell(c1); //将单元格 1 添加到表格中
Cell c2 = new Cell();
c2.add("Raju");
c2.setBackgroundColor(Color.GRAY);
c2.setBorder(Border.NO_BORDER);
c2.setTextAlignment(TextAlignment.CENTER);
table.addCell(c2);
//填充第 2 行并将其添加到表格中
Cell c3 = new Cell();
c3.add("Id");
c3.setBackgroundColor(Color.WHITE);
c3.setBorder(Border.NO_BORDER);
c3.setTextAlignment(TextAlignment.CENTER);
table.addCell(c3);
Cell c4 = new Cell();
c4.add("001");
c4.setBackgroundColor(Color.WHITE);
c4.setBorder(Border.NO_BORDER);
c4.setTextAlignment(TextAlignment.CENTER);
table.addCell(c4);
//填充第 3 行并将其添加到表格中
Cell c5 = new Cell();
c5.add("Designation");
c5.setBackgroundColor(Color.DARK_GRAY);
c5.setBorder(Border.NO_BORDER);
c5.setTextAlignment(TextAlignment.CENTER);
table.addCell(c5);
Cell c6 = new Cell();
c6.add("Programmer");
c6.setBackgroundColor(Color.GRAY);
c6.setBorder(Border.NO_BORDER);
c6.setTextAlignment(TextAlignment.CENTER);
table.addCell(c6);
//将表格添加到文档
doc.add(table);
//关闭文档
doc.close();
System.out.println("Background added successfully..");
}
}
输出
java_itext.html

