Python 在 Windows 上配置 pdfkit [英] Python configure pdfkit on windows

查看:55
本文介绍了Python 在 Windows 上配置 pdfkit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习python,我想将现有的html文件转换为pdf文件.很奇怪,但 pdfkit 似乎是 python pdf 文档的唯一库.

I started to learn python recently and I want to convert existing html file to pdf file. It is very strange, but pdfkit seems to be the only lib for pdf docs for python.

import pdfkit
pdfkit.from_file("C:\\Users\\user\Desktop\\table.html", "out.pdf")

出现错误:OSError:找不到 wkhtmltopdf 可执行文件:b''"

如何在 Windows 上正确配置这个库以使其正常工作?我无法理解:(

How to configure this lib properly on windows to make it work? I can't get it :(

推荐答案

我找到了可行的解决方案.如果您想将文件转换为 pdf 格式,请不要为此使用 python.您需要在本地/删除服务器上的 php 脚本中包含 DOMPDF 库.像这样:

I found working solution. If you want to convert files to pdf format just don't use python for this purpose. You need to include DOMPDF library into your php script on your local/remove server. Something like this:

<?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 文件作为响应.像这样:

Then in your python script you can post your html or whatever content to your server and get generated pdf file as a response. Something like this:

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()

这篇关于Python 在 Windows 上配置 pdfkit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆