vue3 pdf base64转成文件流打开
1、先下载依赖
“vue-pdf”: “^4.3.0”,
“canvas”: “^2.11.2”,
“pdfh5”: “^1.4.0”,
“pdfjs-dist”: “2.5.207”,
2、文件流转换
const getList = async () => {const res = await TH36({query_type: '2',start_date: data.start_date,end_date: data.end_date,})console.log(res)if (res.data.head.errorFlag != 0) {Toast(res.data.head.errorMsg)} else {// data.base64Url = 'data:image/png;base64,' + res.data.data.result.pdfdata.base64Url = 'data:application/pdf;base64,' + res.data.data.result.pdfviewPdf(res.data.data.result.pdf)}}// content是base64格式const viewPdf = (content) => {// console.log('content', content)const blob = base64ToBlob(content)// if (window.navigator && window.navigator.msSaveOrOpenBlob) {// console.log('1:', blob)// window.navigator.msSaveOrOpenBlob(blob)// } else {const fileURL = URL.createObjectURL(blob)console.log('2:', fileURL)// window.location.href = fileURL //打开ppf文件router.push({path: '/service/equityRecordFormDetail',query: {url: fileURL,},})// }}const base64ToBlob = (code) => {code = code.replace(/[\n\r]/g, '') // 检查base64字符串是否符合base64编码// atob() 方法用于解码使用 base-64 编码的字符串。const raw = window.atob(code)const rawLength = raw.lengthconst uInt8Array = new Uint8Array(rawLength)for (let i = 0; i < rawLength; ++i) {// 将解码后的逐个字符转换成Unicode序号,放入Unit8Array数组uInt8Array[i] = raw.charCodeAt(i)}// 通过Blob将Uint8Array数组转换成pdf类型的文件对象return new Blob([uInt8Array], { type: 'application/pdf' })}
3、打开pdf
<template><div id="app"><div id="demo"></div></div>
</template><script setup>import { reactive, toRefs, onMounted } from 'vue'import { useRoute } from 'vue-router'import Pdfh5 from 'pdfh5'import 'pdfh5/css/pdfh5.css'const route = useRoute()const id = route.query.idconst data = reactive({pdfh5: null,PDFsrc: route.query.url,})onMounted(() => {//实例化data.pdfh5 = new Pdfh5('#demo', {pdfurl: data.PDFsrc,})//监听完成事件data.pdfh5.on('complete', function (status, msg, time) {console.log('状态:' +status +',信息:' +msg +',耗时:' +time +'毫秒,总页数:' +data.totalNum)})})const { content } = toRefs(data)
</script><style lang="scss" scoped>* {padding: 0;margin: 0;}html,body,#app {width: 100%;height: 100%;}#demo {height: 100vh;overflow: hidden;overflow-y: scroll;}
</style>