maven包导入
<!-- 获取html并替换内容 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.6.3</version>
</dependency>
<!-- html转PDF -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.1.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.0.1</version>
</dependency>
String fileName = "PDF文件名";
//inline 设置为可在浏览器内打开,下载文件名称为fileName
response.setHeader("Content-Disposition", "inline;fileName=" + new String(fileName.getBytes(), "ISO8859-1") + ".pdf");
response.setContentType("application/pdf;charset=UTF-8");
//html文本地址
Sting url = "";
//根据html获取网络上的html对象
Document html = Jsoup.connect(url).get();
//替换html内容后将输出html文本
String htmlStr = html.html();
//导入字体
FontProvider font = new FontProvider();
font.addFont("/com/common/font/simsun.ttf");
ConverterProperties c = new ConverterProperties();
c.setFontProvider(font);
c.setCharset("utf-8");
PdfDocument pd = new PdfDocument(new PdfWriter(response.getOutputStream()));
//设置文件标题为fileName,web上展示的标题为此标题
pd.getDocumentInfo().setTitle(fileName);
Document document = new Document(pd, PageSize.A3);
try{
//设置页面边距 必须先设置边距,再添加内容,否则页边距无效
document.setMargins(20, 0, 20, 0);
List<IElement> list = HtmlConverter.convertToElements(htmlStr, c);
for (IElement ie : list) {
document.add((IBlockElement) ie);
}
}finally {
document.close();
}