node.js运用Phantom.js爬取页面生成pdf


工具是webstorm,按照下图引进phantom模块,其他开发工具请自行百度其他方法引入。

注意:当后台放在Linux下,Linux需要安装有相应的字体,否则中文打印生成pdf

代码:

    function test(){
        var phantom = require('phantom');//需要引入phantom模块
        const path = require("path");//需要引入path模块
        var url = path.join(__dirname, '../../pdf');//可以通过path获取你向要生成pdf的路径,通过./返回当前目录的上级

        phantom.create().then(function (ph) {
            ph.createPage().then(function (page) {
                page.open("捕捉的页面").then(function (status) {      //status有success和fail
                    if (status === 'fail') {
                        console.log('open page fail!');
                    } else {
                        //进行pdf生成,加页面返回的status判断,确保页面正常打开.
                        // 给一个定时让要被捕捉的页面的html和js加载完成,否则可能页面会没有加载完就执行了生成pdf操作内容确实
                        setTimeout(function () {
                            page.property('viewportSize', {width: 500, height: 500});
                            page.render("生成的pdf路径").then(function () {
                                console.log('Page rendered');
                                page.close()
                                ph.exit();
                            });
                        }, 10000)
                    }
                })
            })
        })
}


猜你喜欢

转载自blog.csdn.net/qq_39229914/article/details/79724051