第一種方式:使用vue-pdf-embed和vue3-pdfjs
使用的插件有:
npm i vue-pdf-embed
npm i vue3-pdfjs
html部分:
<div ref="preRef" v-loading="loading" class="pdf-preview">
<div v-if="pdfState.source" class="pdf-wrap">
<VuePdfEmbed
v-for="item in pdfState.numPages"
:key="item"
:source="pdfState.source"
:style="pdfState.scale"
class="vue-pdf-embed"
:page="item"
/>
</div>
<van-empty v-if="loadError" image="error" description="PDF加載出錯了..." />
</div>
js部分:
// 引入兩個插件相關(guān)的
import VuePdfEmbed from 'vue-pdf-embed';
import { createLoadingTask } from 'vue3-pdfjs';
// 以上涉及的參數(shù)
const pdfState = reactive({
source: '', // 預(yù)覽pdf文件地址
pageNum: 1, // 當(dāng)前頁面
scale: 1, // 縮放比例
numPages: 0, // 總頁數(shù)
width: '400px', // 寬度
});
const preRef = ref();
const detail = ref({});//返回的數(shù)據(jù)
const loading = ref(true);
const loadError = ref(false);
// 方法
// 接口返回的數(shù)據(jù)
function getDetail() {
baseInfoGet({ id: route.currentRoute.value.query.id }).then((res) => {
detail.value = res.data;
const url = safeJSONParse(res.data.fileUrl)?.[0].url || '';
pdfState.source = url;
console.log('預(yù)覽地址:', url);
if (!url) return;
setTimeout(() => {
pdfState.width = getComputedStyle(preRef.value)?.width;
console.log(pdfState.width);
loadingPdf(url);
}, 0.5 * 1000);
});
}
// 加載pdf的方法
function loadingPdf(url) {
const loadingTask = createLoadingTask(url);
loadingTask.promise.then((pdf) => {
pdfState.numPages = pdf.numPages;
loading.value = false;
}).catch(() => {
loading.value = false;
loadError.value = true;
});
}
我一開始使用的時第一種方法,然后測試之后發(fā)現(xiàn)蘋果手機(jī)會顯示pdf加載出錯了,安卓手機(jī)可以正常顯示,于是換成了第二種方法。
第二種方式使用pdfjs-dist,蘋果手機(jī)加載失敗需使用版本2.2.228
npm i pdfjs-dist
html部分:
<div class="pdf-viewer">
<template v-for="item in pageNum" :key="item">
<canvas :id="`pdf-canvas-${item}`" class="pdf-page" />
</template>
<van-empty
v-if="loadError"
image="error"
description="PDF加載出錯了..."
/>
</div>
js部分:
// 引入插件相關(guān)的參數(shù)
import * as pdfjs from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
// html部分涉及的參數(shù)
const loadError = ref(false);
const detail = ref({});
let pdfDoc = null; // 一定不能使用響應(yīng)式的數(shù)據(jù),會報(bào)錯Cannot read from private field---pdf.js
const pageNum = ref(0);
// 處理接口返回的pdf的url
function getDetail() {
baseInfoGet({ id: route.currentRoute.value.query.id }).then((res) => {
detail.value = res.data;
const url = safeJSONParse(res.data.fileUrl)?.[0].url || '';
showLoadingToast({
message: '加載中...',
forbidClick: true,
});
console.log('預(yù)覽地址:', url);
if (!url) return;
loadingPdf(url);
});
}
//加載pdf
function loadingPdf(url) {
const loadingTask = pdfjs.getDocument(url);
loadingTask.promise
.then((pdf) => {
pdfDoc = pdf;
pageNum.value = pdf.numPages;
nextTick(() => {
renderPage();
});
})
.catch(() => {
closeToast();
loadError.value = true;
});
}
// 渲染pdf
function renderPage(num = 1) {
pdfDoc.getPage(num).then((page) => {
const canvas = document.getElementById(`pdf-canvas-${num}`);
const ctx = canvas.getContext('2d');
const scale = 1.5;
const viewport = page.getViewport({ scale });
// 畫布大小,默認(rèn)值是width:300px,height:150px
canvas.height = viewport.height;
canvas.width = viewport.width;
// 畫布的dom大小, 設(shè)置移動端,寬度設(shè)置鋪滿整個屏幕
const { clientWidth } = document.body;
// 減去2rem使用因?yàn)槲业捻撁孀笥壹恿藀adding
canvas.style.width = `calc(${clientWidth}px - 2rem)`;
// 根據(jù)pdf每頁的寬高比例設(shè)置canvas的高度
canvas.style.height = `${
clientWidth * (viewport.height / viewport.width)
}px`;
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({
canvasContext: ctx,
viewport,
});
if (num < pageNum.value) {
renderPage(num + 1);
} else {
closeToast();
}
});
}
用了第二種插件后,蘋果手機(jī)還是加載不出來,后面查到因?yàn)閜dfjs-dist有時候會出現(xiàn)部分手機(jī)比如iphone6和iphone8渲染不出pdf問題
解決辦法:
將pdfjs-dist版本改為2.2.228
npm i pdfjs-dist@2.2.228
然后就加載出來了,最后在各個環(huán)境測試的時候又發(fā)現(xiàn),微信小程序里面打開這個模塊,pdf還是沒加載出來,console之后發(fā)現(xiàn)請求401,報(bào)錯信息是登陸訪問超時,發(fā)現(xiàn)pdfjs加載pdf時沒有攜帶token
遂,在加載url時添加token即可文章來源:http://www.zghlxwxcb.cn/news/detail-788554.html
pdfjs加載pdf時攜帶token
//加載pdf
function loadingPdf(url) {
const afterUrl = {
url,
httpHeaders: {
token: `Bearer-${localStorage.getItem('token')}`,
},
};
const loadingTask = pdfjs.getDocument(afterUrl );
loadingTask.promise
.then((pdf) => {
pdfDoc = pdf;
pageNum.value = pdf.numPages;
nextTick(() => {
renderPage();
});
})
.catch(() => {
closeToast();
loadError.value = true;
});
}
添加之后就加載出來了文章來源地址http://www.zghlxwxcb.cn/news/detail-788554.html
到了這里,關(guān)于vue3移動端實(shí)現(xiàn)pdf預(yù)覽的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!