npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

html-paged-pdf

v2.0.2

Published

纯前端 HTML 自动分页并生成 PDF。基于 paged.js + html2canvas + jsPDF,简化架构,更易使用。

Readme

html-paged-pdf v2.0.2

纯前端 HTML 自动分页并生成 PDF。基于 Paged.js + html2canvas + jsPDF,简化架构,更易使用。

核心改进 v2.0

  • 简化架构:移除复杂的自定义分页逻辑,直接采用 HTML 片段 → Paged.js 分页 → PDF 生成流程
  • 减少代码量:核心代码从 1000+ 行减少到约 300 行
  • 更易维护:清晰的模块划分,易于理解和扩展
  • 保持功能:完整保留分页、渲染、PDF 生成等核心功能

v2.0.2 更新

  • 修复<a> 标签内部包含 <span> 时 PDF 下划线丢失的问题
  • 优化:下划线与文字距离设置为 3px,细化下划线效果

安装

NPM 安装

npm install html-paged-pdf

CDN 使用

<script src="https://unpkg.com/[email protected]/dist/html2canvas.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/html-paged-pdf/dist/index.umd.js"></script>

快速开始

最简单的使用方式

import { htmlToPdf, htmlToPdfAndDownload } from 'html-paged-pdf';

// 方式1:生成 PDF 并自动下载
await htmlToPdfAndDownload(
  `
  <h1>文档标题</h1>
  <p>这是一段内容...</p>
`,
  {
    pdf: { filename: 'my-doc.pdf' }
  }
);

// 方式2:获取 PDF Blob,自行处理
const result = await htmlToPdf(`
  <h1>报告标题</h1>
  <p>报告内容...</p>
`);

console.log(`生成 ${result.pageCount} 页 PDF`);
// 上传到服务器或进行其他操作
const formData = new FormData();
formData.append('file', result.blob, 'report.pdf');
await fetch('/api/upload', { method: 'POST', body: formData });

完整配置示例

import { htmlToPdf } from 'html-paged-pdf';

const result = await htmlToPdf(
  `
  <h1>人工智能技术发展报告</h1>
  <h2>第一章:概述</h2>
  <p>人工智能(AI)是计算机科学的一个分支...</p>
  <img src="https://example.com/image.jpg" style="width:100%;max-width:400px;">
`,
  {
    page: {
      size: 'A4', // 页面尺寸: A4, A3, A5, Letter, Legal
      margin: '20mm', // 边距: 支持 '10mm' 或 { top: '10mm', right: '10mm', bottom: '10mm', left: '10mm' }
      orientation: 'portrait' // 方向: portrait(纵向) | landscape(横向)
    },
    headerFooter: {
      header: '人工智能技术发展报告', // 页眉内容
      footer: '© 2024 AI Research', // 页脚内容
      showPageNumber: true // 是否显示页码
    },
    pdf: {
      filename: 'report.pdf', // 文件名
      quality: 0.95, // 图片质量 0-1
      scale: 2 // 渲染缩放比例
    },
    onProgress: (info) => {
      // 进度回调
      console.log(`${info.stage}: ${info.progress}%`);
    }
  }
);

开发流程

1. 安装依赖

npm install

2. 开发模式

npm run dev

3. 构建

npm run build

构建输出位于 dist/ 目录:

  • index.esm.js - ES Module 格式
  • index.cjs - CommonJS 格式
  • index.umd.js - UMD 格式(浏览器直接使用)
  • index.d.ts - TypeScript 类型定义

4. 本地测试 Demo

npx serve demo

然后访问 http://localhost:3000/demo 查看效果。

5. 发布到 NPM

# 登录 NPM(首次需要)
npm login

# 发布版本 2.0.2(会自动执行 prepublishOnly 钩子进行构建)
npm publish

API 文档

核心函数

htmlToPdf(html, options?)

将 HTML 转换为 PDF,返回包含 Blob 和页数信息的结果。

const result = await htmlToPdf('<h1>Hello</h1>', {
  page: { size: 'A4', margin: '20mm' },
  pdf: { filename: 'doc.pdf' }
});

// result.blob - PDF Blob 对象
// result.pageCount - 总页数
// result.pageSize - 页面尺寸 { width, height }

htmlToPdfAndDownload(html, options?)

将 HTML 转换为 PDF 并自动触发下载。

await htmlToPdfAndDownload('<h1>文档</h1>', {
  pdf: { filename: 'document.pdf' }
});

htmlToPdfBlob(html, options?)

仅获取 PDF Blob,不触发下载。

const blob = await htmlToPdfBlob('<h1>内容</h1>');

htmlToPdfDataUrl(html, options?)

获取 PDF 的 Data URL,可用于新窗口打开。

const dataUrl = await htmlToPdfDataUrl('<h1>内容</h1>');
window.open(dataUrl);

batchHtmlToPdf(items, options?)

批量生成多个 PDF。

const results = await batchHtmlToPdf([
  { html: '<h1>Doc 1</h1>', filename: 'doc1.pdf' },
  { html: '<h1>Doc 2</h1>', filename: 'doc2.pdf' }
]);

配置选项

interface HtmlToPdfOptions {
  page?: {
    size?: 'A4' | 'A3' | 'A5' | 'Letter' | 'Legal'; // 默认: 'A4'
    margin?: string | { top?: string; right?: string; bottom?: string; left?: string }; // 默认: '10mm'
    orientation?: 'portrait' | 'landscape'; // 默认: 'portrait'
  };
  headerFooter?: {
    header?: string; // 页眉内容
    footer?: string; // 页脚内容
    showPageNumber?: boolean; // 是否显示页码
  };
  pdf?: {
    filename?: string; // 默认: 'document.pdf'
    quality?: number; // 默认: 0.95
    scale?: number; // 默认: 2
    printBackground?: boolean; // 默认: true
  };
  timeout?: number; // 默认: 30000 (毫秒)
  onProgress?: (info: ProgressInfo) => void; // 进度回调
  extraCss?: string; // 额外 CSS 样式
}

进度信息

interface ProgressInfo {
  stage: 'preparing' | 'paginating' | 'rendering' | 'generating';
  progress: number; // 0-100
  message?: string;
  currentPage?: number;
  totalPages?: number;
}

工具函数

import {
  formatMargin, // 格式化边距配置
  getPageDimensions, // 获取页面尺寸(毫米)
  mmToPx, // 毫米转像素
  pxToMm, // 像素转毫米
  downloadBlob // 下载 Blob 文件
} from 'html-paged-pdf';

// 示例
getPageDimensions('A4'); // { width: 210, height: 297 }
mmToPx(210, 96); // 794 (A4 宽度像素)

工作原理

HTML 片段 → Paged.js 分页 → html2canvas 渲染 → jsPDF 生成 → PDF 文件
  1. Paged.js 分页:在隐藏的 iframe 中加载 HTML,Paged.js 自动根据 @page 规则分页
  2. html2canvas 渲染:将分页后的每页内容渲染为 Canvas
  3. jsPDF 生成:将 Canvas 转换为图片并组合成 PDF

浏览器兼容性

  • Chrome 80+
  • Firefox 75+
  • Safari 13+
  • Edge 80+

许可证

MIT