Front-end technology realizes file preview (word, excel, pdf, ppt, mp4, picture, text)

foreword

Due to business needs, many files need to be previewed on the front end. Let's learn about them today.

Demo site [1]: zhuye1993.github.io/file-view/d…

Implementation plan

I found an online implementation solution, the effect looks good, put it in the table below, some of which can be directly introduced and used in vue through npm.

document format old open source components Alternative to open source components
word(docx) mammoth docx-preview (npm)
powerpoint(pptx) pptxjs pptxjs transformation development
excel(xlsx) sheetjs、handsontable exceljs (npm) 、 handsontable (npm) (npm)
pdf (pdf) pdfjs pdfjs (npm)
picture jquery.verySimpleImageViewer v-viewer (npm)

docx file to achieve front-end preview

Code

  • First npm i docx-preview
  • Introduce the renderAsync method
  • Pass the blob data stream into the method to render the word document
import { defaultOptions, renderAsync } from "docx-preview";
renderAsync(buffer, document.getElementById("container"), null,
options: {
       className: string = "docx", // 默认和文档样式类的类名/前缀
       inWrapper: boolean = true, // 启用围绕文档内容渲染包装器
       ignoreWidth: boolean = false, // 禁止页面渲染宽度
       ignoreHeight: boolean = false, // 禁止页面渲染高度
       ignoreFonts: boolean = false, // 禁止字体渲染
       breakPages: boolean = true, // 在分页符上启用分页
       ignoreLastRenderedPageBreak: boolean = true,//禁用lastRenderedPageBreak元素的分页
       experimental: boolean = false, //启用实验性功能(制表符停止计算)
       trimXmlDeclaration: boolean = true, //如果为真,xml声明将在解析之前从xml文档中删除
       debug: boolean = false, // 启用额外的日志记录
   }
);

复制代码
复制代码

achieve effect

picture

image.png

pdf realizes front-end preview

Code

  • First npm i pdfjs-dist
  • Set the address of PDFJS.GlobalWorkerOptions.workerSrc
  • Process pdf data through PDFJS.getDocument and return an object pdfDoc
  • Get the data of page 1 separately through pdfDoc.getPage
  • Create a dom element and set the element's canvas property
  • Render the data to the canvas through the page.render method
import * as PDFJS from "pdfjs-dist/legacy/build/pdf";
// 设置pdf.worker.js文件的引入地址
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/legacy/build/pdf.worker.entry.js");
// data是一个ArrayBuffer格式,也是一个buffer流的数据
PDFJS.getDocument(data).promise.then(pdfDoc=>{
    const numPages = pdfDoc.numPages; // pdf的总页数
    // 获取第1页的数据
    pdfDoc.getPage(1).then(page =>{
     // 设置canvas相关的属性
     const canvas = document.getElementById("the_canvas");
     const ctx = canvas.getContext("2d");
     const dpr = window.devicePixelRatio || 1;
     const bsr =
       ctx.webkitBackingStorePixelRatio ||
       ctx.mozBackingStorePixelRatio ||
       ctx.msBackingStorePixelRatio ||
       ctx.oBackingStorePixelRatio ||
       ctx.backingStorePixelRatio ||
       1;
     const ratio = dpr / bsr;
     const viewport = page.getViewport({ scale: 1 });
     canvas.width = viewport.width * ratio;
     canvas.height = viewport.height * ratio;
     canvas.style.width = viewport.width + "px";
     canvas.style.height = viewport.height + "px";
     ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
     const renderContext = {
       canvasContext: ctx,
       viewport: viewport,
     };
     // 数据渲染到canvas画布上
     page.render(renderContext);
    })
})

复制代码
复制代码

achieve effect

picture

image.png

Excel realizes front-end preview

Code

  • Download the library of exceljs, handsontable
  • Read data from file through exceljs
  • Obtain the data of each worksheet through the workbook.getWorksheet method, and process the data into a two-dimensional array of data
  • Introduce the component HotTable of @handsontable/vue
  • Through the settings attribute, some configuration parameters and two-dimensional array data are passed into the component, rendered into an excel style, and previewed
// 加载excel的数据
(new ExcelJS.Workbook().xlsx.load(buffer)).then(workbook=>{
   // 获取excel的第一页的数据
   const ws = workbook.getWorksheet(1);
   // 获取每一行的数据
   const data = ws.getRows(1, ws.actualRowCount);
 })
 
 
// 渲染页面
import { HotTable } from "@handsontable/vue";
<hot-table  :settings="hotSettings"></hot-table>
hotSettings = {
   language: "zh-CN",
   readOnly: true,
   data: this.data,
   cell: this.cell,
   mergeCells: this.merge,
   colHeaders: true,
   rowHeaders: true,
   height: "calc(100vh - 107px)",
   // contextMenu: true,
   // manualRowMove: true,
   // 关闭外部点击取消选中时间的行为
   outsideClickDeselects: false,
   // fillHandle: {
   //   direction: 'vertical',
   //   autoInsertRow: true
   // },
   // afterSelectionEnd: this.afterSelectionEnd,
   // bindRowsWithHeaders: 'strict',
   licenseKey: "non-commercial-and-evaluation"
}
复制代码
复制代码

achieve effect

picture

image.png

Front-end preview of pptx

Mainly through the jszip library, load the binary file, and then through some series of processing and conversion to achieve the preview effect, it is more troublesome to implement, so I will not paste the code. If you are interested, you can download the code to view.

achieve effect

picture

image.png

Summarize

It mainly introduces the way of previewing word, excel, and pdf files. The best effect of previewing the front-end is PDF, and there will be no problems of garbled characters and garbled characters. Therefore, the general good solution is to cooperate with the back-end to convert files of different formats. Convert it into pdf, and then realize the preview effect by the front end, which will retain some style effects of the file. For the realization of pictures and txt files, you can read the code if you are interested.

finally

See here, if this article is helpful to you, please like it~

code address

github.com/zhuye1993/f…[2]:github.com/zhuye1993/f…

About this article

Author: Bamboo Industry

juejin.cn/post/707159…

Guess you like

Origin juejin.im/post/7078468596988379149