js将PDF转为base64格式,并在将base64格式PDF回显在页面中
js将PDF转为base64格式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="file" onchange='handelChange(this)'> </body> </html> <script> function handelChange (e) { console.log(e.files) var file = new File(e.files,"r"); var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { // base64格式PDF console.log(reader.result); }; reader.onerror = function (error) { console.log('Error: ', error); }; } </script>
base64格式PDF回显在页面中
<template>
<div>
<div>pdf转为base64,并回显</div>
<pdf v-for="i in numPages" :key="i" :src="src" :page="i" ref="myPdfComponent"></pdf>
</div>
</template>
<script>
// data为后端给的base64格式的pdf
import { data } from "./tempData";
import pdf from 'vue-pdf'
// 解决部分文字不显示的问题
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'
export default {
data () {
return {
src: '',
numPages: 0,
page: 1,
currentPage: 0
};
},
components: {
pdf
},
methods: {
getUrl () {
return new Promise(resolve => {
let da = data.fileGongjiao
resolve(da)
})
},
},
mounted () {
// 获取到base64的pdf
this.getUrl()
.then((da) => {
let datas = 'data:application/pdf;base64,' + da
this.src = pdf.createLoadingTask({ url: datas, CMapReaderFactory });
this.src.promise.then(pdf => {
this.numPages = pdf.numPages;
});
})
}
}
</script>
******注:
*****base64为去掉开头格式的base64 ,如‘JVBERi0xLjMNJeLjz9MNCjcgMCBvICAgICAgICAgICAgICAgICAgDQoyMSAwIG9.........................................(此处省略)’,
*****不包含 'data:application/........................(此处省略)'
参考 https://blog.csdn.net/yuanmengdage/article/details/111871993

浙公网安备 33010602011771号