我最近开始学习Python,我想将现有的html文件转换为pdf文件。这很奇怪,但 pdfkit 似乎是 python pdf 文档的唯一库。
import pdfkit
pdfkit.from_file("C:\\Users\\user\Desktop\\table.html", "out.pdf")
出现错误:
OSError: No wkhtmltopdf executable found: "b''"
如何在Windows上正确配置这个lib以使其工作?我看不懂:(
看起来你需要安装wkhtmltopdf。对于 Windows,安装程序可以在 https://wkhtmltopdf.org/downloads.html
找到另请查看这个人的帖子,他也遇到了同样的问题:Can't create pdf using python PDFKIT Error : " No wkhtmltopdfexecutablefound:"
我找到了可行的解决方案。 如果你想将文件转换为 pdf 格式,请不要使用 python 来实现此目的。 您需要将 DOMPDF 库包含到本地/删除服务器上的 php 脚本中。像这样的东西:
<?php
// include autoloader
require_once 'vendor/autoload.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
if (isset($_POST['html']) && !empty($_POST['html'])) {
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($_POST['html']);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
$dompdf->stream();
} else {
exit();
}
然后在 python 脚本中,您可以将 html 或任何内容发布到服务器并获取生成的 pdf 文件作为响应。像这样的东西:
import requests
url = 'http://example.com/html2pdf.php'
html = '<h1>hello</h1>'
r = requests.post(url, data={'html': html}, stream=True)
f = open('converted.pdf', 'wb')
f.write(r.content)
f.close()