解密pdf-4(pdf文件中的表格创建)

本文介绍如何使用iText库在Java中生成带有表格的PDF文件。通过设置表格的宽度、高度、背景颜色等属性来定制PDF表格样式,并展示了单元格合并及对齐方式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

既然用到了pdf
基本上就一定会用到表格
下面的例子就是一个使用itext进行表格的生成


package test.pdf;

import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
/**
* 创建表格
*
*/
public class Simple4 {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws DocumentException, IOException {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("E:/HelloWorld.pdf"));
doc.open();
//这里我们一一个2*5的表格为例
float[] widths = {120f, 220f};//设置表格的列宽
PdfPTable table = new PdfPTable(widths);//建立一个pdf表格
table.setSpacingBefore(130f);//设置表格上面空白宽度
table.setTotalWidth(342f);//设置表格的宽度
table.setLockedWidth(true);//设置表格的宽度固定

PdfPCell cell = new PdfPCell(new Paragraph("id"));//建立一个单元格

table.addCell(cell);//增加单元格
cell = new PdfPCell(new Paragraph("name"));

table.addCell(cell);
cell = new PdfPCell(new Paragraph("1"));
cell.setBackgroundColor(new Color(212,208,200));//设置单元格的背景颜色
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Joy"));
cell.setFixedHeight(30);//设置单元格的高度
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置单元格垂直对齐方式
table.addCell(cell);
cell = new PdfPCell(new Paragraph("2"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Join"));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("3"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Tom"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Num = 3"));
cell.setColspan(2);//设置合并单元格
cell.setBorder(0);//设置单元格无边框
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);//设置单元格中的文字水平对齐方式
table.addCell(cell);

doc.add(table);
doc.close();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值