用到的依赖:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.0.3</version>
</dependency>
<!--工具类-->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
核心代码:
package org.com.util;
import com.itextpdf.text.pdf.BaseFont;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.OutputStream;
public class FileTypeConvertUtil {
/**
* 将HTML转成PD格式的文件。html文件的格式比较严格
* @param htmlText html内容
* @param os pdf存储文件输出流 os = new FileOutputStream(new File("路径"))
* @throws Exception
*/
public static void html2pdf(String htmlText, OutputStream os) throws Exception {
Document document = Jsoup.parse(htmlText);
/*手动为一些标签添加闭合,这一步至关重要*/
Elements meta = document.getElementsByTag("meta");
String html = document.html();
for (Element link : meta) {
String s = link.outerHtml();
String s1 = s.replace("/>", ">");
html = html.replace(s, s1 + "</meta>");
}
Elements link1 = document.getElementsByTag("link");
for (Element link : link1) {
String s = link.outerHtml();
String s1 = s.replace("/>", ">");
html = html.replace(s, s1 + "</link>");
}
html = html.replaceAll("<br>", "<br/>");
html = html.replaceAll(" ", " ");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
// step 3 解决中文支持
ITextFontResolver fontResolver = renderer.getFontResolver();
if(getCurrentOperatingSystem().contains("linux")){
fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}else{
fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
renderer.layout();
renderer.createPDF(os);
os.close();
}
/**
* 当前的操作系统
*/
public static String getCurrentOperatingSystem(){
String os = System.getProperty("os.name").toLowerCase();
return os;
}
}
注意事项:
通过itext这种古老的方法转换,受限的条件颇多,其中一条严格的规定就是:标签必须闭合,例如:
会报错,而则可以正常转换。
如果不能识别中文字体,那么检查是否已经安装了相对应的字体,路径字体详见代码。
(本文完!希望对大家有帮助,转载需附本文链接!)