Nodejs 中将html转换成pdf文件,Nodejs Convert html into pdf

1. 下载phantomjs.exe,将该文件放在根目录

2. 编写pdf.js文件(在github上下载phantomjs相关的测试文件,仿照rasterize.js文件编写pdf.js文件)

3. Nodejs调用phantomjs,将html页面转换成pdf文件

// 改变存放html和pdf的路径

app.get('/pdf5',function(request,response){

   var http = require('http');

   var sys = require('sys');

   var exec = require('child_process').exec;

   var util = require('util');

   var fs = require('fs');

   var innertTextForBody="<table style=' border: 1px dotted  green;'><tr><td>Name</td><td>Age</td><td>Agent</td><td>Address</td><td>FootMark</td></tr></table>";

   var dummyContent = '<!doctype  html><html><head><title>Test</title><meta  charset="utf-8"></head><body><p  style="border: 1px dotted #adff2f">Hello everyone,Node you can inspire weg page go forward!</p>'+innertTextForBody+'</body></html>';

   var date=new Date();

   var  fileName=date.getYear().toString()+date.getMonth().toString()+date.getDay().toString()+date.getHours().toString()+date.getMinutes().toString()+date.getSeconds().toString();

   console.log(fileName);

   // var htmlFileName ="wwwroot/public/ConverPdf/page.html",  pdfFileName ="wwwroot/public/ConverPdf/page.pdf";

   var htmlFileName  ="wwwroot/public/ConverPdf/"+fileName+".html",  pdfFileName ="wwwroot/public/ConverPdf/"+fileName+".pdf";

   // Save to HTML file(this html url you can specify web page)

   fs.writeFile(htmlFileName, dummyContent, function(err) {

    if(err) { throw err; }

    util.log("temporatry html file have  generator");

   });

   // var child = exec("phantomjs.exe"+"  "+"pdf.js"+" "+ htmlFileName + " " +  pdfFileName, function(err, stdout, stderr) {

   var child = exec("phantomjs.exe"+"  "+"pdf.js"+" "+ htmlFileName + " " +  pdfFileName, function(err, stdout, stderr) {

    if(err) { throw err; }

    else

    {

      console.log('pdf file saved to');

      util.log(stderr);

      fs.unlink(htmlFileName,function(err){

        if (err) throw err;

        console.log('successfully deleted  '+htmlFileName);

      });

    }

   });

   response.writeHead(200, {'Content-Type' : 'text/html'});

   response.end('Rendered to ' + htmlFileName + ' and ' + pdfFileName +  '\n');

});

转载于:https://www.cnblogs.com/guide2it/p/3503615.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐