[我用python创建了一个GUI程序来创建pdf。我正在使用pdfkit库来创建pdf:
options = {
'page-size': 'A4',
'margin-top': '0.3in',
'margin-bottom': '0.3in',
'margin-left': '0.5in',
'margin-right': '0.4in',
'quiet': '',
'orientation' : 'Landscape'
}
toc = {
'xsl-style-sheet': 'toc.xsl'
}
path_wkhtmltopdf = r'wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
pdfkit.from_string(htmlString, reportPath, configuration=config, toc=toc, options = options)
为了使我的GUI程序可执行,我使用了pyinstaller
。当我使用此.exe文件时,它将在创建pdf时弹出wkhtmltopdf.exe的cmd窗口。如何停止弹出?经过互联网研究后,我没有找到任何解决方案。
尽管不是直接的,但是弹出窗口来自模块subprocess
调用的命令,默认情况下,该命令在调用wkhtmltopdf
的可执行文件时创建一个窗口。
subprocess.CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
由于无法将参数传递给pdfkit
,因此您可以在从pyinstaller
构建之前定位要进行更改的模块。下面介绍的方法在Windows和Python 3.X上对我有效。
找到并更改用于创建窗口的subprocess
设置
import pdfkit
pdfkit.pdfkit
#THIS LOCATES THE FILE YOU NEED TO CHANGE
Output:
<module 'pdfkit.pdfkit' from '\\lib\\site-packages\\pdfkit\\pdfkit.py'>
从下面的链接中编辑文件,添加的参数带有注释;
def to_pdf(self, path=None):
#CREATE AN ADDITIONAL PARAMTER
CREATE_NO_WINDOW = 0x08000000
args = self.command(path)
result = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
#PASS YOUR PARAMETER HERE
creationflags = CREATE_NO_WINDOW )
并保存文件,这传递了禁止创建窗口的必需参数。
完成后,您应该可以重建程序。
示例程序
使用.pyw
扩展名保存以下代码,该扩展名基本上意味着Python的无控制台脚本,例如html2pdf.pyw
。确保将路径替换为您的路径。
import pdfkit
path_wkhtmltopdf = 'your wkhtmltopdf.exe path'
out_path = 'the output file goes here'
config = pdfkit.configuration(wkhtmltopdf = path_wkhtmltopdf)
pdfkit.from_url('http://google.com',
out_path,
configuration = config)
找到html2pdf.pyw
文件夹并使用pyinstaller
:pyinstaller html2pdf
进行构建。
使用位于dist\html2pdf\html2pdf.exe
下同一文件夹中的可执行文件最后测试您的程序。