生成pdf phantomjs

使用html">phantomjs生成还原度比较高的pdf文件,理论上生成word也可以,因需求没有做这块要求,功课留给大家去做了。

下载 https://html">phantomjs.org/download.html

根据需要选择对应版本下载使用

生成pdf phantomjs

使用总结

担心有人等不及看下面内容,先贴出来总结,在贴代码,最后贴介绍

邮件模板可以用ftl格式来做, 使用这个类来封装import freemarker.template.Template; ############liunx下安装步骤:################# 1,解压,配置引用,安装字体防止图片汉字乱码 tar -jxvf phantomjs-2.1.1-liunx-x86.tar.bz2 mv phantomjs-2.1.1-liunx-x86 /usr/local/src/phantomjs ln -sf /usr/local/src/phantomjs/bin/phantomjs /usr/local/bin/phantomjs yum install fontconfig freetype2 phantomjs -v #测试版本号 2,配置环境变量 vim /etc/profile export PATH=${PATH}:/usr/local/src/phantomjs/bin/ 记得刷新环境变量,生效 3,在liunx服务器的任意文件目录下输入命令: phantomjs, 正常输出,则配置成功,ctrl+c退出 ###############window下使用:################ 1, 解压zip包, 2,不是全局用的话,直接在bin目录搜索栏输入cmd打开即可, 不用配置环境变量 3,命令: 共四段,第一,二段不用改;第三段为自己的index.html文件路径,也即要生成pdf的html文件路径;第四段为输出文件路径 在bin目录下: phantomjs htmlToPdf.js "file:///D://temp//index.html" "D://temp/outpdf.pdf" 注: 路径file:/// 和全路径中要用"//"来加载而不是"\\" 用到的文件名: index.html ##html原页面 htmlToPdf.js ##将html转成pdf的关键js outpdf.pdf ##最终生成的pdf文件 #############echarts图片生成:################### 1, 生成的echarts图片需要放到pdf中,要分两步, 使用命令生成图片: phantomjs echarts-convert.js -infile echarts-options.js -outfile echarts-demo.png -scale 0.01 -width 800 用到的文件名: echarts-all.js echarts-options.js ##这个内容可以从echarts官网直接copy,实际在用的时候,可以自己生成该文件 jquery-3.2.1.min.js echarts-demo.png ##最终生成的图片 2,第一步先生成echart.png, 然后将图片路径放到index.html中,然后在去生成pdf 上目录

生成pdf phantomjs

上代码

Html2pdfUtil.java

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * 转换html为pdf */ public class Html2pdfUtil { public static String parseHtml2Pdf(String url) throws IOException { System.out.println(url); Runtime rt = Runtime.getRuntime(); Process p = rt.exec("/Users/a/Downloads/phantomjs2/bin/phantomjs /Users/a/Downloads/phantomjs2/bin/html2pdf.js "+url + " D://tmp//outpdf.pdf"); InputStream is = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer sbf = new StringBuffer(); String tmp = ""; while ((tmp = br.readLine()) != null) { sbf.append(tmp); } String resultstr = sbf.toString(); System.out.println("resultstr:"+resultstr); String[] arr = resultstr.split("\\$"); String result = ""; for(String s : arr){ if(s.endsWith("pdf"))result = s; } return result; } } public class Converter { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); String result = Html2pdfUtil.parseHtml2Pdf("https://www.baidu.com"); long all = System.currentTimeMillis()- start; System.out.println("pdf生成地址:"+result+",用时:"+all/1000+"秒"); } }

echarts-convert.js

(function() { var system = require('system'); var fs = require('fs'); var config = { // define the location of js files JQUERY : 'jquery-3.2.1.min.js', ECHARTS : 'echarts-all.js', // default container width and height DEFAULT_WIDTH : '800', DEFAULT_HEIGHT : '400' }, parseParams, render, pick, usage; usage = function() { console.log("\nUsage: phantomjs echarts-convert.js -options options -outfile filename -width width -height height" + "OR" + "Usage: phantomjs echarts-convert.js -infile URL -outfile filename -width width -height height\n"); }; pick = function() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i += 1) { arg = args[i]; if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') { return arg; } } }; parseParams = function() { var map = {}, i, key; if (system.args.length < 2) { usage(); phantom.exit(); } for (i = 0; i < system.args.length; i += 1) { if (system.args[i].charAt(0) === '-') { key = system.args[i].substr(1, i.length); if (key === 'infile') { // get string from file // force translate the key from infile to options. key = 'options'; try { map[key] = fs.read(system.args[i + 1]).replace(/^\s+/, ''); } catch (e) { console.log('Error: cannot find file, ' + system.args[i + 1]); phantom.exit(); } } else { map[key] = system.args[i + 1]; } } } return map; }; render = function(params) { var page = require('webpage').create(), createChart; page.onConsoleMessage = function(msg) { console.log(msg); }; page.onAlert = function(msg) { console.log(msg); }; createChart = function(inputOption, width, height) { var counter = 0; function decrementImgCounter() { counter -= 1; if (counter < 1) { console.log(messages.imagesLoaded); } } function loadScript(varStr, codeStr) { var script = $('<script>').attr('type', 'text/javascript'); script.html('var ' + varStr + ' = ' + codeStr); document.getElementsByTagName("head")[0].appendChild(script[0]); if (window[varStr] !== undefined) { console.log('Echarts.' + varStr + ' has been parsed'); } } function loadImages() { var images = $('image'), i, img; if (images.length > 0) { counter = images.length; for (i = 0; i < images.length; i += 1) { img = new Image(); img.onload = img.onerror = decrementImgCounter; img.src = images[i].getAttribute('href'); } } else { console.log('The images have been loaded'); } } // load opitons if (inputOption != 'undefined') { // parse the options loadScript('options', inputOption); // disable the animation options.animation = false; } // we render the image, so we need set background to white. $(document.body).css('backgroundColor', 'white'); var container = $("<div>").appendTo(document.body); container.attr('id', 'container'); container.css({ width : width, height : height }); // render the chart var myChart = echarts.init(container[0]); myChart.setOption(options); // load images loadImages(); }; // parse the params page.open("about:blank", function(status) { // inject the dependency js page.injectJs(config.JQUERY); page.injectJs(config.ECHARTS); var width = pick(params.width, config.DEFAULT_WIDTH); var height = pick(params.height, config.DEFAULT_HEIGHT); // create the chart page.evaluate(createChart, params.options, width, height); // define the clip-rectangle page.clipRect = { top : 0, left : 0, width : width, height : height }; // render the image page.render(params.outfile); console.log('render complete:' + params.outfile); // exit phantom.exit(); }); }; // get the args var params = parseParams(); // validate the params if (params.options === undefined || params.options.length === 0) { console.log("ERROR: No options or infile found."); usage(); phantom.exit(); } // set the default out file if (params.outfile === undefined) { var tmpDir = fs.workingDirectory + '/tmp'; // exists tmpDir and is it writable? if (!fs.exists(tmpDir)) { try { fs.makeDirectory(tmpDir); } catch (e) { console.log('ERROR: Cannot make tmp directory'); } } params.outfile = tmpDir + "http://www.likecs.com/" + new Date().getTime() + ".png"; } // render the image render(params); }());

echarts-options.js

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpyspy.html