无法写入目标 pdfkit python

问题描述

总结

我正在尝试使用包 pdfkit(版本 0.6.1)和 wkhtmltopdf(版本 0.12.6.0)将 HTML 转换为 PDF。

我可以使用该脚本,直到我尝试使用 cx_freeze 将其转换为 .exe 文件。然后它失败了。使用可执行文件,我收到以下错误

错误

Exception in thread Thread-109:
Traceback (most recent call last):
  File "C:\Users\Diego\AppData\Local\Programs\Python\python38-32\lib\threading.py",line 932,in _bootstrap_inner
    self.run()
  File "C:\Users\Diego\AppData\Local\Programs\Python\python38-32\lib\threading.py",line 870,in run
    self._target(*self._args,**self._kwargs)
  File "C:\Users\Diego\Pictures\Zona Python\GuideMath\src\interfaz\VentanaExportar.py",line 132,in __exportarHTMLaPDF
    self.__resultado = self.__ctrl.exportarHTMLaPDF(
  File "C:\Users\Diego\Pictures\Zona Python\GuideMath\src\controlador\Controlador.py",line 142,in exportarHTMLaPDF
    return "E" if pdfkit.from_url(
  File "C:\Users\Diego\AppData\Local\Programs\Python\python38-32\lib\site-packages\pdfkit\api.py",line 26,in from_url
    return r.to_pdf(output_path)
  File "C:\Users\Diego\AppData\Local\Programs\Python\python38-32\lib\site-packages\pdfkit\pdfkit.py",line 156,in to_pdf
    raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Loading pages (1/6)
Warning: Javascript alert: Hola
QPainter::begin(): Returned false============================] 100%
Error: Unable to write to destination
Exit with code 1,due to unkNown error.

相关代码片段

pdfConf = pdfkit.configuration(wkhtmltopdf=os.path.join(
            self.__principalPath,"docs/web/PDF/wkhtmltopdf.exe"))

pdfOpti = {
            "window-status": "print","dpi": "90",# "quiet": "","page-size": "A4","footer-html": f"{url}/footer.html"
        }
try:
            return "E" if pdfkit.from_url(
                url=f"{url}/document.html",output_path=outputPath,configuration=pdfConf,options=pdfOpti) else "F"
except:
            return "F"

其他

上网查了一下,发现问题可能出在目标路径上。但我使用的是完整路径:C:\Users\Diego\Desktop\JAA.pdf

设置文件

import sys
from cx_Freeze import setup,Executable

build_exe_options = {"packages": ["ctypes","os","wx","json","threading","pdfkit"],"excludes": ["tkinter"]}

base = None
if sys.platform == "win32":
    base = "win32gui"

setup(name="App",version="0.1",description="",options={"build_exe": build_exe_options},executables=[Executable("main.py",base=base,icon="app.ico")])



解决方法

您做出的诊断是正确的(毕竟,Error: Unable to write to destination 非常简单)。

如果您可以创建输出文件,但创建的 EXE 文件不能 - 我们知道它不能 - 那么这意味着要么

  • 真正的目标路径在 EXE 运行时实际上并不存在。您认为正在写入给定的路径,但不知何故,EXE 试图在别处写入
  • EXE 没有创建文件的权限。

这可能是由多种原因造成的。出于安全原因,EXE 文件可能会在给定目录中输出,因此当您要求“C:\somefile”时,它实际上会尝试写入“%TEMP%/C:/somefile”。或者可能拒绝使用完整路径。

或者你可能需要用 Unix 语法编写文件(“C:/Users/...”而不是“C:\Users...”,因为例如“\Diego”被翻译成“0x0Diego”(带有回车前缀的“iego”)。

因此,您应该在 EXE 文件中插入一些代码来探索 EXE 看到的文件系统(这可能与您看到的文件系统不同!),和/或者尝试写入不同的路径,也许确实是 %TEMP%(权限应该足够)。