electron项目导出pdf的方法

5 篇文章 1 订阅
5 篇文章 0 订阅

前言

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导出功能。希望小伙伴们多多留言,有问题或者有建议都可以留言告诉我。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是在 Vue 项目中引入 Electron 的详细方法: 1. 首先,需要在 Vue 项目的根目录下安装 Electron: ``` npm install electron --save-dev ``` 2. 在项目根目录下创建一个 `main` 目录,并在该目录下创建一个 `index.js` 文件,用于启动 Electron: ```javascript const { app, BrowserWindow } = require('electron') function createWindow () { // 创建浏览器窗口 let win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // 加载 Vue 项目的主页面 win.loadURL('http://localhost:8080') // 打开开发者工具 win.webContents.openDevTools() } // Electron 初始化完成后执行的回调函数 app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // 当所有窗口都关闭时退出应用 app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ``` 在 `package.json` 文件中添加以下脚本: ```json { "scripts": { "electron": "electron main/index.js" } } ``` 3. 修改 `vue.config.js` 文件,在开发模式下执行 `electron` 命令启动 Electron: ```javascript module.exports = { // ... devServer: { before (app, server) { if (process.env.NODE_ENV === 'development') { const electron = require('child_process').spawn('npm', ['run', 'electron']) electron.stdout.on('data', data => { console.log(data.toString()) }) electron.stderr.on('data', data => { console.error(data.toString()) }) electron.on('close', code => { console.log(`Electron exited with code ${code}`) }) } } } } ``` 4. 在 `public` 目录下创建一个 `electron.js` 文件,用于判断当前是否在 Electron 中运行: ```javascript window.isElectron = navigator.userAgent.toLowerCase().indexOf(' electron/') > -1 ``` 5. 修改 `public/index.html` 文件,根据当前是否在 Electron 中运行来加载不同的脚本: ```html <body> <noscript> <strong>We're sorry but my-app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <script> if (window.isElectron) { require('./electron.js') } else { document.write('<script src="http://localhost:8080/js/chunk-vendors.js"></script><script src="http://localhost:8080/js/app.js"></script>') } </script> </body> ``` 6. 最后,在命令行中执行以下命令启动 Vue 项目: ``` npm run serve ``` 在浏览器中访问 `http://localhost:8080`,即可看到 Vue 项目的主页面。同时,在命令行中执行以下命令启动 Electron: ``` npm run electron ``` 即可看到 Electron 窗口中加载了 Vue 项目的主页面。 注意:在 Electron 中使用 Vue,需要在 `webPreferences` 中设置 `nodeIntegration` 为 `true`,这样才能在渲染进程中使用 Node.js 模块。但是,这样也会存在一些安全问题,需要注意。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值