html生成pdf
功能实现方式
引入itext依赖
<!--iText-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.13</version>
</dependency>
<!--linux解决字体问题-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
实现思路具体是
1 管理员在富文本中编辑具体的模版以及样式,用 %汉字% 来对后续补充的字段占位。
2 用户在对固定的合同内容进行赋值,
3 进行打印pdf
具体实现
1 首先,合同模版是以富文本的格式储存数据库中,我们要做的处理就是将其加上html标签,才能进行后续的转义pdf操作
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<style
type="text/css">html,
body{
font-family:simsun;
margin: 0;
border: 0;
padding: 0;
letter-spacing: 2px;
line-height: 2.5em;
}
</style><body>
" + content + "
</body></html>
2 拼接成html内容之后,就可以利用XMLWorkerHelper进行转pdf操作了,这里面有一点需要注意的就是html中所有的标签都需要闭合,如果出现单标签的情况,转义的时候会报错的。
3 转义pdf代码
Document document = new Document(PageSize.A4, 35, 35, 90, 90);
InputStream is = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
PdfWriter writer = null;
try {
String fileName = new String((templateName + ".pdf").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "inline;filename=" + fileName);
response.setContentType("application/pdf");
writer = PdfWriter.getInstance(document, response.getOutputStream());
//3 打开文档
document.open();
//4 html转为pdf
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(content.getBytes()), is, StandardCharsets.UTF_8, new FontProviderUtil());
} catch (DocumentException | IOException e) {
throw new RuntimeException("转pdf失败罗~");
} finally {
if (null != writer) {
writer.flush();
}
//5 关闭文档
document.close();
is.close();
writer.close();
}
4
如果需要添加页眉页脚这些信息的话,可以用到PDFBuilder类,具体使用方式
在上述代码打开文档操作前添加一下代码
PDFBuilder builder =new PDFBuilder();
writer.setPageEvent(builder);
添加pdfbuilder
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;
import lombok.SneakyThrows;
import java.io.IOException;
import static com.itextpdf.text.BaseColor.WHITE;
/**
* 设置页面附加属性
*/
public class PDFBuilder extends PdfPageEventHelper {
/**
* 页眉
*/
public String header = "这是页眉";
/**
* 水印
*/
public String watermark = “这里是水印";
/**
* 页脚
*/
public String footer = "这是页脚这是页脚这是页脚这是页脚这是页脚这是页脚这是页脚这是页脚";
/**
* logo
*/
public String imagePath = "logo地址";
/**
* 文档字体大小,页脚页眉最好和文本大小一致
*/
public int presentFontSize = 10;
/**
* 水印文字大小
*/
public int waterMarkFontSize = 50;
/**
* 文档页面大小,最好前面传入,否则默认为A4纸张
*/
public Rectangle pageSize = PageSize.A4;
/**
* 模板
*/
public PdfTemplate total;
/**
* 基础字体对象
*/
public BaseFont bf = null;
/**
* 利用基础字体生成的字体对象,一般用于生成中文文字
*/
public Font fontDetail = null;
/**
*
*/
public PDFBuilder() {}
/**
* 添加logo
*
* @param writer
* @param path
* @param fitWidth
* @param fitHeight
* @param absoluteX
* @param absoluteY
*/
public void setImg(PdfWriter writer, String path, float fitWidth, float fitHeight, float absoluteX, float absoluteY) {
try {
Image image = Image.getInstance(path);
image.setAlignment(Image.MIDDLE);
image.setBackgroundColor(WHITE);
image.scaleToFit(fitWidth, fitHeight);
image.setAbsolutePosition(absoluteX, absoluteY);
writer.getDirectContent().addImage(image);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* TODO 文档打开时创建模板
*/
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
// 共 页 的矩形的长宽高
total = writer.getDirectContent().createTemplate(50, 50);
}
//加分页
public void addPage(PdfWriter writer, Document document) {
try {
if (bf == null) {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
}
if (fontDetail == null) {
// 数据体字体
fontDetail = new Font(bf, presentFontSize, Font.NORMAL);
}
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
// 1.写入文字页眉
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase(header, fontDetail),
document.left() + 200, document.top() + 25, 0);
//写入商标logo
setImg(writer, imagePath, 100, 90, document.getPageSize().getLeft(50), 770);
//写入头部分割线
Phrase p1 = new Phrase();
p1.add(new Chunk(new LineSeparator()));
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, p1, document.left(), document.top() + 18, 0);
//写入页脚公司地址
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase(footer, fontDetail),
document.left(), document.bottom() - 50, 0);
// 2.写入前半部分的 第 X页/共
int pageS = writer.getPageNumber();
String foot1 = "第 " + pageS + " 页 /共";
Phrase footer = new Phrase(foot1, fontDetail);
// 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
float len = bf.getWidthPoint(foot1, presentFontSize);
// 4.拿到当前的PdfContentByte
PdfContentByte cb = writer.getDirectContent();
// 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
// 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了
// ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
ColumnText
.showTextAligned(
cb,
Element.ALIGN_CENTER,
footer,
document.right() - 30,
document.bottom() - 50, 0);
// 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
// len , y 轴和之前的保持一致,底边界-20
cb.addTemplate(total, document.right() - 8,
// 调节模版显示的位置
document.bottom() - 50);
}
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
// 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
total.beginText();
// 生成的模版的字体、颜色
total.setFontAndSize(bf, presentFontSize);
String foot2 = " " + (writer.getPageNumber()) + " 页";
// 模版显示的内容
total.showText(foot2);
total.endText();
total.closePath();
}
@SneakyThrows
@Override
public void onEndPage(PdfWriter writer, Document document) {
this.addPage(writer, document);
PdfContentByte contentUnder = writer.getDirectContentUnder();
//设置水印字体字号
contentUnder.setFontAndSize(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false), 50);
//设置透明度
PdfGState gState = new PdfGState();
//填充字体透明度 0.4
gState.setFillOpacity(0.4f);
//水印颜色
contentUnder.setColorFill(BaseColor.PINK);
//设置水印透明度
contentUnder.setGState(gState);
ColumnText.showTextAligned(
contentUnder,
Element.ALIGN_CENTER,
new Phrase(watermark, new Font(bf, waterMarkFontSize, Font.NORMAL)),
300,
400,
45);
}
}
5 再次打印