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

如何在Node.js中从HTML生成PDF?已用phantomjs,求替代方案

Node.js/JavaScript 环境下 HTML 转 PDF 的替代方案(替代 PhantomJS)

下面是几个成熟稳定的替代方案,覆盖不同场景需求:

1. Puppeteer

  • 基于Chrome/Chromium无头浏览器,Google官方维护,渲染稳定性和兼容性拉满
  • 完美支持现代HTML/CSS特性(Flexbox、Grid、CSS变量等),输出效果和真实浏览器一致
  • 基础使用示例:
const puppeteer = require('puppeteer');

async function generatePDF() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  // 可以直接传入HTML字符串,也可以加载远程URL
  await page.setContent('<h1>Hello PDF</h1><p>Generated via Puppeteer</p>');
  // 生成PDF,支持自定义尺寸、边距、页眉页脚等
  await page.pdf({ path: 'output.pdf', format: 'A4', printBackground: true });
  await browser.close();
}

generatePDF();
  • 适用场景:需要高精度渲染、依赖现代浏览器特性的业务场景

2. html-pdf(基于wkhtmltopdf)

  • 封装了开源工具wkhtmltopdf,依赖Qt WebKit引擎,资源占用比无头浏览器低
  • 不需要完整浏览器环境,适合资源有限的服务器部署
  • 基础使用示例:
const pdf = require('html-pdf');
const htmlContent = '<h1>Hello PDF</h1><p>Generated via html-pdf</p>';

// 配置项支持自定义尺寸、页眉页脚、分页等
pdf.create(htmlContent, { format: 'A4' }).toFile('output.pdf', (err, res) => {
  if (err) return console.error(err);
  console.log('PDF生成完成:', res.filename);
});
  • 注意:必须先在系统中安装wkhtmltopdf二进制文件,否则无法运行;对最新CSS特性的支持不如Puppeteer

3. jsPDF + html2canvas

  • 同时支持前端浏览器和Node.js环境,适合纯前端生成PDF的场景
  • 核心原理:先用html2canvas将HTML节点转为Canvas图片,再用jsPDF将图片插入PDF文档
  • 浏览器环境示例:
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

async function generatePDF() {
  const targetElement = document.getElementById('pdf-container');
  const canvas = await html2canvas(targetElement, { scale: 2 }); // 提高分辨率
  const imgData = canvas.toDataURL('image/png');

  const pdf = new jsPDF('portrait', 'mm', 'A4');
  const imgWidth = 210;
  const imgHeight = canvas.height * imgWidth / canvas.width;
  let remainingHeight = imgHeight;
  let yPosition = 0;

  // 第一页
  pdf.addImage(imgData, 'PNG', 0, yPosition, imgWidth, imgHeight);
  remainingHeight -= 297; // A4页面高度

  // 自动分页处理长内容
  while (remainingHeight >= 0) {
    yPosition = remainingHeight - imgHeight;
    pdf.addPage();
    pdf.addImage(imgData, 'PNG', 0, yPosition, imgWidth, imgHeight);
    remainingHeight -= 297;
  }

  pdf.save('output.pdf');
}
  • 局限性:生成的PDF本质是图片,文本无法选中复制;复杂分页需要手动处理

4. Playwright

  • 微软推出的跨浏览器自动化工具,支持Chrome、Firefox、WebKit三大引擎
  • API设计更简洁直观,支持多浏览器渲染对比,维护活跃度高
  • 基础使用示例:
const { chromium } = require('playwright');

async function generatePDF() {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.setContent('<h1>Hello PDF</h1><p>Generated via Playwright</p>');
  await page.pdf({ path: 'output.pdf', format: 'A4' });
  await browser.close();
}

generatePDF();
  • 优势:支持切换不同浏览器引擎生成PDF,适合需要验证多浏览器渲染效果的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:31:08