最近接触把html文件转换成pdf
三种实现方法
(1).用wkhtmlhopdf工具
(2).js前台去完成转换
(3).itext的方式
第一种方式比较完美 图片文字支持的比较好 ,而且也可以批量去生成,生成的pdf文字是可以copy的
第二种js的方式其实就是吧当前页面截图然后放到pdf文件中,只是个图片文字无法选中.
第三种itext的方式对文字支持的不太好,而且对css样式也不太友好(flying sauser 支持css)
第一种实现
1.安装wkhtmlhopdf
2.编写启动代码
demo
public static boolean convert(String srcPath, String destPath) {
File file = new File(destPath);
File parent = file.getParentFile();
// 如果pdf保存路径不存在,则创建路径
if (!parent.exists()) {
parent.mkdirs();
}
//c:\wkhtmltopdf.exe http://www.csdn.net c:\csdn.pdf"
StringBuilder cmd = new StringBuilder();
cmd.append(TOPDFTOOL);
cmd.append(" ");
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);
boolean result = true;
try {
Process proc = Runtime.getRuntime().exec(cmd.toString());
HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(
proc.getInputStream());
error.start();
output.start();
proc.waitFor();
System.out.println("HTML2PDF成功,参数---html路径:{},pdf保存路径 :{}"+new Object[] {srcPath, destPath });
} catch (Exception e) {
System.out.println(("HTML2PDF失败,srcPath地址:{},错误信息:{}"));
result = false;
}
return result;
}
/**
* @param args
*/
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("开始执行");
String htmlPath = "D:/诊断报告_files/1234.html";
String pdfPath = "D:/结果/"+System.currentTimeMillis()+".pdf";
// HtmlToPdf.convert(htmlPath, pdfPath );
long staTime = System.currentTimeMillis();
HtmlToPdf.convert(htmlPath, pdfPath );
long endTime = System.currentTimeMillis();
System.out.println( "用时" + (endTime-staTime));
}
}
创建一个线程
package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
class HtmlToPdfInterceptor extends Thread {
private InputStream is;
public HtmlToPdfInterceptor(InputStream is) {
this.is = is;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
第二种实现
前台点击按钮 保存到本地一个pdf
<button id="renderPdf">DOWNLOAD PDFbutton>
//点击button触发事件
//依赖于以下两个js
<script type="text/javascript" src="./js/html2canvas.js">script>
<script type="text/javascript" src="./js/jsPdf.debug.js">script>
<script type="text/javascript">
var downPdf = document.getElementById("renderPdf");
downPdf.onclick = function() {
html2canvas(document.body, {
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 555.28;
var imgHeight = 555.28/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf');
}
})
}
script>
第三种
package com;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreeMarkerTest1 {
public static void main(String[] args) throws Exception {
/* 创建配置 */
Configuration cfg = new Configuration();
/* 指定模板存放的路径*/
cfg.setDirectoryForTemplateLoading(new File("src/com"));
//cfg.setObjectWrapper(new DefaultObjectWrapper());
/* 从上面指定的模板目录中加载对应的模板文件*/
Template temp = cfg.getTemplate("test.ftl");
/* 创建数据模型 */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("name", "green mouse");
/* 将生成的内容写入hello .html中 */
String file1 = "src/com/静态诊断报告.html";
File file = new File(file1);
if (!file.exists())
file.createNewFile();
Writer out = new FileWriter(file);
// Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
String url = new File(file1).toURI().toURL().toString();
String outputFile = "src/com/my.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
//解决中文问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("src/com/SIMSUN.TTC", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
System.out.println("转换成功!");
os.close();
}
}
最后附上下载链接:https://download.csdn.net/download/ibudongit/10273731