踩坑1: 渲染失敗
(1)在vue項目中,讀取本地的pdf文件需要放到public下static文件夾中,不能放在別的地方;
(2)引用時,不能使用相對路徑,因為使用public文件下面的資源,是不會被webpack處理的,它們會被直接復制到最終的打包目錄下面,且必須使用絕對路徑來引用這些文件。寫法:“/static/pdf/show.pdf",/即表示public文件夾(需略去public);
文檔:
https://www.npmjs.com/package/pdfh5
安裝:
npm install pdfh5 --legacy-peer-deps
npm install --save canvas --legacy-peer-deps
<script setup>
import { ref } from 'vue'
import Pdfh5 from 'pdfh5'
import 'pdfh5/css/pdfh5.css'// pdfh5實例
const pdfh5 = ref(null)// pdf預覽
const handlePreview = () => {pdfh5.value = new Pdfh5('#demo', {pdfurl: '/static/1.pdf', // 讀取本地的pdf文件需要放到public下static文件夾中})
}const beforeRead = (file) => {if (file.type == 'application/pdf') {// 使用類型化數組(Uint8Array)可以提高內存使用率。let reader = new FileReader()reader.readAsArrayBuffer(file)reader.onload = (loadEvent) => {let arrayBuffer = loadEvent.target.resultpdfh5.value = new Pdfh5('#demo', {data: arrayBuffer,})}}return true
}const afterRead = (file) => {// file.content是BASE64// PDF數據是BASE64編碼的,請先使用atob()將其轉換為二進制字符串// const data = atob(file.content.replace('data:application/pdf;base64,', '')) // 去除BASE64編碼的頭// pdfh5.value = new Pdfh5('#demo', {// data// })
}
</script><template><div class="home-page"><header class="header"><van-button type="default" @click="handlePreview" style="margin-right: 8px;">通過pdfurl預覽</van-button><van-uploader accept=".pdf" :before-read="beforeRead" :after-read="afterRead"><van-button icon="plus" type="primary">通過pdf文件流預覽</van-button></van-uploader></header><main class="main"><div id="demo"></div></main></div>
</template><style>
.home-page {width: 100%;height: 100%;.header {height: 50px;display: flex;align-items: center;}.main {height: calc(100% - 50px);}#demo {width: 100%;height: 100%;}
}
</style>