scripts/html-to-pdf.ts

scripts/html-to-pdf.ts

基本信息

  • 类型: CLI 脚本 / PDF 转换器
  • 路径: ./scripts/html-to-pdf.ts

功能描述

使用 Puppeteer 将生成的 HTML 书籍文件转换为 PDF 格式。支持屏幕阅读版和印刷就绪版两种输出模式。

导出内容

  • 无(CLI 脚本,直接执行)

依赖导入

  • fs - 文件系统操作
  • path - 路径处理
  • puppeteer - 无头浏览器(动态导入)

前置要求

# 安装 Puppeteer(只需一次)
npm install puppeteer

使用方法

# 转换英文版本
npx tsx scripts/html-to-pdf.ts

# 转换指定语言
npx tsx scripts/html-to-pdf.ts tr

# 转换所有语言
npx tsx scripts/html-to-pdf.ts --all

# 印刷就绪模式
npx tsx scripts/html-to-pdf.ts --print

# 所有语言,印刷模式
npx tsx scripts/html-to-pdf.ts --all --print

工作流程

前置检查

  1. Puppeteer 是否安装
  2. 输出目录是否存在
  3. HTML 源文件是否存在

PDF 生成参数

屏幕版

参数
页面尺寸6in × 9in
边距上 0.55in, 左右 0.5in, 下 0.6in
页眉页脚显示页码

印刷版

参数
页面尺寸6.25in × 9.25in(含出血)
边距上 0.7in, 左右 0.65in, 下 0.75in
页眉页脚

CJK 支持

  • 使用 file:// 协议加载 HTML 文件
  • 中/日/韩内容自动检测
  • 页码生成失败时自动重试(无页眉页脚模式)

核心函数

convertToPdf()

转换单个 HTML 文件为 PDF:

  1. 启动 Puppeteer 浏览器
  2. 加载本地 HTML 文件
  3. 根据模式应用不同 PDF 选项
  4. 保存并输出文件大小

输出文件

  • public/book-pdf/book-{locale}.pdf
  • public/book-pdf/book-{locale}-print.pdf

错误处理

  • Puppeteer 未安装:提示安装命令
  • HTML 文件不存在:提示先运行 generate-book-pdf.ts
  • CJK 页码失败:自动降级为无页码模式
← 返回目录