如何解决python pdfkit中的“wkhtmltopdf报告错误:由于网络错误而退出并显示代码1:ProtocolUnknownError”

2023-12-30

我正在使用姜戈。这是views.py 中的代码。

def download_as_pdf_view(request, doc_type, pk):
    import pdfkit
    file_name = 'invoice.pdf'
    pdf_path = os.path.join(settings.BASE_DIR, 'static', 'pdf', file_name)

    template = get_template("paypal/card_invoice_detail.html")
    _html = template.render({})
    pdfkit.from_string(_html, pdf_path)

    return FileResponse(open(pdf_path, 'rb'), filename=file_name, content_type='application/pdf')

回溯如下。


[2022-09-05 00:56:35,785] ERROR [django.request.log_response:224] Internal Server Error: /paypal/download_pdf/card_invoice/MTE0Nm1vamlva29zaGkz/
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/project/app/paypal/views.py", line 473, in download_as_pdf_view
    pdfkit.from_string(str(_html), pdf_path)
  File "/usr/local/lib/python3.8/site-packages/pdfkit/api.py", line 75, in from_string
    return r.to_pdf(output_path)
  File "/usr/local/lib/python3.8/site-packages/pdfkit/pdfkit.py", line 201, in to_pdf
    self.handle_error(exit_code, stderr)
  File "/usr/local/lib/python3.8/site-packages/pdfkit/pdfkit.py", line 155, in handle_error
    raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: ProtocolUnknownError

[2022-09-05 00:56:35,797] ERROR [django.server.log_message:161] "GET /paypal/download_pdf/card_invoice/MTE0Nm1vamlva29zaGkz/ HTTP/1.1" 500 107486

这是工作文件。

pdfkit.from_url('https://google.com', 'google.pdf')

However pdfkit.from_string and pdfkit.from_file返回“协议未知错误”

请帮我!

Update

我打了这个代码。

    _html = '''<html><body><h1>Hello world</h1></body></html>'''
    pdfkit.from_string(_html), pdf_path)

效果很好。我将上面的html保存为sample.html。然后运行这段代码

  • 我添加了这个参数options={"enable-local-file-access": ""}
    _html = render_to_string('path/to/sample.html')
    pdfkit.from_string(str(_html), pdf_path, options={"enable-local-file-access": ""})

效果很好!由于“ProtocolUnknownError”错误消失了options={"enable-local-file-access": ""}.

因此,我将 HTML 文件路径更改为我真正想要使用的路径。

    _html = render_to_string('path/to/invoice.html')
    pdfkit.from_string(_html, pdf_path, options={"enable-local-file-access": ""})
    return FileResponse(open(pdf_path, 'rb'), filename=file_name, content_type='application/pdf')

它没有完成转换 pdf。当我逐行运行代码时。

stdout, stderr = result.communicate(input=input)不返回。

处理时间很长。


我解决了这个问题。有3个步骤可以解决这个问题。

  1. 您需要设置选项{"enable-local-file-access": ""}. pdfkit.from_string(_html, pdf_path, options={"enable-local-file-access": ""})

  2. pdfkit.from_string()无法从 URL 加载 css。是这样的。<link rel="stylesheet" href="https://path/to/style.css">css路径应该是绝对路径或者写style在同一个文件中。

  3. 如果 css 文件加载另一个文件。例如:字体文件。这将是ContentNotFoundError.

我的解决方案

我使用了这样的简单 css 文件。

body {
    font-size: 18px;
    padding: 55px;
}

h1 {
    font-size: 38px;
}

h2 {
    font-size: 28px;
}

h3 {
    font-size: 24px;
}

h4 {
    font-size: 20px;
}

table, th, td {
    margin: auto;
    text-align: center;
    border: 1px solid;
}

table {
    width: 80%;
}

.text-right {
    text-align: right;
}


.text-left {
    text-align: left;
}

.text-center {
    text-align: center;
}

此代码将最后一个 css 文件作为样式插入到同一 html 中。

import os

import pdfkit
from django.http import FileResponse
from django.template.loader import render_to_string

from paypal.models import Invoice
from website import settings


def download_as_pdf_view(request, pk):
    # create PDF from HTML template file with context.
    invoice = Invoice.objects.get(pk=pk)
    context = {
        # please set your contexts as dict.
    }
    _html = render_to_string('paypal/card_invoice_detail.html', context)
     # remove header
    _html = _html[_html.find('<body>'):]  

    # create new header
    new_header = '''<!DOCTYPE html>
    <html lang="ja">
    <head>
    <meta charset="utf-8"/>
    </head>
    <style>
'''
    # add style from css file. please change to your css file path.
    css_path = os.path.join(settings.BASE_DIR, 'paypal', 'static', 'paypal', 'css', 'invoice.css')
    with open(css_path, 'r') as f:
        new_header += f.read()
    new_header += '\n</style>'
    print(new_header)

    # add head to html
    _html = new_header + _html[_html.find('<body>'):]
    with open('paypal/sample.html', 'w') as f: f.write(_html)  # for debug

    # convert html to pdf
    file_name = 'invoice.pdf'
    pdf_path = os.path.join(settings.BASE_DIR, 'static', 'pdf', file_name)
    pdfkit.from_string(_html, pdf_path, options={"enable-local-file-access": ""})
    return FileResponse(open(pdf_path, 'rb'), filename=file_name, content_type='application/pdf')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何解决python pdfkit中的“wkhtmltopdf报告错误:由于网络错误而退出并显示代码1:ProtocolUnknownError” 的相关文章

  • 散景图只会弹出一个空白窗口

    所以我最近一直在尝试学习散景 一切都很顺利 但突然间 每当我尝试制作散景图时 浏览器就会显示一个空白页面 我没有收到任何错误代码 只有空白页 这是我几天前成功用来创建绘图的程序 我什至尝试加载几周前制作的 html 绘图文件 该文件在同事计
  • 如何打印前面有一定数量空格的整数?

    C has printf Xd Y 它只打印整数 X 并使其在控制台窗口上占据 Y 空格 例如 printf 3d 10 console 10 printf 5d 5 console 5 我如何在 python 3 中使用它 This pr
  • 按每个元素中出现的数字对字符串列表进行排序[重复]

    这个问题在这里已经有答案了 我有一个脚本 其目的是对不断下载到服务器上的空间数据集文件进行排序和处理 我的列表目前大致如下 list file t00Z wrff02 grib2 file t00Z wrff03 grib2 file t0
  • 学习Python中的解析器

    我记得我读过有关解析器的内容 您只需提供一些示例行 它就知道如何解析某些文本 它只是确定两条线之间的差异 以了解可变部分是什么 我以为它是用 python 写的 但我不确定 有谁知道那是什么图书馆吗 可能你的意思是模板制作器 http co
  • 在 Python 中延迟转置列表

    所以 我有一个延迟生成的可迭代的三元组 我试图弄清楚如何将其转换为 3 个可迭代对象 分别由元组的第一个 第二个和第三个元素组成 然而 我希望这件事能懒惰地完成 所以 举例来说 我希望 1 2 3 4 5 6 7 8 9 将变成 1 4 7
  • 创建 xyz 海拔数据的曲面图

    我正在尝试用 python 创建一座山的表面图 其中我有一些 xyz 数据 最终结果应该类似于that https i stack imgur com rKQV0 png 该文件的格式如下 616000 0 90500 0 3096 712
  • 我可以在 matplotlib 中的绘图左侧放置一个垂直颜色条吗?

    来自颜色条方法的 matplotlib 命令摘要 http matplotlib org api pyplot api html highlight colorbar matplotlib pyplot colorbar我知道关键字参数or
  • NumPy 数组与 SQLite

    我在 Python 中见过的最常见的 SQLite 接口是sqlite3 但是有什么东西可以很好地与 NumPy 数组或 rearray 配合使用吗 我的意思是 它可以识别数据类型 不需要逐行插入 并提取到 NumPy rec 数组中 有点
  • DataFrame.loc 的“索引器太多”

    我读了关于切片器的文档 http pandas pydata org pandas docs stable advanced html using slicers一百万次 但我从来没有理解过它 所以我仍在试图弄清楚如何使用loc切片Data
  • pandas 数据框的最大大小

    我正在尝试使用读取一个有点大的数据集pandas read csv or read stata功能 但我不断遇到Memory Errors 数据帧的最大大小是多少 我的理解是 只要数据适合内存 数据帧就应该没问题 这对我来说不应该是问题 还
  • 如何在Python中手动对数字列表进行排序?

    规格 Ubuntu 13 04 Python 3 3 1 背景 Python的初学者 遇到了这个 手动排序 问题 我被要求做的事情 让用户输入 3 个数值并将它们存储在 3 个不同的变量中 不使用列表或排序算法 手动将这 3 个数字从小到大
  • ImproperlyConfigured at / 不允许空静态前缀 - Django

    我正在使用 Django 上传 显示图像 该网站部署在 Heroku 上 下列的this https coderwall com p bz0sng教程我能够成功上传图像 但是 图像并未显示在模板中 然后我了解到我的 urls py 末尾应该
  • 使用 Python-VLC 的 PyInstaller:无属性“media_player_new”错误

    我使用 Python VLC 创建视频播放器 并使用 PyInstaller 在 Windows 10 计算机上生成可执行文件 最初 它给了我错误 Import Error Failed to load dynlib dll libvlc
  • 类变量:“类列表”与“类布尔值”[重复]

    这个问题在这里已经有答案了 我不明白以下示例的区别 一次类的实例可以更改另一个实例的类变量 而另一次则不能 示例1 class MyClass object mylist def add self self mylist append 1
  • 如何将 pandas DataFrame 转换为 TimeSeries?

    我正在寻找一种将 DataFrame 转换为 TimeSeries 而不拆分索引和值列的方法 有任何想法吗 谢谢 In 20 import pandas as pd In 21 import numpy as np In 22 dates
  • 如何在类型提示中定义元组或列表的大小

    有没有办法在参数的类型提示中定义元组或列表的大小 目前我正在使用这样的东西 from typing import List Optional Tuple def function name self list1 List Class1 if
  • 带 Qt 的菜单栏/系统托盘应用程序

    我是 Qt PyQt 的新手 我正在尝试制作一个应用程序 其功能将从菜单栏 系统托盘执行 这里展示了一个完美的例子 我找不到关于如何做到这一点的好资源 有人可以建议吗 Thanks 我认为您正在寻找与QMenu and QMainWindo
  • 如何创建简单的梯度下降算法

    我正在研究简单的机器学习算法 从简单的梯度下降开始 但在尝试用 python 实现它时遇到了一些麻烦 这是我试图重现的示例 我获得了有关房屋的数据 居住面积 以英尺为单位 和卧室数量 以及最终的价格 居住面积 英尺2 2104 卧室 3 价
  • 在Python中使用os.makedirs创建目录时出现权限问题

    我只是想处理上传的文件并将其写入工作目录中 该目录的名称是系统时间戳 问题是我想以完全权限创建该目录 777 但我不能 使用以下代码创建的目录755权限 def handle uploaded file upfile cTimeStamp
  • 如何使 Django 自定义管理命令参数不再需要?

    我正在尝试在 django 中编写自定义管理命令 如下所示 class Command BaseCommand def add arguments self parser parser add argument delay type int

随机推荐