electron项目导出pdf

998 阅读1分钟

前言

electron项目导出pdf的功能和electron打印的方法类似

一、渲染进程通知主进程进行导出

随便找个页面 ==注意== 一定要写行内样式,颜色相关的不能使用16进制(#000)只能使用rgb(0,0,0) 或者颜色的英文单词。别问为什么,问就是坑。

import { ipcRenderer } from 'electron';
const path = require('path')
const os = require('os')

const html = `
<div style="width:100%;display:flex;justify-content:flex-start;align-items:center;height:30px;line-height:30px;padding-left: 10px">
        <section style="width: 15%;">张三</section>
        <section style="width: 15%;">李四</section>
        <section style="width: 15%;">小明</section>
        <section style="width: 20%;">王五</section>
      </div>`;
// 或者从页面上获取你需要导出的内容
// const html = document.querySelector('#pdf');
const filePath = path.join(os.homedir(), 'Desktop', 'temp.pdf')//文件存储的路径
ipcRenderer.send('export-pdf', { html, filePath }); // 告诉主线程执行导出pdf的任务
ipcRenderer.once('export-pdf-res', (_e, data) => {
      console.log('收到导出pdf的结果', data);
      exportPdfResult(data);
    });

二、主线进程执行导出任务

import electron, {
  app, BrowserWindow, shell, ipcMain
} from 'electron';
const fs = require('fs');

let mainWindow: BrowserWindow | null = null; // 主应用窗口
let pdfWindow: BrowserWindow | null = null; // 新建一个窗口用于导出pdf

  ipcMain.on('export-pdf', async (_event, obj) => {
    pdfWindow = new BrowserWindow({
      webPreferences: {
        nodeIntegration: true,
        webSecurity: false,
        enableRemoteModule: true
      },
      show: true, // 如果不想显示窗口可以改为false
      width: 800,
      height: 600,
      fullscreenable: true,
      minimizable: false
    });
    pdfWindow.loadURL(`data:text/html;charset=utf-8,${encodeURI(obj.html)}`);

    pdfWindow.webContents.on('did-finish-load', () => {
      // Use default printing options
      const pdfPath = obj.filePath;
      pdfWindow.webContents.printToPDF({
        printBackground: true
      }).then(data => {
        fs.writeFile(pdfPath, data, error => {
          if (error) throw error;
          mainWindow.webContents.send('export-pdf-res', { success: `导出成功,路径:${pdfPath}` });
          pdfWindow.close();// 保存pdf过后关闭该窗口
          pdfWindow = null;
        });
      }).catch(error => {
        mainWindow.webContents.send('export-pdf-res', { failed: `导出失败,路径:${JSON.stringify(error)}` });
      });
    });
  });

总结

尝试过pdfmak, html2canvas + jsPDF,几种方法,但是都需要对中文乱码做处理。最后还是使用了electron自带的pdf导出功能。希望小伙伴们多多留言,有问题或者有建议都可以留言告诉我。