当前位置: 首页 > Web前端 > HTML5

使用Electron打印成PDF

时间:2023-04-05 14:59:33 HTML5

使用Electron打印成PDF本系列文章的应用示例已发布在GitHub上:electron-api-demos-Zh_CN。您可以克隆或下载它并运行它来查看。欢迎来到星空。Electron中的浏览器窗口模块有一个webContents属性,它允许你的应用程序打印和打印成PDF。此模块的一个版本可用于两个进程:ipcMain和ipcRenderer。在浏览器中查看完整的API文档。打印为PDF支持:Win、macOS、Linux为了演示打印为PDF的功能,上面的示例按钮会将此页面另存为PDF,如果您有PDF查看器,请打开该文件。在实际应用程序中,您更有可能将其添加到应用程序菜单中,但出于演示目的,我们将其设置为示例button.rendererprocessconstipc=require('electron').ipcRendererconstprintPDFBtn=document.getElementById('print-pdf')printPDFBtn.addEventListener('click',function(event){ipc.send('print-to-pdf')})ipc.on('written-pdf',function(event,path){constmessage=`PDFsavedto:${path}`document.getElementById('pdf-path').innerHTML=message})主进程constfs=require('fs')constos=require('os')constpath=require('path')constelectron=require('electron')constBrowserWindow=electron.BrowserWindowconstipc=electron.ipcMainconstshell=electron.shellipc.on('print-to-pdf',函数(事件){constpdfPath=path.join(os.tmpdir(),'print.pdf')constwin=BrowserWindow.fromWebContents(event.sender)//使用默认打印选项win.webContents.printToPDF({},function(error,data){if(error)抛出错误fs.writeFile(pdfPath,data,function(error){if(error){throwerror}shell.openExternal('file://'+pdfPath)event.sender.send('wrote-pdf',pdfPath)})})})高级技术使用打印样式表。您可以为打印目标创建样式表以优化用户打印的外观。下面是这个应用程序中使用的样式表,位于assets/css/print.css.@mediaprint{body{background:none;颜色:黑色!重要;字体大小:70%;保证金:0;填充:0;}h1{字体大小:22px;}.nav,button,.demo-box:before,#pdf-path,headerp{display:none;}.demo-box,h2,pre,code{padding:0!important;保证金:0!重要;}header{填充:0010px0;}code,.support{font-size:10px;}}如果本文对您有帮助,感谢下方支持或StarGitHub:electron-api-demos-Zh_CN,谢谢。