友情提示:本文章只提供方法思路,不要复制粘贴后说跑不通
一、需要先安装NodeJs,网上教程很多
二、安装puppeteer依赖,如果npm下载不成功就使用cnpm命令(cnpm需要先安装)
npm install puppeteer --save
三、在安装puppeteer依赖的目录下创建puppeteer.js
const puppeteer = require('puppeteer');
const options = process.argv;
var address, types;
(async () => {
if(options.length>=4){
address=options[2];
types=options[3];
mobileWidth=Number(options[4]);
mobileHight=Number(options[5]);
}
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
timeout: 60000,
headless:true
})
try {
const page = await browser.newPage();
page.setViewport({width: mobileWidth, height: mobileHight});
await page.goto(address, {waitUntil: 'networkidle2'});
await page.waitForSelector('.nodeCompleted');
const pdf = await page.pdf({
width:mobileWidth,
height:mobileHight+1,
printBackground:true,
margin:{top:0,right:0,bottom:0,left:0},
scale:1
});
await browser.close();
process.stdout.write(pdf);
}catch(e){
}finally{
await browser.close();
}
})().then(function(res){
});
四、Java项目中创建PuppeteerHtmlToPdf.class
public class PuppeteerHtmlToPdf {
public static void parseHtml2Pdf(HttpServletResponse response, String fileName, String puppeteerjs, String webSiteUrl, String types, String mobileWidth, String mobileHight) {
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("node " + puppeteerjs + " " + webSiteUrl + " " + types + " " + mobileWidth + " " + mobileHight);
InputStream is = p.getInputStream();
BufferedInputStream bf = new BufferedInputStream(is);
byte[] data = IOUtils.toByteArray(bf);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
五、在你需要将网页转成pdf是去调用PuppeteerHtmlToPdf 的parseHtml2Pdf方法即可
六、注意:需要等页面加载完才去转pdf,需要在页面设置一个标志用于判断页面是否加载完成(这里前端使用的是vue的语法,页面加载完会把addNameFlags置为true,只有为true才设置class属性nodeCompleted,传统的可以在onload函数中给标签绑定class属性)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8426b4ee95293ae3aecd547afd35aba3.png#pic_center)