共计 3724 个字符,预计需要花费 10 分钟才能阅读完成。
前言
本文是 js 文件导出系列第二期,主要讲讲如何在线导出 pdf 文件,及 office 文件如何在线预览。目前前端实现这些技术已经比较成熟,都有比较成熟的技术库,下面来和大家一起过一下吧。
纯前端导出 pdf
这里就不造轮子了,说一说纯前端导出 pdf 的几个流行的前端库,大家可以根据不同场景使用。
1、pdfmake
github 地址:https://github.com/bpampuch/pdfmake
pdf 能够支持中文,具有部分自适应布局功能,需要引入字体库。
//npm 或者 cdn 引入文件
// 引入字体库
pdfmake.addFonts(Roboto);
// 创建文档流
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 地址:
https://github.com/parallax/jsPDF
使用简单,官方推荐 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 地址 https://github.com/eKoopmans/html2pdf.js
适合比较复杂排版的场景,所见即所得,可以导出 pdf。适合预览一起做的场景。
office 在线预览
pdf 在线预览,我们一般用 pdf.js
首先 npm i pdfjs-dist
设置 PDFJS.GlobalWorkerOptions.workerSrc 的地址
通过 PDFJS.getDocument 处理 pdf 数据,返回一个对象 pdfDoc
通过 pdfDoc.getPage 单独获取第 1 页的数据
创建一个 dom 元素,设置元素的画布属性
通过 page.render 方法,将数据渲染到画布上
html:
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)
// 渲染函数
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
docx 文件实现前端预览
首先 npm i docx-preview
引入 renderAsync 方法
将 blob 数据流传入方法中,渲染 word 文档
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, // 启用额外的日志记录
}
);
excel 实现前端预览
exceljs github 库 https://github.com/exceljs/exceljs
下载 exceljs、handsontable 的库
通过 exceljs 读取到文件的数据
通过 workbook.getWorksheet 方法获取到每一个工作表的数据,将数据处理成一个二维数组的数据
通过 settings 属性,将一些配置参数和二维数组数据传入组件,渲染成 excel 样式,实现预览
// 加载 excel 的数据(new ExcelJS.Workbook().xlsx.load(buffer)).then(workbook=>{
// 获取 excel 的第一页的数据
const ws = workbook.getWorksheet(1);
// 获取每一行的数据
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 的另外的预览,可以采用 https://github.com/SheetJS/sheetjs
nodejs 或者纯客户端都可以使用,纯客户端 react 的使用案例如下:
参考 demo https://github.com/SheetJS/sheetjs/tree/master/demos/react
pptx 的前端预览
github 地址:https://github.com/meshesha/PPTXjs
这个库采用 jquery,和 jszip,假如不想引入 jquery,可以自己改造一下使用。
还有种方式就是将 ppt 转为 pdf,通过预览 pdf 的方式来预览,这样比较通用,也比较方便。
小结
除了上面的纯前端方式,其实微软和谷歌也提供了在线预览 api,这个预览其实效果会更好,更加简单。
谷歌在线预览接口
https://docs.google.com/viewer?url= 预览文档地址
微软预览地址:
https://view.officeapps.live.com/op/view.aspx?src= 预览文档指定