itext應用HTML模版生成PDF並加水印,處理了中文問題
阿新 • • 發佈:2019-02-06
剛用itext實現了一個生成PDF加水印
其中遇到的問題是它對中文支援不好,專門寫了對中文的處理
先看效果圖:
maven包
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.1</version>
</dependency>
java程式碼
package com.helper.pdf;
import com.itextpdf.text.*;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.*;
import com.travelsky.helper.FileHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
public class PDFHelper {
public static void main(String[] args) throws Exception {
String templatePath="E:/workspace/pssMQ/msgCore/src/main/java/com/helper/temp.html";
String targetPath="E:/temp/購票證明3.pdf";
String watermarkPath="e:/temp/gongzhang.png";
createPdfWithMark(templatePath,targetPath,watermarkPath,400 ,400);
}
/**
* 建立PDF 帶水印
* @param htmlFile
* @param targetUrl
* @param markPicUrl
* @param xCoord
* @param yCoord
* @throws Exception
*/
public static void createPdfWithMark(String htmlFile,String targetUrl,String markPicUrl,int xCoord,int yCoord) throws Exception {
String tempPdf="e:/temp/"+Thread.currentThread().getId()+"temp.pdf";
createPdfByHtmlFile(htmlFile,tempPdf);
addPdfMark(tempPdf, targetUrl, markPicUrl, xCoord, yCoord, 1);
}
/**
* 建立PDF
* @param htmlFile
* @param targetUrl
* @return
* @throws Exception
*/
public static PdfWriter createPdfByHtmlFile(String htmlFile,String targetUrl) throws Exception {
String html = FileHelper.readFile(htmlFile);
return createPdfByHtml(html,targetUrl);
}
public static PdfWriter createPdfByHtml(String html,String targetUrl) throws Exception {
List<Element> parseToList = HTMLWorker.parseToList(new StringReader(html), null, new HashMap<String, Object>());
Document d = new Document(PageSize.A4);
PdfWriter writer=PdfWriter.getInstance(d, new FileOutputStream(new File(targetUrl)));
d.open();
for (Element e : parseToList) {
fixChineseCoding(e);
d.add(e);
}
System.out.println("已完成");
d.close();
return writer;
}
public static void addPdfMark(String InPdfFile, String outPdfFile, String markImagePath,int xCoord,int yCoord, int pageSize) throws Exception {
PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
Image img = Image.getInstance(markImagePath);// 插入水印
img.setAbsolutePosition(xCoord, yCoord);
for(int i = 1; i <= pageSize; i++) {
PdfContentByte under = stamp.getUnderContent(i);
under.addImage(img);
}
stamp.close();// 關閉
File tempfile = new File(InPdfFile);
if(tempfile.exists()) {
tempfile.delete();
}
}
private static BaseFont bfChinese;
private static Font cfont ;
/**
* 修正中文亂碼問題
* 現只支援table與p,div,span等
* @param e
* @return
* @throws IOException
* @throws DocumentException
*/
private static void fixChineseCoding(Element e) throws IOException, DocumentException {
if(bfChinese==null){
bfChinese = BaseFont.createFont("C:/Windows/Fonts/msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
if(e instanceof Paragraph){
for(Chunk c:e.getChunks()){//解決中文亂碼
cfont = new Font(bfChinese, 20, Font.NORMAL);
cfont.setColor(c.getFont().getColor());
cfont.setSize(c.getFont().getSize());
c.setFont(cfont);
}
return;
}
if(e instanceof PdfPTable){
PdfPTable table=(PdfPTable)e;
for(PdfPRow row:table.getRows()){
for(PdfPCell cell:row.getCells()){
if(cell!=null&&cell.getCompositeElements()!=null){
for(Element comp:cell.getCompositeElements()){
fixChineseCoding(comp);
}
}
}
}
}
}
}
html模版程式碼
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body style="text-align:center;">
<div style="text-align:center;width:80%;">
<p style="font-size:18;">遠東航空</p>
<p style="font-size:14;">Far Eastern Air Transport</p>
<p style="font-size:10;">購票證明單</p>
<p style="font-size:10;">TICKET RECEIPT</p>
</div>
<div style="text-align:right;">
<p style="font-size:10;">日期 年 月 日</p>
</div>
<span> </span>
<table border="1" align="left" style="width:80%;">
<tr><td>
<table border="0" style="font-size:10;">
<tr>
<td style="text-align:left;">搭機人:_NAME_ </td>
<td style="text-align:left;">機票號碼:_TICKET_NO_</td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td style="text-align:left;">機票款數:_NUM_</td>
<td style="text-align:left;"> 日期及班次:_TICKET_DATE_ </td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">航程 ROUTINGS : 自 FROM: 至 TO: 至 TO: </td>
</tr>
</table>
</td></tr>
</table>
</body>
</html>