1. 程式人生 > 其它 >前端技術實現檔案預覽(word、excel、pdf、ppt、mp4、圖片、文字)

前端技術實現檔案預覽(word、excel、pdf、ppt、mp4、圖片、文字)

前言

因為業務需要,很多檔案需要在前端實現預覽,今天就來了解一下吧。

 

實現方案

找了網上的實現方案,效果看起來不錯,放在下面的表格裡,裡面有一些是可以直接通過npm在vue中引入使用。

文件格式 老的開源元件 替代開源元件
word(docx) mammoth docx-preview(npm)
powerpoint(pptx) pptxjs pptxjs改造開發
excel(xlsx) sheetjs、handsontable exceljs(npm)、handsontable(npm)(npm)
pdf(pdf) pdfjs pdfjs(npm)
圖片 jquery.verySimpleImageViewer v-viewer(npm)

1、docx檔案實現前端預覽

  • 首先npm i docx-preview
  • 引入renderAsync方法
  • 將blob資料流傳入方法中,渲染word文件
 1 import { defaultOptions, renderAsync } from "docx-preview";
 2 renderAsync(buffer, document.getElementById("container"), null,
 3 options: {
 4        className: string = "docx", // 預設和文件樣式類的類名/字首
 5        inWrapper: boolean
= true, // 啟用圍繞文件內容渲染包裝器 6 ignoreWidth: boolean = false, // 禁止頁面渲染寬度 7 ignoreHeight: boolean = false, // 禁止頁面渲染高度 8 ignoreFonts: boolean = false, // 禁止字型渲染 9 breakPages: boolean = true, // 在分頁符上啟用分頁 10 ignoreLastRenderedPageBreak: boolean = true,//禁用lastRenderedPageBreak元素的分頁
11 experimental: boolean = false, //啟用實驗性功能(製表符停止計算) 12 trimXmlDeclaration: boolean = true, //如果為真,xml宣告將在解析之前從xml文件中刪除 13 debug: boolean = false, // 啟用額外的日誌記錄 14 } 15 );

實現效果:

 

 

 

2、pdf實現前端預覽

  • 首先npm i pdfjs-dist
  • 設定PDFJS.GlobalWorkerOptions.workerSrc的地址
  • 通過PDFJS.getDocument處理pdf資料,返回一個物件pdfDoc
  • 通過pdfDoc.getPage單獨獲取第1頁的資料
  • 建立一個dom元素,設定元素的畫布屬性
  • 通過page.render方法,將資料渲染到畫布上
 1 import * as PDFJS from "pdfjs-dist/legacy/build/pdf";
 2 // 設定pdf.worker.js檔案的引入地址
 3 PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/legacy/build/pdf.worker.entry.js");
 4 // data是一個ArrayBuffer格式,也是一個buffer流的資料
 5 PDFJS.getDocument(data).promise.then(pdfDoc=>{
 6     const numPages = pdfDoc.numPages; // pdf的總頁數
 7     // 獲取第1頁的資料
 8     pdfDoc.getPage(1).then(page =>{
 9      // 設定canvas相關的屬性
10      const canvas = document.getElementById("the_canvas");
11      const ctx = canvas.getContext("2d");
12      const dpr = window.devicePixelRatio || 1;
13      const bsr =
14        ctx.webkitBackingStorePixelRatio ||
15        ctx.mozBackingStorePixelRatio ||
16        ctx.msBackingStorePixelRatio ||
17        ctx.oBackingStorePixelRatio ||
18        ctx.backingStorePixelRatio ||
19        1;
20      const ratio = dpr / bsr;
21      const viewport = page.getViewport({ scale: 1 });
22      canvas.width = viewport.width * ratio;
23      canvas.height = viewport.height * ratio;
24      canvas.style.width = viewport.width + "px";
25      canvas.style.height = viewport.height + "px";
26      ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
27      const renderContext = {
28        canvasContext: ctx,
29        viewport: viewport,
30      };
31      // 資料渲染到canvas畫布上
32      page.render(renderContext);
33     })
34 })

實現效果

 

 

 

3、excel實現前端預覽

  • 下載exceljs、handsontable的庫
  • 通過exceljs讀取到檔案的資料
  • 通過workbook.getWorksheet方法獲取到每一個工作表的資料,將資料處理成一個二維陣列的資料
  • 引入@handsontable/vue的元件HotTable
  • 通過settings屬性,將一些配置引數和二維陣列資料傳入元件,渲染成excel樣式,實現預覽
 1 // 載入excel的資料
 2new ExcelJS.Workbook().xlsx.load(buffer)).then(workbook=>{
 3    // 獲取excel的第一頁的資料
 4    const ws = workbook.getWorksheet(1);
 5    // 獲取每一行的資料
 6    const data = ws.getRows(1, ws.actualRowCount);
 7  })
 8  
 9  
10 // 渲染頁面
11 import { HotTable } from "@handsontable/vue";
12 <hot-table  :settings="hotSettings"></hot-table>
13 hotSettings = {
14    language: "zh-CN",
15    readOnly: true,
16    data: this.data,
17    cell: this.cell,
18    mergeCells: this.merge,
19    colHeaders: true,
20    rowHeaders: true,
21    height: "calc(100vh - 107px)",
22    // contextMenu: true,
23    // manualRowMove: true,
24    // 關閉外部點選取消選中時間的行為
25    outsideClickDeselects: false,
26    // fillHandle: {
27    //   direction: 'vertical',
28    //   autoInsertRow: true
29    // },
30    // afterSelectionEnd: this.afterSelectionEnd,
31    // bindRowsWithHeaders: 'strict',
32    licenseKey: "non-commercial-and-evaluation"
33 }

實現效果:

 

 

 

 

 

4、pptx的前端預覽

主要是通過jszip庫,載入二進位制檔案,再經過一些列處理處理轉換實現預覽效果,實現起來比較麻煩,就不貼程式碼了,感興趣的可以下載程式碼檢視。

實現效果:

 

 

總結

主要介紹了word、excel、pdf檔案實現預覽的方式,前端實現預覽最好的效果還是PDF,不會出現一些文字錯亂和亂碼的問題,所以一般好的方案就是後端配合將不同格式的檔案轉換成pdf,再由前端實現預覽效果,將會保留檔案的一些樣式的效果,對於圖片、txt檔案的實現,感興趣的可以看下程式碼。

 

Demo地址:https://zhuye1993.github.io/file-view/dist/index.html

程式碼地址:https://github.com/zhuye1993/file-view

 

轉自:https://mp.weixin.qq.com/s/nyiThw5eU1SoUR7jbV6Tuw