gpt4 book ai didi

python - 如何阻止 wkhtmltopdf.exe 弹出?

转载 作者:行者123 更新时间:2023-12-01 06:42:43 26 4
gpt4 key购买 nike

我在 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。

<小时/>

找到并更改创建窗口的子进程设置

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 下同一文件夹中的可执行文件来测试您的程序。

关于python - 如何阻止 wkhtmltopdf.exe 弹出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59374849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com