This article is the second issue of the JS file export series, which mainly talks about how to export pdf files online and how to preview office files online. At present, these technologies are relatively mature in front-end implementation, and they all have relatively mature technology libraries. Let’s go through it with you below.
Pure front-end export pdf
I won’t make wheels here. Let’s talk about several popular front-end libraries that export pdf in pure front-end, which you can use according to different scenarios.
1、pdfmake
Github address:/bpampuch/pdfmake
pdf can support Chinese, has some adaptive layout functions, and needs to introduce a font library.
//npm or cdn import files// Introduce font library(Roboto); // Create a document streamlet docDefinition={} var pdf = (docDefinition); ('pdfs/').then(() => { (new Date() - now); }, err => { (err); });
This solution is suitable for document streams that are relatively not exquisite in layout and are easy to generate. No online preview, download the PDF directly
2、jsPDF
Github address:
/parallax/jsPDF
Simple to use, the official recommendation is to use html2canvas in conjunction with it, and html2canvas generates pictures.
// = { // ... externals: { // only define the dependencies you are NOT using as externals! canvg: "canvg", html2canvas: "html2canvas", dompurify: "dompurify" } };
It's easy to use
// Landscape export, 2×4 inches const doc = new jsPDF({ orientation: "landscape", unit: "in", format: [4, 2] }); ("Hello world!", 1, 1); ("");
Support the introduction of fonts
const doc = new jsPDF(); const myFont = ... // load the *.ttf font file as binary string // add the font to jsPDF ("", myFont); ("", "MyFont", "normal"); ("MyFont");
3、html2pdf
Html can directly export pdf and github address/eKoopmans/
Suitable for more complex typesetting scenarios, what you see is what you get, and you can export pdf. Suitable for previewing scenes together.
Office online preview
pdf online preview, we usually use
First npm i pdfjs-dist
Set address
By processing pdf data, return an object pdfDoc
Get the data on page 1 individually
Create a dom element and set the element's canvas properties
By using the method, render the data on the canvas
html:
<div class="showContent" ></div>
js:
import pdfjsLib from 'pdfjs-dist' import pdfwprker from 'pdfjs-dist/build/' // let pdfPath = '/pdfjs/' = pdfwprker const wrapBox = ('canvasWrap') (wrapBox,pdfPath ) // Rendering function async renderPdfs(element, url) { // (url,"psfurl") const loadingTask = (url) const pdfDocument = await // (pdfDocument, 'pdf') for (let i = 1; i <= ; i++) { const canvas = ('canvas') // Dynamically create canvas (canvas); (async function(n) { const pdfPage = await (n) // Display page on the existing canvas with 100% scale. const viewport = (1.5) = `theCanvas${n}` = = var ctx = ('2d') var renderTask = ({ canvasContext: ctx, viewport: viewport }) return })(i) } }
Docx file implementation front-end preview
First npm i docx-preview
Introduce renderAsync method
Pass blob data stream into the method and render the word document
import { defaultOptions, renderAsync } from "docx-preview"; renderAsync(buffer, ("container"), null, options: { className: string = "docx", // Class name/prefix for default and document style classes inWrapper: boolean = true, // Enable render wrapper around document content ignoreWidth: boolean = false, //Page rendering width is prohibited ignoreHeight: boolean = false, //Page rendering height is prohibited ignoreFonts: boolean = false, // font rendering is prohibited breakPages: boolean = true, // Enable paging on page break ignoreLastRenderedPageBreak: boolean = true,//Disable pagination of lastRenderedPageBreak element experimental: boolean = false, //Enable experimental function (tab character stops calculation) trimXmlDeclaration: boolean = true, //If true, the xml declaration will be removed from the xml document before parsing debug: boolean = false, // Enable additional logging } );
Excel implements front-end preview
exceljs github library/exceljs/exceljs
Download exceljs, handsontable libraries
Read the data of the file through exceljs
The data of each worksheet is obtained through the method and the data is processed into a two-dimensional array of data
Through the settings property, some configuration parameters and two-dimensional array data are passed to the component and rendered into an excel style to achieve preview
// Load excel data(new ().(buffer)).then(workbook=>{ // Get the data on the first page of excel const ws = (1); // Get the data of each row const data = (1, ); }) // Render pagehotSettings = { language: "zh-CN", readOnly: true, data: , cell: , mergeCells: , colHeaders: true, rowHeaders: true, height: "calc(100vh - 107px)", // contextMenu: true, // manualRowMove: true, // Close the behavior of unselecting the time when external click outsideClickDeselects: false, // fillHandle: { // direction: 'vertical', // autoInsertRow: true // }, // afterSelectionEnd: , // bindRowsWithHeaders: 'strict', licenseKey: "non-commercial-and-evaluation" }
Another preview of excel can be used/SheetJS/sheetjs
Nodejs or pure client can be used. The use cases of pure client react are as follows:
Reference demo/SheetJS/sheetjs/tree/master/demos/react
Front-end preview of pptx
Github address:/meshesha/PPTXjs
This library uses jquery and jszip. If you don't want to introduce jquery, you can modify it yourself.
Another way is to convert ppt to pdf and preview it by previewing pdf, which is more general and convenient.
summary
In addition to the pure front-end method above, Microsoft and Google also provide online preview APIs, which will actually have better results and simpler. Google Online Preview Interface
/viewer?url=Preview document address
Microsoft preview address:
/op/?src=Preview document specification
This is the article about JavaScript implementing PDF file export and online preview functions. For more related JavaScript pdf file export content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!