JavaScript實(shí)現(xiàn)pdf文件導(dǎo)出和在線預(yù)覽功能
本文是js文件導(dǎo)出系列第二期,主要講講如何在線導(dǎo)出pdf文件,及office文件如何在線預(yù)覽。目前前端實(shí)現(xiàn)這些技術(shù)已經(jīng)比較成熟,都有比較成熟的技術(shù)庫,下面來和大家一起過一下吧。
純前端導(dǎo)出pdf
這里就不造輪子了,說一說純前端導(dǎo)出pdf的幾個(gè)流行的前端庫,大家可以根據(jù)不同場(chǎng)景使用。
1、pdfmake
github地址:github.com/bpampuch/pdfmake
pdf能夠支持中文,具有部分自適應(yīng)布局功能,需要引入字體庫。
//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);
});
本方案適用于排版相對(duì)不是太精美的文檔流,生成方便。無在線預(yù)覽,直接下載pdf的情況
2、jsPDF
github地址:
使用簡(jiǎn)單,官方推薦html2canvas 配合使用,html2canvas生成圖片。
// webpack.config.js
module.exports = {
// ...
externals: {
// only define the dependencies you are NOT using as externals!
canvg: "canvg",
html2canvas: "html2canvas",
dompurify: "dompurify"
}
};
使用很簡(jiǎn)單
// 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可以直接導(dǎo)出pdf,github地址 github.com/eKoopmans/html2pdf.js
適合比較復(fù)雜排版的場(chǎng)景,所見即所得,可以導(dǎo)出pdf。適合預(yù)覽一起做的場(chǎng)景。
office在線預(yù)覽
pdf在線預(yù)覽,我們一般用pdf.js
首先npm i pdfjs-dist
設(shè)置PDFJS.GlobalWorkerOptions.workerSrc的地址
通過PDFJS.getDocument處理pdf數(shù)據(jù),返回一個(gè)對(duì)象pdfDoc
通過pdfDoc.getPage單獨(dú)獲取第1頁的數(shù)據(jù)
創(chuàng)建一個(gè)dom元素,設(shè)置元素的畫布屬性
通過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')
// 動(dòng)態(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文件實(shí)現(xiàn)前端預(yù)覽
首先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", // 默認(rèn)和文檔樣式類的類名/前綴
inWrapper: boolean = true, // 啟用圍繞文檔內(nèi)容渲染包裝器
ignoreWidth: boolean = false, // 禁止頁面渲染寬度
ignoreHeight: boolean = false, // 禁止頁面渲染高度
ignoreFonts: boolean = false, // 禁止字體渲染
breakPages: boolean = true, // 在分頁符上啟用分頁
ignoreLastRenderedPageBreak: boolean = true,//禁用lastRenderedPageBreak元素的分頁
experimental: boolean = false, //啟用實(shí)驗(yàn)性功能(制表符停止計(jì)算)
trimXmlDeclaration: boolean = true, //如果為真,xml聲明將在解析之前從xml文檔中刪除
debug: boolean = false, // 啟用額外的日志記錄
}
);
excel實(shí)現(xiàn)前端預(yù)覽
exceljs github庫 github.com/exceljs/exceljs
下載exceljs、handsontable的庫
通過exceljs讀取到文件的數(shù)據(jù)
通過workbook.getWorksheet方法獲取到每一個(gè)工作表的數(shù)據(jù),將數(shù)據(jù)處理成一個(gè)二維數(shù)組的數(shù)據(jù)
通過settings屬性,將一些配置參數(shù)和二維數(shù)組數(shù)據(jù)傳入組件,渲染成excel樣式,實(shí)現(xiàn)預(yù)覽
// 加載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,
// 關(guān)閉外部點(diǎn)擊取消選中時(shí)間的行為
outsideClickDeselects: false,
// fillHandle: {
// direction: 'vertical',
// autoInsertRow: true
// },
// afterSelectionEnd: this.afterSelectionEnd,
// bindRowsWithHeaders: 'strict',
licenseKey: "non-commercial-and-evaluation"
}
excel的另外的預(yù)覽,可以采用 github.com/SheetJS/sheetjs
nodejs 或者純客戶端都可以使用,純客戶端react的使用案例如下:
參考demo github.com/SheetJS/sheetjs/tree/master/demos/react
pptx的前端預(yù)覽
github地址:github.com/meshesha/PPTXjs
這個(gè)庫采用jquery,和jszip ,假如不想引入jquery,可以自己改造一下使用。
還有種方式就是將ppt轉(zhuǎn)為pdf,通過預(yù)覽pdf的方式來預(yù)覽,這樣比較通用,也比較方便。
小結(jié)
除了上面的純前端方式,其實(shí)微軟和谷歌也提供了在線預(yù)覽api,這個(gè)預(yù)覽其實(shí)效果會(huì)更好,更加簡(jiǎn)單。 谷歌在線預(yù)覽接口
https://docs.google.com/viewer?url=預(yù)覽文檔地址
微軟預(yù)覽地址:
https://view.officeapps.live.com/op/view.aspx?src=預(yù)覽文檔指定
到此這篇關(guān)于JavaScript實(shí)現(xiàn)pdf文件導(dǎo)出和在線預(yù)覽功能的文章就介紹到這了,更多相關(guān)JavaScript pdf文件導(dǎo)出內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
用JS實(shí)現(xiàn)根據(jù)當(dāng)前時(shí)間隨機(jī)生成流水號(hào)或者訂單號(hào)
本文通過實(shí)例代碼給大家介紹了基于JS實(shí)現(xiàn)根據(jù)當(dāng)前時(shí)間隨機(jī)生成流水號(hào)或者訂單號(hào)的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-05-05
echarts實(shí)現(xiàn)橫向和縱向滾動(dòng)條(使用dataZoom)
這篇文章主要給大家介紹了關(guān)于echarts使用dataZoom實(shí)現(xiàn)橫向和縱向滾動(dòng)條的相關(guān)資料,最近項(xiàng)目中使用到echarts圖表,當(dāng)數(shù)據(jù)過多時(shí)需要添加橫向滾動(dòng)條,需要的朋友可以參考下2023-08-08
JavaScript動(dòng)態(tài)檢測(cè)密碼強(qiáng)度原理及實(shí)現(xiàn)方法詳解
這篇文章主要介紹了JavaScript動(dòng)態(tài)檢測(cè)密碼強(qiáng)度原理及實(shí)現(xiàn)方法,結(jié)合具體實(shí)例形式詳細(xì)分析了javascript針對(duì)輸入字符串密碼強(qiáng)度檢測(cè)的原理與相關(guān)判斷操作技巧,需要的朋友可以參考下2019-06-06
微信小程序?qū)崿F(xiàn)簡(jiǎn)單文字跑馬燈
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)簡(jiǎn)單文字跑馬燈,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05
關(guān)于預(yù)加載InstantClick的問題解決方法
本篇文章主要介紹了關(guān)于預(yù)加載InstantClick的問題解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
JavaScript的for循環(huán)中嵌套一個(gè)點(diǎn)擊事件的問題解決
本文主要介紹了JavaScript的for循環(huán)中嵌套一個(gè)點(diǎn)擊事件點(diǎn)擊一次彈出多個(gè)相同的值的解決方法,具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-03-03
js實(shí)現(xiàn)中文轉(zhuǎn)拼音的完整步驟記錄
這篇文章主要給大家介紹了關(guān)于js實(shí)現(xiàn)中文轉(zhuǎn)拼音的相關(guān)資料,主要利用了pinyin-pro包,可以完美的實(shí)現(xiàn)所需要的功能,需要的朋友可以參考下2021-06-06
JS控制FileUpload的上傳文件類型實(shí)例代碼
下面小編就為大家?guī)硪黄狫S控制FileUpload的上傳文件類型實(shí)例代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10

