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

标签 python python-3.x popup wkhtmltopdf pdfkit

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

相关文章:

python - Django 1.8 ModelForm request.POST 取代实例

python - 使用 python TVTK 或 MayaVi 探测/采样/插值 VTK 数据

python - Django 1.5.4 中的 ImageField ——处理图像路径

python - 归并排序Python实现方法

python - tkMessageBox 弹出窗口从桌面运行时不可见,从引导运行时可见

javascript - 用户登录时仅显示一次弹出窗口

WPF 弹出窗口出现在其他桌面窗口上,如何只出现在 WPF 主窗口的顶部?

python - 以可迭代作为参数的函数是否总是接受迭代器?

python-3.x - Selenium 与 Python-unittest - 测试返回进程已完成,退出代码为 0,并且不执行任何操作

python - 使用输入设置所有字符的列表。使用列表长度检查所有字符并将其替换为相应的值