JavaScript實現(xiàn)pdf文件導出和在線預覽功能
本文是js文件導出系列第二期,主要講講如何在線導出pdf文件,及office文件如何在線預覽。目前前端實現(xiàn)這些技術已經(jīng)比較成熟,都有比較成熟的技術庫,下面來和大家一起過一下吧。
純前端導出pdf
這里就不造輪子了,說一說純前端導出pdf的幾個流行的前端庫,大家可以根據(jù)不同場景使用。
1、pdfmake
github地址:github.com/bpampuch/pdfmake
pdf能夠支持中文,具有部分自適應布局功能,需要引入字體庫。
//npm 或者cdn引入文件 // 引入字體庫 pdfmake.addFonts(Roboto); // 創(chuàng)建文檔流 let docDefinition={} var pdf = pdfmake.createPdf(docDefinition); pdf.write('pdfs/absolute.pdf').then(() => { console.log(new Date() - now); }, err => { console.error(err); });
本方案適用于排版相對不是太精美的文檔流,生成方便。無在線預覽,直接下載pdf的情況
2、jsPDF
github地址:
使用簡單,官方推薦html2canvas 配合使用,html2canvas生成圖片。
// webpack.config.js module.exports = { // ... externals: { // only define the dependencies you are NOT using as externals! canvg: "canvg", html2canvas: "html2canvas", dompurify: "dompurify" } };
使用很簡單
// Landscape export, 2×4 inches const doc = new jsPDF({ orientation: "landscape", unit: "in", format: [4, 2] }); doc.text("Hello world!", 1, 1); doc.save("two-by-four.pdf");
支持引入字體
const doc = new jsPDF(); const myFont = ... // load the *.ttf font file as binary string // add the font to jsPDF doc.addFileToVFS("MyFont.ttf", myFont); doc.addFont("MyFont.ttf", "MyFont", "normal"); doc.setFont("MyFont");
3、html2pdf
Html可以直接導出pdf,github地址 github.com/eKoopmans/html2pdf.js
適合比較復雜排版的場景,所見即所得,可以導出pdf。適合預覽一起做的場景。
office在線預覽
pdf在線預覽,我們一般用pdf.js
首先npm i pdfjs-dist
設置PDFJS.GlobalWorkerOptions.workerSrc的地址
通過PDFJS.getDocument處理pdf數(shù)據(jù),返回一個對象pdfDoc
通過pdfDoc.getPage單獨獲取第1頁的數(shù)據(jù)
創(chuàng)建一個dom元素,設置元素的畫布屬性
通過page.render方法,將數(shù)據(jù)渲染到畫布上
html:
<div class="showContent" id="canvasWrap"></div>
js:
import pdfjsLib from 'pdfjs-dist' import pdfwprker from 'pdfjs-dist/build/pdf.worker.js' // let pdfPath = 'http://cdn.mozilla.net/pdfjs/tracemonkey.pdf' pdfjsLib.GlobalWorkerOptions.workerSrc = pdfwprker const wrapBox = document.getElementById('canvasWrap') this.renderPdfs(wrapBox,pdfPath ) //渲染函數(shù) async renderPdfs(element, url) { // console.log(url,"psfurl") const loadingTask = pdfjsLib.getDocument(url) const pdfDocument = await loadingTask.promise // console.log(pdfDocument, 'pdf') for (let i = 1; i <= pdfDocument.numPages; i++) { const canvas = document.createElement('canvas') // 動態(tài)創(chuàng)建canvas element.appendChild(canvas); (async function(n) { const pdfPage = await pdfDocument.getPage(n) // Display page on the existing canvas with 100% scale. const viewport = pdfPage.getViewport(1.5) canvas.id = `theCanvas${n}` canvas.width = viewport.width canvas.height = viewport.height var ctx = canvas.getContext('2d') var renderTask = pdfPage.render({ canvasContext: ctx, viewport: viewport }) return renderTask.promise })(i) } }
docx文件實現(xiàn)前端預覽
首先npm i docx-preview
引入renderAsync方法
將blob數(shù)據(jù)流傳入方法中,渲染word文檔
import { defaultOptions, renderAsync } from "docx-preview"; renderAsync(buffer, document.getElementById("container"), null, options: { className: string = "docx", // 默認和文檔樣式類的類名/前綴 inWrapper: boolean = true, // 啟用圍繞文檔內(nèi)容渲染包裝器 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, // 啟用額外的日志記錄 } );
excel實現(xiàn)前端預覽
exceljs github庫 github.com/exceljs/exceljs
下載exceljs、handsontable的庫
通過exceljs讀取到文件的數(shù)據(jù)
通過workbook.getWorksheet方法獲取到每一個工作表的數(shù)據(jù),將數(shù)據(jù)處理成一個二維數(shù)組的數(shù)據(jù)
通過settings屬性,將一些配置參數(shù)和二維數(shù)組數(shù)據(jù)傳入組件,渲染成excel樣式,實現(xiàn)預覽
// 加載excel的數(shù)據(jù) (new ExcelJS.Workbook().xlsx.load(buffer)).then(workbook=>{ // 獲取excel的第一頁的數(shù)據(jù) const ws = workbook.getWorksheet(1); // 獲取每一行的數(shù)據(jù) const data = ws.getRows(1, ws.actualRowCount); }) // 渲染頁面 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" }
excel的另外的預覽,可以采用 github.com/SheetJS/sheetjs
nodejs 或者純客戶端都可以使用,純客戶端react的使用案例如下:
參考demo github.com/SheetJS/sheetjs/tree/master/demos/react
pptx的前端預覽
github地址:github.com/meshesha/PPTXjs
這個庫采用jquery,和jszip ,假如不想引入jquery,可以自己改造一下使用。
還有種方式就是將ppt轉(zhuǎn)為pdf,通過預覽pdf的方式來預覽,這樣比較通用,也比較方便。
小結(jié)
除了上面的純前端方式,其實微軟和谷歌也提供了在線預覽api,這個預覽其實效果會更好,更加簡單。 谷歌在線預覽接口
https://docs.google.com/viewer?url=預覽文檔地址
微軟預覽地址:
https://view.officeapps.live.com/op/view.aspx?src=預覽文檔指定
到此這篇關于JavaScript實現(xiàn)pdf文件導出和在線預覽功能的文章就介紹到這了,更多相關JavaScript pdf文件導出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
極酷的javascirpt,讓你隨意編輯任何網(wǎng)頁
極酷的javascirpt,讓你隨意編輯任何網(wǎng)頁...2007-02-02詳解webpack4之splitchunksPlugin代碼包分拆
這篇文章主要介紹了詳解webpack4之splitchunksPlugin代碼包分拆,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12