Java操作PDF文件

引入依赖

<!--ITextPdf,操作PDF文件的工具类-->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.4.2</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>

代码片段

File file = new File("test.pdf");
/** 实例化文档对象 */
Document document = new Document(PageSize.A4, 20, 20, 50, 50);
/** 创建 PdfWriter 对象 */
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
// 设置图片是否精确放置,选择是(true),否(false)
pdfWriter.setStrictImageSequence(true);
document.open();// 打开文档

/** pdf文档中中文字体的设置,注意一定要添加iTextAsian.jar包 */
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                        "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(bfChinese, 15, Font.BOLD);
 /** 向文档中添加内容,创建段落对象 */
Paragraph paragraph1 = new Paragraph("我是段落添加对象", font);
// 设置是否文件居中
paragraph1.setAlignment(Element.ALIGN_CENTER);
// 将Paragraph添加到Document对象中
document.add(paragraph1);

// 添加表格
PdfPTable pdfPTable = new PdfPTable(6); // 参数为表格列数numColumns
pdfPTable.setWidthPercentage(500 / 5.23f);// 设置表格宽度
PdfPCell cell;// 表格单元格对象
cell = new PdfPCell();
cell.setPaddingTop(15);// 顶部内边距
cell.setPaddingBottom(7);// 底部内边距
cell.disableBorderSide(Rectangle.BOX);// 隐藏边框
cell.setColspan(6);// 设置当前列所占表格总列数
Paragraph cellContent = new Paragraph("表格列内容", font4);
cellContent.setIndentationRight(30);// 设置内容右边距
cellContent.setAlignment(Element.ALIGN_RIGHT);
// paragraph 段落行间距
cellContent.setLeading(28.0f);
cell.addElement(cellContent);
pdfPTable.addCell(cell);

// 需求:当pdf文件中一个段落,存在字体样式多样风格时,可以使用Chunk(块)的概念来实现该需求
Font fontChunk = new Font(bfChinese, 15, Font.UNDERLINE);
Chunk chunk;// pdf块内容

cell = new PdfPCell();
cell.setFixedHeight(360);// 固定当前单元格高度
cell.disableBorderSide(Rectangle.BOTTOM);// 隐藏下边框
//cell.disableBorderSide(Rectangle.TOP + Rectangle.RIGHT);// 隐藏上、右边框
cell.setPaddingBottom(66);// 底部内边距
cell.setColspan(6);
cellContent = new Paragraph();
cellContent.setLeading(28.0f);
chunk = new Chunk("font1字体样式", font);
cellContent.add(chunk);

chunk = new Chunk(“fontChun字体样式”, fontChunk);
cellContent.add(chunk);
cellContent.setAlignment(Element.ALIGN_LEFT);
cell.addElement(cellContent);
pdfPTable.addCell(cell);

// 给pdf添加图片
cell = new PdfPCell();
cell.setBorderColor(BaseColor.GRAY);
cell.setPadding(10);
Image image = Image.getInstance(new URL("url"));//图片的地址
image.scaleToFit(400, 250);// 设置图片大小
cell.addElement(image);
pdfPTable.addCell(cell);

// 添加表格对象到document中
document.add(pdfPTable);
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值