preface

Because business needs, many files need to realize preview in the front end, today is to understand it.

Implementation scheme

Some of them can be directly introduced into VUE through NPM.

Document format Old open source components Alternative Open source components
The word (docx) mammoth docx-preview(npm)
Powerpoint (PPTX) pptxjs PPTXJS transformation and development
Excel (XLSX) Sheetjs, handsontable Exceljs (NPM), handsontable (NPM) (NPM)
PDF (PDF) pdfjs pdfjs(npm)
The picture jquery.verySimpleImageViewer v-viewer(npm)

Docx file front-end preview

Code implementation

  • First NPM I DOCX-Preview
  • Introduce the renderAsync method
  • The BLOB data is propagated into the method, rendering the Word document
import { defaultOptions, renderAsync } from "docx-preview";
renderAsync(buffer, document.getElementById("container"), null.options: {
       className: string = "docx".// The class name/prefix of the default and document style classes
       inWrapper: boolean = true.// Enable the render wrapper around document content
       ignoreWidth: boolean = false.// Disable page render width
       ignoreHeight: boolean = false.// Disable page render height
       ignoreFonts: boolean = false.// Disable font rendering
       breakPages: boolean = true.// Enable paging on page breaks
       ignoreLastRenderedPageBreak: boolean = true.// Disable pagination of the lastRenderedPageBreak element
       experimental: boolean = false.// Enable experimental function (TAB stop calculation)
       trimXmlDeclaration: boolean = true.// If true, the XML declaration will be removed from the XML document before parsing
       debug: boolean = false.// Enable additional logging});Copy the code

Implementation effect

PDF implements front-end preview

Code implementation

  • First, NPM I PDFJS-dist
  • Set the PDFJS. GlobalWorkerOptions. WorkerSrc address
  • Pdfjs.getdocument processes the PDF data and returns an object pdfDoc
  • Get the data on page 1 separately from pdfdoc.getPage
  • Create a DOM element and set the canvas properties of the element
  • Render the data onto the canvas using the Page. render method
import * as PDFJS from "pdfjs-dist/legacy/build/pdf";
// Set the import address for the pdf.worker.js file
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/legacy/build/pdf.worker.entry.js");
// Data is an ArrayBuffer format, which is also a buffer stream of data
PDFJS.getDocument(data).promise.then(pdfDoc= >{
    const numPages = pdfDoc.numPages; // Total number of pages in PDF
    // get the data on page 1
    pdfDoc.getPage(1).then(page= >{
     // Set canvas related properties
     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,
     };
     // Render data to canvas canvaspage.render(renderContext); })})Copy the code

Implementation effect

Excel implements front-end preview

Code implementation

  • Download excelJS, HandsonTable libraries
  • Read the file data through ExcelJS
  • The workbook.getWorksheet method is used to obtain the data of each worksheet and process the data into a two-dimensional array of data
  • Introduce the @handsonTable /vue component HotTable
  • Through the Settings property, some configuration parameters and two-dimensional array data are passed into the component and rendered in Excel style for preview
// Load excel datanew ExcelJS.Workbook().xlsx.load(buffer)).then(workbook= >{
   // Get the first page of Excel data
   const ws = workbook.getWorksheet(1);
   // Get the data for each row
   const data = ws.getRows(1, ws.actualRowCount);
 })
 
 
// Render the page
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,
   // Turn off external clicks to deselect time
   outsideClickDeselects: false.// fillHandle: {
   // direction: 'vertical',
   // autoInsertRow: true
   // },
   // afterSelectionEnd: this.afterSelectionEnd,
   // bindRowsWithHeaders: 'strict',
   licenseKey: "non-commercial-and-evaluation"
}
Copy the code

Implementation effect

PPTX front end preview

The preview effect is achieved by loading the BLOB file stream through the JsZIP library and performing some column processing transformations

Implementation effect

conclusion

Mainly introduced the word, excel, PDF files to achieve preview mode, front or PDF make a preview of the best effect, won’t appear some questions writing disorder and garbled, so generally good plan is the backend with different format file into PDF, again by the front end to achieve preview effect, the effect of the some style will retain file, For pictures, TXT file implementation, interested can see the code.

The last

If this article is helpful to you, please like it

The code address

Github.com/zhuye1993/f…

The resources

1. www.npmjs.com/package/doc… 2. blog.csdn.net/wybaby168/a…