2017-06-20 109 views
0

我最近开始学习python,我想将现有的html文件转换为pdf文件。这很奇怪,但pdfkit似乎是python的pdf文档的唯一库。发生Python在Windows上配置pdfkit

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

错误: OSError: No wkhtmltopdf executable found: "b''"

如何在Windows正确配置this lib,使其工作?我不能让它:(

+0

pdfkit不是从Python生成PDF的唯一选项。 [Sphinx](http://www.sphinx-doc.org)是一个非常强大的文档生成器,可以使用LaTeX,[rinohtype](http://www.mos6581.org/rinohtype/)或[rst2pdf]输出PDF (http://rst2pdf.ralsina.me)(还有许多其他格式,还有一些可以从HTML生成PDF的其他Python软件包,例如[Weasyprint](http://weasyprint.org)) –

回答

0

看起来你需要安装wkhtmltopdf。对于Windows,安装程序可以在https://wkhtmltopdf.org/downloads.html

发现同样被这家伙,谁是有同样的问题,检查后:Can't create pdf using python PDFKIT Error : " No wkhtmltopdf executable found:"

+0

谢谢。上次我尝试通过pip安装wkhtmltopdf并且它没有工作,经过大量尝试,这些代码行(正好)解决了问题'config = pdfkit.configuration(wkhtmltopdf =“C:\\ Program Files \\ wkhtmltopdf \\ bin \\ wkhtmltopdf.exe“) pdfkit.from_url('http://google.com','out.pdf',configuration = config)'IT is SO WIRED!你甚至可以用python编码吗? :) –

+0

哦,不。 Pdfkit工作非常糟糕。经过一些测试后发现一些html文件不能被pdfkit lib正确转换。作为一个输出它给空表等等......为什么没有工作的PDF处理? –

0

我找到工作的解决方案 如果你想将文件转换为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()