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

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

具体过程

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

复制代码
没有界面的浏览器

下载puppeteer

js 复制代码
npm i puppeteer

下载中可能会出现文件,中途不要暂停,这个不用管

启动无头浏览器

js 复制代码
  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页面

js 复制代码
 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格式

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

开始转化

js 复制代码
  await page.pdf(options);
    //关闭页面
    page.close();
    //关闭 chromium
    browser.close();

完整基础代码

直接放在index.js文件里

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('https://cloud.tencent.com/developer/article/1417076', 'a.pdf')  

然后启动node index.js

接着你会发现多了一个a.pdf文件

相关推荐
qyyyyy5702 天前
外文 PDF 怎么整理成 Markdown?从翻译、内容提取到 RAG 知识库导入
自然语言处理·pdf·erlang·机器翻译·零知识证明
赖龙2 天前
pnpm vs npm
前端·npm·node.js
AI导出鸭2 天前
Perplexity的LaTeX生成PDF文件复制后数学公式乱码,怎样修改?AI导出鸭苹果版的技术拆解与批量之道
人工智能·pdf·ai导出鸭
烂蜻蜓3 天前
Node.js入门教程(三十一):Express 框架
node.js·express
SpaceAIGlobal3 天前
AI PPT生成工具哪些支持PDF文档导入?
人工智能·ai·pdf·powerpoint·办公
小屁孩你滑稽掉了3 天前
prisma操作数据库的方法使用教程(简洁版)
数据库·node.js·prisma·fastify
Xxtaoaooo3 天前
极空间部署Stirling PDF:搭建自托管PDF工具箱并实现远程访问
pdf·cpolar·stirling pdf
__zRainy__3 天前
Node系列 · Node基础:https 模块
后端·网络协议·http·https·node.js
SamChan903 天前
对比 4 种主流 PDF 文档解析方案:PyMuPDF vs pdfplumber vs Apache PDFBox vs 大模型 OCR
python·ai·pdf·ocr·apache·机器翻译
__zRainy__3 天前
Node.js Web 框架选型指南:从 Express 到 Hono 的全景对比
前端·node.js·express·koa·nestjs·egg·fastify