如何停止弹出 wkhtmltopdf.exe?

How to stop wkhtmltopdf.exe popping up?

我在 python 中创建了一个 GUI 程序来创建 pdfs.I 我正在使用 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 期间弹出 window of wkhtmltopdf.exe 的命令。我怎样才能停止弹出?在互联网上搜索后我没有找到任何解决方案。

虽然不是直接的,但是弹出 window 来自模块 subprocess 调用的命令,当来自 [=15= 的可执行文件时默认创建 window ] 叫做。

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.


找到并更改创建 window

subprocess 设置
import pdfkit

pdfkit.pdfkit
#THIS LOCATES THE FILE YOU NEED TO CHANGE

Output:
<module 'pdfkit.pdfkit' from '\lib\site-packages\pdfkit\pdfkit.py'>

从link编辑文件,添加的参数有注释;

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 )

并保存文件,这会传递抑制创建 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 下同一文件夹中的可执行文件测试您的程序。