# 导出word

# 依赖

docxtemplater 根据模板填充数据导出WORD文档的库
jszip-utils 读取WORD文件的库
pizzip 一个同步压缩文件的库
open-docxtemplater-image-module 开源WORD插入图片的库
1
2
3
4
//-- 安装 docxtemplater pizzip
npm install docxtemplater pizzip  --save
//-- 安装 jszip-utils
npm install jszip-utils --save 
//安装 open-docxtemplater-image-module
npm install open-docxtemplater-image-module --save
1
2
3
4
5
6
import docxtemplater from 'docxtemplater' //生成WORD
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
const ImageModule = require('open-docxtemplater-image-module'); //WORD图片依赖
1
2
3
4

# 数据填充

数据使用{变量}

图片使用{%变量}

list使用{#list}{data1}{/list}

let data = {
    title : '标题',
    clients: [
        {
          first_name: "John",
          last_name: "Doe",
          phone: "+44546546454"
        }
  	]
    img : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4QIJBywfp3IOswAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAkUlEQVQY052PMQqDQBREZ1f/d1kUm3SxkeAF/FdIjpOcw2vpKcRWCwsRPMFPsaIQSIoMr5pXDGNUFd9j8TOn7kRW71fvO5HTq6qqtnWtzh20IqE3YXtL0zyKwAROQLQ5l/c9gHjfKK6wMZjADE6s49Dver4/smEAc2CuqgwAYI5jU9NcxhHEy60sni986H9+vwG1yDHfK1jitgAAAABJRU5ErkJggg=='
}
1
2
3
4
5
6
7
8
9
10
11

输出文档:

# 导出PDF

Electron 中的 browser window 模块具有 webContents 属性, 它允许您的应用程序进行打印以及打印到PDF.

示例

const { BrowserWindow } = require('electron')
const fs = require('fs')
const path = require('path')
const os = require('os')

const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com')

win.webContents.on('did-finish-load', () => {
  // Use default printing options
  win.webContents.printToPDF({}).then(data => {
    const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
    fs.writeFile(pdfPath, data, (error) => {
      if (error) throw error
      console.log(`Wrote PDF successfully to ${pdfPath}`)
    })
  }).catch(error => {
    console.log(`Failed to write PDF to ${pdfPath}: `, error)
  })
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20