【js文件系列二】导出pdf文件和word/excel/pdf/ppt在线预览

9684次浏览

前言

本文是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:

<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 )

  //渲染函数
    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')
        // 动态创建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文件实现前端预览

首先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=预览文档指定

相关文章: