话不多说,直接上代码。
pd4ml有三个需要依赖的jar包,链接在这https://download.csdn.net/download/qq_33540034/11266791
导入jar包之后,上代码
1、将html文件内容转换成字符串的方法
/**
* 读取HTML内容的方法
*/
private final static String readFile(String path, String encoding) throws IOException {
File f = new File(path);
FileInputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
byte buffer[] = new byte[2048];
int read;
do {
read = is.read(buffer, 0, buffer.length);
if (read > 0) {
fos.write(buffer, 0, read);
}
} while (read > -1);
fos.close();
bis.close();
is.close();
return fos.toString(encoding);
}
2、HTML转换pdf的方法
private void html2pdf(String htmlStr, String outputPath) throws InvalidParameterException, IOException {
int topValue = 10;
int leftValue = 20;
int rightValue = 10;
int bottomValue = 10;
int userSpaceWidth = 1300;
PD4ML pd4ml = new PD4ML();
//设置默认字体为宋体
pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
pd4ml.setHtmlWidth(userSpaceWidth);
//设置pdf尺寸
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
//设置HTML全局样式
pd4ml.addStyle("BODY {margin: 0}", true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pd4ml.render(new StringReader(htmlStr), baos);
baos.close();
File output = new File(outputPath);
java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
fos.write(baos.toByteArray());
fos.close();
}
3、编写测试方法
public static void main(String[] args) {
try {
Test test = new Test();
//设置读取HTML的字符编码为utf8
String html = readFile("d:/asd.html", "UTF-8");
//设置生成的pdf存放位置及文件名
test.html2pdf(html, "d:/test.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
4、记录一下自己踩过的坑:
fonts.jar里面的字体很少,如果有自己的需求可以自己下载ttf字体,然后放在项目里让pd4ml的引用指向自己的字体文件,此时需要在html2pdf方法里的pd4ml.addStyle语句下方添加下面这个代码
//表示程序会从以下路径里去寻找字体文件
String path = request.getSession().getServletContext().getRealPath("");
pd4ml.useTTF(path+"/fonts", true);
在项目的webapp文件夹下新建一个fonts文件夹,把自己的.ttf字体文件复制进去,再把pd4ml.jar复制进去,再打开idea的命令行切换到fonts目录下,输入
java -jar pd4ml.jar -configure.fonts ../fonts ../fonts 执行完毕之后会在fonts目录中生成两个配置文件,重新部署项目就能识别自己设置的字体
此外:需要将fonts.jar移除才能使用自己的字体,不然还是默认的使用fonts.jar中的字体,另外在HTML文件中尽量使用英文,要将font-family:"宋体";写成font-family: "SimSun";才能被识别。可以在java中使用replace进行替换。
最终,因为种种问题,放弃了HTML转PDF,采用了返回流前台直接展示HTML的方案
欢迎大家加入京东淘宝捡垃圾群:698433653