1、引入maven包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.12</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.6</version>
</dependency>
2、Controller写法:
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FlySaucerUtil {
/**
*将htmlCode转换为pdf文件
*
* @param htmlCode 其中body体必须包含字体样式设置,否则无法识别汉字。
* 字体样式设置举例:style='font-family:SimSun'
* @param pdfPath 实际存在的全路径pdf文件
*/
public static void htmlCodeToPdf(String htmlCode, String pdfPath) {
OutputStream os =null;
try {
os=new FileOutputStream(pdfPath);
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString(htmlCode);
renderer.layout();
renderer.createPDF(os);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}finally {
if(null!=os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3、字体乱码问题:
html字符串指定utf-8字体,指定body标签样式为SimSun。
SimSun是windows里的宋体,可将其文件放资源文件中引入。
<head>
<title>XXX合同</title>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Type" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
<style>
body{font-family:SimSun}
</style>
</head>