electron-vite 配合python
要实现的功能
- pdf转化和doc
- doc转换为pdf
- pdf的合并
Q:为什么不直接使用node?
只想尝试electron是否能和其他的程序相互配合
- 构建工具 yarn | npm 不要选择pnpm
- electron框架选择 electron-vite
- 转换功能选择 python库
from pdf2docx import Converterimport docx2pdffrom PyPDF2 import PdfMerger
electron-vite要怎么嵌入python
可看csdn这篇文章
项目结构
所有的python代码都要放到resources文件夹下面
注意点1
import pdf2docPathAddress from '../../resources/pythonCode/pdf2doc.py?asset'
import pythonPathAddress from '../../resources/python/python-3.13.5-embed-amd64/python.exe?asset'
import pdfMergePathAddress from '../../resources/pythonCode/PdfFileMerger.py?asset'
上述代码导入的时候一定要写?asset,让electron-vite知道这是静态文件,
否则打包的时候会将python代码位置放错
注意点2
const scriptPath = is.dev? pdf2docPathAddress: pdf2docPathAddress.replace('app.asar', 'app.asar.unpacked')const pythonPath = is.dev? pythonPathAddress: pythonPathAddress.replace('app.asar', 'app.asar.unpacked')const pdfMergePath = is.dev? pdfMergePathAddress: pdfMergePathAddress.replace('app.asar', 'app.asar.unpacked')
必须这么做,打包之后静态文件,也就是python代码会在app.asar.unpacked文件下面! 如果不更改那么在使用spawn的时候,不能找到python.exe
为什么静态文件会放到resources下面?
asarUnpack:- resources/**
因为electron-builder.yml中配置,你可自己手动更改,但不建议
贴出所有pdf转换为doc代码剩余都类似
ipcMain.handle('convert-pdf-to-docx', async (_, pdfPath) => {const docxPath = pdfPath.replace(/\.pdf$/, '.docx')return new Promise((resolve, reject) => {const py = spawn(pythonPath, [scriptPath, pdfPath, docxPath, 'convert-pdf-to-docx'])py.on('close', (code) => {if (code === 0) {resolve(docxPath)// 系统弹窗dialog.showMessageBox({type: 'info',title: '转换成功',message: '文件已成功转换为 DOCX 格式'}).then(() => {// 打开文件所在目录shell.showItemInFolder(docxPath)// 打开文件shell.openPath(docxPath)})} else {// 系统弹窗dialog.showMessageBox({type: 'error',title: '转换失败',message: `转换失败,退出码: ${code}`}).then(() => {reject(new Error(`转换失败,退出码: ${code}`))})}})py.on('error', (error) => {reject(new Error(`启动 Python 失败: ${error.message}`))})})
})
import sys
import os# pdf和world相互转换# 自动注入嵌入式 python site-packages 路径
def inject_site_packages():base_dir = os.path.dirname(os.path.abspath(__file__))# 适配你的嵌入式目录结构(根据实际路径调整)python_lib = os.path.abspath(os.path.join(base_dir, '..', 'python', 'python-3.13.5-embed-amd64', 'Lib', 'site-packages'))if python_lib not in sys.path:sys.path.insert(0, python_lib)
inject_site_packages()from pdf2docx import Converter
import docx2pdf
from pathlib import Pathdef pdf_to_docx(pdf: Path, docx: Path):try:cv = Converter(str(pdf))cv.convert(str(docx), start=0, end=None)cv.close()print(f"文件 {pdf} 已成功转换为 {docx}")return Trueexcept Exception as e:print(f"转换过程中出错: {e}")raisedef docx_to_pdf(docx: Path, pdf: Path):try:# 确保目标目录存在out_dir = pdf.parentout_dir.mkdir(parents=True, exist_ok=True)docx2pdf.convert(str(docx), str(pdf))print(f"文件 {docx} 已成功转换为 {pdf}")return Trueexcept Exception as e:print(f"docx 转 pdf 过程中出错: {e}")return Falseif __name__ == '__main__':pdf_path = sys.argv[1]docx_path = sys.argv[2]action = sys.argv[3]if action == 'convert-pdf-to-docx':pdf = Path(pdf_path)docx = Path(docx_path)pdf_to_docx(pdf, docx)elif action == 'convert-docx-to-pdf':docx = Path(docx_path)pdf = Path(pdf_path)docx_to_pdf(docx, pdf)
页面展示