首页 > 解决方案 > 如何使用 vfs_fonts.js 减小 bundle.js 文件的大小?

问题描述

我正在使用 react/typescript 开发 pdf 下载功能。(使用 pdfmake)

我的 bundle.js 文件太大了。(超过 8MB)所以,我想减少这个。

主要原因是 bundle.js 包含 vfs_fonts.js。此文件大小超过 17MB。

我试过动态获取字体文件而不是捆绑文件,参考这个页面。

https://github.com/bpampuch/pdfmake/issues/1374

但它没有用。

这是我的代码的一部分

import * as pdfMake from 'pdfmake/build/pdfmake';

function fetchFont (fontURL: string) {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open('GET', fontURL, true);
    request.responseType = 'arraybuffer';

    request.onload = function (e: any) {
      resolve(request.response);
    };

    request.onerror = reject;

    request.send();
  });
}

interface Dictionary {
  [index: string]: string;
}

class PdfFontLoader {
  fontDefs: Dictionary[];
  vfs: {};
  loaded: boolean;
  constructor () {
    this.fontDefs = [];
    this.vfs = {};
  }
  addFont (fontDef: Dictionary) {
    this.fontDefs.push(fontDef);
  }

  load() {
    return new Promise((resolve, reject) => {
      if (this.loaded) {
        resolve();
      } else {
        const fetches = this.fontDefs.map(fontDef => {
          return fetchFont(fontDef.URL).then((data) => {
            console.log('fetched ' + JSON.stringify(data));
            this.vfs[fontDef.name] = data;
          }).catch(e => {
            console.log('error ' + e);
          });
        });
        Promise.all(fetches).then(() => {
          this.loaded = true;
          resolve();
        }).catch(reject);
      }
    });
  }
}

const pdf = pdfMake;

  pdf.vfs = fontLoader.vfs;
  fontLoader.addFont({URL: 'GenShinGothic-Normal.ttf', name: 'GenShinGothic-Normal.ttf'});
  fontLoader.addFont({URL: 'GenShinGothic-Bold.ttf', name: 'GenShinGothic-Bold.ttf'});

  fontLoader.load().then(res => {
    console.log('load finished');
    pdf.fonts = {
      GenShinGothic: {
        normal: 'GenShinGothic-Normal.ttf',
        bold: 'GenShinGothic-Bold.ttf'
      }
    };
    console.log("vfs is " + JSON.stringify(pdf.vfs));

控制台日志

load finished
fetched {}
vfs is {"GenShinGothic-Normal.ttf":{},"GenShinGothic-Bold.ttf":{}}

如果生成pdf...

Error: unknown font format

你能帮助我吗?

====附加信息=====字体文件(ttf)与bundle.js部署在同一目录中...

标签: reactjsfontspdfmake

解决方案


推荐阅读