我正在使用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));
console.log
load finished
fetched {}
vfs is {"GenShinGothic-Normal.ttf":{},"GenShinGothic-Bold.ttf":{}}
如果pdf生成...
Error: unknown font format
你能帮我吗?
====其他信息===== 字体文件(ttf)与bundle.js部署在同一目录中。