You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cypress.IO调用Chrome API将页面转换为PDF?

在Cypress中调用Chrome DevTools API生成PDF页面

当然可以通过Cypress结合Chrome DevTools Protocol(CDP)的Page.printToPDF方法,将cy.visit()访问的页面导出为PDF文件。以下是具体实现步骤:

1. 安装依赖

首先需要安装chrome-remote-interface库,用于在Node环境中连接Chrome的DevTools接口:

npm install chrome-remote-interface --save-dev

2. 配置Cypress任务

在cypress.config.js中添加自定义任务,处理PDF生成逻辑:

const { defineConfig } = require('cypress');
const CDP = require('chrome-remote-interface');
const fs = require('fs');
const path = require('path');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        async printPdf({ options = {} }) {
          // 连接到当前Cypress控制的Chrome实例
          const client = await CDP();
          try {
            // 启用Page域
            await client.Page.enable();
            // 调用printToPDF方法,合并自定义配置
            const { data } = await client.Page.printToPDF({
              printBackground: true, // 打印背景色/图片
              format: 'A4', // 默认纸张尺寸
              ...options
            });
            // 确保输出目录存在
            const outputDir = path.join(__dirname, 'cypress/downloads');
            if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
            // 生成带时间戳的PDF文件名,避免重复
            const outputPath = path.join(outputDir, `${Date.now()}-page.pdf`);
            // 将base64格式的PDF数据写入文件
            fs.writeFileSync(outputPath, Buffer.from(data, 'base64'));
            return outputPath;
          } finally {
            // 关闭CDP连接
            await client.close();
          }
        }
      });
    },
    // 指定使用Chrome内核浏览器(仅支持Chromium系浏览器)
    browser: 'chrome'
  }
});

3. 编写测试用例

在测试文件中,先访问目标页面,再调用自定义任务生成PDF:

describe('导出页面为PDF', () => {
  it('将cy.visit的页面生成PDF', () => {
    cy.visit('https://example.com');
    
    // 自定义PDF配置(可选,按需调整)
    const pdfConfig = {
      landscape: false,
      displayHeaderFooter: true,
      headerTemplate: '<div style="font-size:8px; text-align:center;">页面页眉</div>',
      footerTemplate: '<div style="font-size:8px; text-align:center;">第<span class="pageNumber"></span>页,共<span class="totalPages"></span>页</div>'
    };

    // 调用任务生成PDF并验证
    cy.task('printPdf', { options: pdfConfig }).then(pdfPath => {
      cy.log(`PDF已保存至:${pdfPath}`);
      // 验证文件是否生成
      cy.readFile(pdfPath, 'base64').should('exist');
    });
  });
});

注意事项

  • 仅支持Chrome、Edge等Chromium内核浏览器,Firefox的DevTools Protocol不兼容此方法。
  • Cypress启动Chrome时默认开启调试模式,无需额外配置。
  • 可根据需求调整Page.printToPDF的参数,比如纸张尺寸、页眉页脚模板、是否隐藏背景等。

内容的提问来源于stack exchange,提问作者AMendis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:47:39