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

如何使用npm在客户端浏览器中压缩PDF文件?

客户端PDF压缩方案推荐

1. pdf-lib

这是纯前端PDF操作库,支持通过调整图片质量、移除冗余资源等方式压缩PDF。可直接加载本地PDF文件,修改内部资源后重新生成压缩文件,适配客户端场景。

简单实现示例:

import { PDFDocument } from 'pdf-lib';

async function compressPdf(file) {
  // 读取本地PDF文件
  const pdfBytes = await file.arrayBuffer();
  const pdfDoc = await PDFDocument.load(pdfBytes);
  
  // 遍历页面压缩内置图片
  const pages = pdfDoc.getPages();
  for (const page of pages) {
    const images = page.getImages();
    for (const image of images) {
      // 0-1区间调整图片质量,值越小压缩率越高
      await image.setQuality(0.5);
    }
  }
  
  // 生成压缩后的PDF字节数据并转为File对象
  const compressedPdfBytes = await pdfDoc.save();
  return new File([compressedPdfBytes], 'compressed.pdf', { type: 'application/pdf' });
}

2. jsPDF + html2canvas(HTML转PDF场景专属)

如果你的PDF是由HTML生成的,可通过html2canvas将HTML转为图片,再用jsPDF生成PDF时调整图片质量实现压缩。仅适用于HTML转PDF的场景,不支持处理已有PDF文件。

示例代码:

import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

async function compressHtmlToPdf(element) {
  // 降低缩放比例减少图片尺寸
  const canvas = await html2canvas(element, { scale: 0.8 });
  // 0-1区间调整JPEG质量
  const imgData = canvas.toDataURL('image/jpeg', 0.7);
  
  const pdf = new jsPDF('p', 'mm', 'a4');
  const imgWidth = 210;
  const pageHeight = 297;
  const imgHeight = (canvas.height * imgWidth) / canvas.width;
  let heightLeft = imgHeight;
  let position = 0;

  pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
  heightLeft -= pageHeight;

  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    pdf.addPage();
    pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;
  }
  
  // 转为File对象用于上传
  const pdfBlob = pdf.output('blob');
  return new File([pdfBlob], 'compressed.pdf', { type: 'application/pdf' });
}

3. PDF.js + 自定义压缩逻辑

PDF.js是Mozilla的PDF解析库,可用来解析PDF内容,重新生成PDF时手动优化资源。该方案需要更多自定义开发,适合对压缩粒度有高要求的场景。

注意事项

  • 前端PDF压缩效果依赖PDF内容:以图片为主的PDF压缩效果明显,纯文本为主的PDF压缩空间有限。
  • 部分库对复杂PDF(含表单、加密内容)支持有限,使用前需针对目标PDF类型做测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:29:58