最近遇到了使用iText生成PDF的业务,最初的时候制定了两套方案:
1,直接使用iText动态生成pdf
2,使用iText搭配XML解析插件,直接解析html页面。
两个方法比较起来,还是第二个方法比较符合通用的设计规则,然而其弊端有两个:
1.被解析的html必须是严格xhtml语法,这样就限制了一定的通用性,必须专门为PDF开发一个显示页面。
2.由于使用XMLReader解析器进行解析,XMLReader对中文支持不好,很容易造乱码。
基于这两个不足,尤其是需要使用严格html进行开发,需要额外增加前端的工作量,最终放弃了这个方案。改为直接使用iText在后台生成PDF。以下是一些iText的不常见API:
1.PDF生成代码,这并不是一个不常见的api,把这段代码放在这里,是为了更明确下面代码片的位置,减少误会。
Document document = new Document();
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream("D://"+time+".pdf"));
document.open();
Paragraph reporttime = new Paragraph("生成报告时间 : "+DateUtil.getTime(), new Font(bfCN, 10, Font.NORMAL, fontColor));
document.add(reporttime);
document.close();
2.设置PDF背景颜色,这里可以直接使用RGB来确定颜色。
Rectangle rect = new Rectangle(PageSize.A4);
rect.setBackgroundColor(new BaseColor(242, 243, 243));
Document document = new Document(rect);
3.设置中文字体,其中font可以为不同的Paragraph 来定义字体。
BaseFont bfCN = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
Font report_title = new Font(bfCN, 10, Font.NORMAL, fontColor);
Paragraph maintenanceReport = null;
maintenanceReport = new Paragraph("× 发动机记录异常", report_title);
4.创建添加图片,并控制位置
Image image = Image.getInstance("D://logo.png");
image.scaleAbsolute(81,28);
document.add(image);
5.创建表格并添加内容
float[] widths = { 12f, 35f, 12f, 35f }; /*表格每行的宽度*/
PdfPTable basicTable = new PdfPTable(widths);
basicTable.setTotalWidth(TABLEWIDTH); /*设置总宽度*/
basicTable.setLockedWidth(true); /*设置总宽度固定*/
basicTable.setSpacingBefore(20f); /*设置与前一元素距离*/
basicTable.setSpacingAfter(10f); /*设置与后一元素距离*/
basicTable.setHorizontalAlignment(Element.ALIGN_RIGHT); /*设置文字对齐方式*/
PdfPCell cellh = null; // 表头cell
PdfPCell cellb = null; // 表格cell
cellh = new PdfPCell(new Paragraph("品牌", chFont));
basicTable.addCell(cellh);
cellb = new PdfPCell(new Paragraph("保时捷", chFont));
basicTable.addCell(cellb);
document.add(basicTable);
6.控制表格PDFCell
/**
* 添加表格内容
* @param cellb
* @param content
* @param chFont
* @return
*/
private static PdfPCell tableAddCellh(PdfPCell cellh,String content,Font chFont){
cellh = new PdfPCell(new Paragraph(content, chFont)); /*传入内容*/
cellh.setBorderColor(new BaseColor(231,234,236)); /*设置表格边框颜色*/
cellh.setBackgroundColor(new BaseColor(220, 223, 225)); /*设置表格背景颜色*/
cellh.setUseAscender(true); /*调节边距需要设置为true*/
cellh.setHorizontalAlignment(Element.ALIGN_CENTER); /*水平对齐*/
cellh.setVerticalAlignment(Element.ALIGN_MIDDLE); /*垂直对齐*/
cellh.setMinimumHeight(CELLHEIGHT); /*最小高度*/
cellh.setLeading(0.5f, 1.35f); /*行距*/
return cellh;
}
/*d调用方式*/
cellh=tableAddCellh(cellh, "品牌", chFont);
7.控制表格在一页显示
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream("D://"+time+".pdf"));
Paragraph maintenanceContent=new Paragraph();
float[] contentwidths = { 8f, 35f };
PdfPTable contentTable = new PdfPTable(contentwidths);
/*计算页面剩余空间,确认是否插入分页*/
if (writer.getVerticalPosition(true)-contentTable.calculateHeights() < document.bottom()) {
document.newPage();
}
附调整了一天多的PDF截图: