Nodejs 中将html转换成pdf文件

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');



});

你可能感兴趣的:(nodejs)