使用node将页面转为pdf?(puppeteer实现)

作者 : admin 本文共2011个字,预计阅读时间需要6分钟 发布时间: 2024-06-9 共3人阅读

本文章适合win系统下实验(linux,mac可能会出现些莫名其妙的bug我也不会解决)

具体过程

  • 首先了解什么时无头浏览器
  • 启动无头浏览器
  • 打开指定的url页面
  • 设置导出pdf格式
  • 开始转化
  • 完整基础代码

首先了解什么时无头浏览器

没有界面的浏览器

下载puppeteer

npm i puppeteer

下载中可能会出现文件,中途不要暂停,这个不用管
使用node将页面转为pdf?(puppeteer实现)插图

启动无头浏览器

  const browser = await puppeteer.launch({
        args: ['--no-sandbox', '--disable-setuid-sandbox', '--enable-accelerated-2d-canvas', '--enable-aggressive-domstorage-flushing'],
        ignoreHTTPSErrors: true,
        headless: true,
        timeout: 60000,
    });

打开指定的url页面

 const page = await browser.newPage();
    await page.setViewport({
        width: 640,
        height: 480,
        deviceScaleFactor: 1,
      });//将调整页面大小。许多网站不希望手机改变大小,因此你应该在导航到页面之前设置视口。
    let waitUntil;;
    waitUntil = 'networkidle0';
    await page.goto(url, { waitUntil });
waitUntil = 'networkidle0';
这个参数就是当网络在一定时间内不在请求时开始执行(进入一个网页肯定会加载相应的js,css文件)

设置导出pdf格式

 const options = {
        //纸张尺寸
        // format: 'A4',
        width: '800px',
        height: '1130px',
        //打印背景,默认为false
        printBackground: true,
        //不展示页眉
        displayHeaderFooter: true,
        //页眉与页脚样式,可在此处展示页码等
        headerTemplate: '',
        footerTemplate: '',
        path: filePath  //指定生成的pdf文件存放路径
    };

开始转化

  await page.pdf(options);
    //关闭页面
    page.close();
    //关闭 chromium
    browser.close();

完整基础代码

直接放在index.js文件里

const puppeteer = require('puppeteer');

async function generatePdf(url, filePath) {
    //启动无头浏览器
    const browser = await puppeteer.launch({
        args: ['--no-sandbox', '--disable-setuid-sandbox', '--enable-accelerated-2d-canvas', '--enable-aggressive-domstorage-flushing'],
        ignoreHTTPSErrors: true,
        headless: true,
        timeout: 60000,
    }); //PDF 生成仅在无界面模式支持, 调试完记得设为 true
    const page = await browser.newPage();
    await page.setViewport({
        width: 640,
        height: 480,
        deviceScaleFactor: 1,
      });//将调整页面大小。许多网站不希望手机改变大小,因此你应该在导航到页面之前设置视口。
    let waitUntil;;
    waitUntil = 'networkidle0';
    await page.goto(url, { waitUntil });
    await page.waitForSelector('.mod-article-content');//等到这个元素出现时开始转化

    //导出PDF的格式
    const options = {
        //纸张尺寸
        // format: 'A4',
        width: '800px',
        height: '1130px',
        //打印背景,默认为false
        printBackground: true,
        //不展示页眉
        displayHeaderFooter: true,
        //页眉与页脚样式,可在此处展示页码等
        headerTemplate: '',
        footerTemplate: '',
        path: filePath  //指定生成的pdf文件存放路径
    };
    await page.pdf(options);
    //关闭页面
    page.close();
    //关闭 chromium
    browser.close();
}
generatePdf('http://cloud.tencent.com/developer/article/1417076', 'a.pdf')  

然后启动node index.js
接着你会发现多了一个a.pdf文件

本站无任何商业行为
个人在线分享 » 使用node将页面转为pdf?(puppeteer实现)
E-->