在electron下實現PDF線上預覽功能
由於公司業務的開發需要,需要實現在electron上實現PDF的線上預覽功能。electron 3.x版本後就不在支援PDF的預覽功能了,官方給的解釋是由於人手不夠將不再支援PDF預覽功能(也是醉了),在經過一番調研結合大佬們的經驗實現了PDF的在線上預覽功能
實現方式一、
-
將下好的檔案放入static檔案目錄下
-
在electron的主執行緒中通過渲染執行緒與主執行緒之間的通訊獲取viewer.html檔案位置
// 監聽獲取viewer.html檔案位置、 function getUrl(win) { const filePath = process.env.NODE_ENV === 'development' ? `${__static}\\pdfjs\\web\\viewer.html` : path.resolve(__dirname, '../../../static/pdfjs/web/viewer.html') win.webContents.send('recieve', filePath) } // pdf預覽獲取viewer.html檔案位置 ipcMain.on('getUrl', () => getUrl(win)) 複製程式碼
-
在pdf.vue中寫
<template> <iframe :src="base + '?file=' + url" :width="width" :height="height" class="iframe-placeholder"></iframe> </template> <script> import { ipcRenderer } from 'electron' // eslint-disable-line export default { props: { url: { type: String, default: '', }, width: { type: Number, default: 750 }, height: { type: Number, default: 600 }, }, data() { return { preview: false, base: '', } }, computed: { // 講義檔名 name() { const uri = decodeURI(this.url) const arr = uri.split('/') const len = arr.length return arr[len - 1] }, }, created() { // 獲取viewer.html的位置 ipcRenderer.send('getUrl') }, mounted() { ipcRenderer.on('recieve', (e, arg) => { console.log('檔案路徑', arg) this.base = arg }) } } </script> <style lang="scss" scoped> .wrapper { .info { width: 200px; } .iframe-placeholder { background: url('../../../assets/loading.svg') no-repeat 50% 50%; } } </style> 複製程式碼
-
在需要引入的地方引用即可
問題
樣式比較醜,但是可以實現PDF的分頁和列印的功能,且在打完包後文件比較大