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

Vue项目中使用pdfjsLib加载PDF时字体加载报错问题

解决PDF.js加载PDF时的CMap字体报错问题

问题详情

加载PDF时出现以下字体加载警告:

Warning: Error during font loading: The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.

当前库加载代码:

let pdfjsLib = require('pdfjs-dist/build/pdf.js');
pdfjsLib.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry');

原PDF显示异常效果:
原PDF显示异常

解决方案

该问题是因为PDF.js处理包含CJK(中日韩)等非标准字体的PDF时,需要依赖CMap字符映射文件,必须显式配置cMapUrl和cMapPacked参数,具体步骤如下:

1. 安装CMap资源包

通过npm安装官方提供的CMap包:

npm install pdfjs-dist-cmaps

2. 修改代码添加CMap配置

在加载PDF的逻辑中传入CMap相关参数:

let pdfjsLib = require('pdfjs-dist/build/pdf.js');
pdfjsLib.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry');

// 配置CMap路径和压缩标识
const cMapUrl = 'node_modules/pdfjs-dist-cmaps/';
const cMapPacked = true;

// 加载PDF时传入配置
async function loadPDF(pdfUrl) {
  const loadingTask = pdfjsLib.getDocument({
    url: pdfUrl,
    cMapUrl,
    cMapPacked
  });
  const pdfDoc = await loadingTask.promise;
  // 执行后续页面渲染逻辑
}

3. 浏览器/CDN环境适配

如果是浏览器环境,可直接使用CDN托管的CMap资源:

const cMapUrl = 'https://cdn.jsdelivr.net/npm/pdfjs-dist-cmaps@latest/';
const cMapPacked = true;

4. Webpack打包配置(可选)

若使用Webpack打包,需确保CMap文件被复制到输出目录,可通过copy-webpack-plugin实现:

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  // ...其他Webpack配置
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'node_modules/pdfjs-dist-cmaps/',
          to: 'pdfjs-dist-cmaps/'
        }
      ]
    })
  ]
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:50:05