使用 iTextpdf 绘制表格并生成 DPF 文件

本贴最后更新于 2101 天前,其中的信息可能已经时移世易

引用 iTextpdf

使用 maven 引用或下载 jar 包使用,jar 包在文末

<!-- 引用itextpdf支持 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> <!-- 引用itextpdf对中文的支持 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>

功能实现

// 自定义页面的宽高,如果需要标准文档大小不需要此步骤 Rectangle pageSize = new Rectangle(PageSize.A4.getWidth(),1000); // 创建一个Document对象并传入页面大小设置 // 需要标准文档大小可以使用PageSize.A4之类的文档大小 // 4个50分别是文档左右上下的内边距 Document document = new Document(pageSize,50,50,50,50); // 创建一个文档,传入文档地址即可 PdfWriter.getInstance(document, new FileOutputStream(outPath+"hallo.pdf")); // 打开文档 document.open(); // 如果需要使用中文需要传入中文的字体文字,这里传入的是微软雅黑粗体,注意后面的,1不能省略必须加上 BaseFont bfChinese = BaseFont.createFont("msyhbd.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 创建一种颜色以供字体使用 BaseColor titleFontColor = new BaseColor(255, 255, 255); // 设置文字大小和和样式 Font fontChinese = new Font(bfChinese, 8, Font.NORMAL,titleFontColor); // 创建一个table并指定列数 PdfPTable table = new PdfPTable(15); // 创建颜色标题背景使用 BaseColor titleBackgroundColor = new BaseColor(32, 200, 197); // 创建颜色标标题边框使用 BaseColor titleBorderColor = new BaseColor(167, 225, 224); // 创建单元格对象,单元格满列后自动换行 PdfPCell cell = new PdfPCell(new Paragraph("单位",fontChinese)); // 垂直对齐 cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 水平对齐 cell.setHorizontalAlignment(Element.ALIGN_CENTER); // 设置边框色 cell.setBorderColorRight(titleBorderColor); // 设置背景色 cell.setBackgroundColor(titleBackgroundColor); // 设置边框宽度 cell.setBorderWidth(1); // 设置单元格高度 cell.setFixedHeight(19); // 合并单元格,由于没有API可以提供居中,可以设置背景色一致的单元格实现伪居中效果 cell.setColspan(2); // 单元格添加到表格中 table.addCell(cell); // 表格添加到PDF文件中 document.add(table); // 关闭文档,生成PDF文档结束 document.close();

资料下载

itextpdf 下载
itext-asian 下载
微软雅黑粗体下载
iText 中文文档下载

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...