【问题标题】:How to stop wkhtmltopdf.exe popping up?如何阻止 wkhtmltopdf.exe 弹出?
【发布时间】:2019-12-17 13:03:50
【问题描述】:

我在 python 中创建了一个 GUI 程序来创建 pdfs。我正在使用 pdfkit 库来创建 pdfs:

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 窗口。我怎样才能停止弹出?上网查了一下,没找到解决办法。

【问题讨论】:

  • 我无法弄清楚如何使用目录。你能帮助我吗?我假设我需要一个 .xsl 文件。但我不太了解那种文档类型,也不知道我应该在那里放什么。谢谢!

标签: python python-3.x popup wkhtmltopdf pdfkit


【解决方案1】:

虽然不是直截了当,但弹出窗口来自模块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'>

从您在以下部分中的链接编辑文件,添加的参数与 cmets;

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

【讨论】:

  • 你是救星!我想说这个解决方案非常简单且易于实施。虽然,它也可以在没有使用 .pyw 扩展名保存脚本的情况下工作。
  • 是的,.pyw 只是为了抑制 Python 控制台(如果有)。希望对您有所帮助,无论如何,如果您认为有用,请进一步建议将args 传递到pdfkit 的选项以在不更改原始库代码的情况下传递参数。
猜你喜欢
  • 2018-12-02
  • 2016-03-20
  • 2015-03-03
  • 1970-01-01
  • 2013-08-10
  • 2021-10-01
  • 2020-05-04
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多