vue-pdf无法显示中文的解决方案
vue-pdf是vue中展示pdf文件的常用插件,在pc端和移动端都有较好的显示效果。但如果载入的pdf中有中文,可能会显示不出来或者乱码,控制台中报错如下
Warning: Error during font loading: The CMap “baseUrl” parameter must be specified, ensure that the “cMapUrl” and “cMapPacked” API parameters are provided.
html如下:
<pdf :src="src"></pdf>
1.首先我们先获取到后端返回流,如
然后将返回的流数据转换为url
find(item) {
billExportPdf({
id: item.row.id,
})
.then((res) => {
this.src = this.getObjectURL(res);
})
.catch((res) => {
console.log(res);
});
},
// 将返回的流数据转换为url
getObjectURL(file) {
console.log(file);
let url = null;
if (window.createObjectURL != undefined) {
// basic
url = window.createObjectURL(file);
} else if (window.webkitURL != undefined) {
// webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {
console.log(error);
}
} else if (window.URL != undefined) {
// mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {
console.log(error);
}
}
return url;
},
然后发现并不是我们想要的效果,PDF并没有我们想要的数据
错误原因:
当PDF文件中有中文的情况下,在引用pdfjs过程中可能会出现中文不显示问题,在console中会报下面的错误,
解决方法
解决方案也比较简单,在项目中引入“CMapReaderFactory.js”,引入方式如下:
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
然后将流数据转换为url,CMapReaderFactory方法在进行处理
// 将返回的流数据转换为url
getObjectURL(file) {
console.log(file);
let url = null;
if (window.createObjectURL != undefined) {
// basic
url = window.createObjectURL(file);
} else if (window.webkitURL != undefined) {
// webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {
console.log(error);
}
} else if (window.URL != undefined) {
// mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {
console.log(error);
}
}
//这里是重点,然后将流数据转换为url,CMapReaderFactory方法在进行处理
url = pdf.createLoadingTask({
url: url, CMapReaderFactory });
return url;
},
接下来就得到了我们想要的数据,如图: