Python configure pdfkit on windows

2019-04-03 04:28发布

问题:

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

An error occurs: OSError: No wkhtmltopdf executable found: "b''"

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

回答1:

It looks like you need to install wkhtmltopdf. For windows, the installer can be found at https://wkhtmltopdf.org/downloads.html

Also check out a post by this guy, who is having the same problem: Can't create pdf using python PDFKIT Error : " No wkhtmltopdf executable found:"



回答2:

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

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