注意
使用的是pdf.js 版本为 v2.16.105。因为新版本 兼容性不太好,部分手机预览不了,所以采用v2版本。
相关依赖
"canvas": "^2.11.2",
"pdfjs-dist": "^2.16.105",
"core-js-pure": "^3.37.1",
"hammerjs": "^2.0.8", //这个是写手势 双指缩放的 不需要可以去掉
解决部分浏览器或者手机系统的兼容问题
//解决 structuredClone
// https://developer.mozilla.org/en-US/docs/Web/API/structuredClone#browser_compatibility
// https://gitcode.com/zloirock/core-js/overview?utm_source=csdn_github_accelerator
import structuredClone from 'core-js-pure/actual/structured-clone';
// 解决 TypeError: key.split(...).at is not a function
// https://github.com/wojtekmaj/react-pdf/issues/1465
import 'core-js/features/array/at';
window.structuredClone = structuredClone;
代码
以下为在uniapp vue3 实现 h5 预览pdf文件的代码 有使用vant(手指缩放功能只写了一点,是不能用的)。
<template>
<div id="pdf-view" ref="pdfView">
<!-- <canvas v-for="page in state.pdfPages" :key="page" id="pdfCanvas" />-->
<div ref="pdfViewContainer">
<div
v-for="pageNumber in state.pdfPages"
v-show="state.pdfPageList.includes(pageNumber)"
:key="pageNumber"
:ref="(el) => (pageRefs[pageNumber - 1] = el)"
></div>
</div>
<je-loading v-show="loading" />
</div>
</template>
<script setup>
//解决 structuredClone
// https://developer.mozilla.org/en-US/docs/Web/API/structuredClone#browser_compatibility
// https://gitcode.com/zloirock/core-js/overview?utm_source=csdn_github_accelerator
import structuredClone from 'core-js-pure/actual/structured-clone';
// 解决 TypeError: key.split(...).at is not a function
// https://github.com/wojtekmaj/react-pdf/issues/1465
import 'core-js/features/array/at';
import * as pdfjsWorker from 'pdfjs-dist/lib/pdf.worker.js';
// 解决 pdfjsWorker 未定义
window.pdfjsWorker = pdfjsWorker;
window.structuredClone = structuredClone;
// if (!Array.prototype.at) {
// Array.prototype.at = function (index) {
// if (index < 0) {
// index = this.length + index;
// }
// if (index >= 0 && index < this.length) {
// return this[index];
// }
// return undefined;
// };
// }
import Hammer from 'hammerjs';
import * as pdfjsWorker from 'pdfjs-dist/lib/pdf.worker.js';
// 解决 pdfjsWorker 未定义
window.pdfjsWorker = pdfjsWorker;
import 'pdfjs-dist/web/pdf_viewer.css';
import * as PDF from 'pdfjs-dist';
// import * as PDF from 'pdfjs-dist/build/pdf.js';
import {
useRoute } from 'vue-router';
import {
ref, reactive, onMounted, nextTick, defineProps } from 'vue';
import {
showFailToast } from 'vant';
const route = useRoute();
const props = defineProps({
src: {
type: String,
default: '',
},
});
const pdfViewContainer = ref(null);
const pdfView = ref(null);
const pageRefs = ref([]