-->

Is there any wkhtmltopdf option to convert html te

2019-04-06 07:39发布

问题:

I recently stumbled on wkhtmltopdf and have found it to be an excellent tool for on-the-fly conversion from html to pdf in the browser.

A typical usage (in Windows) would go:

wkhtmltopdf.exe --some-option "<div>Some html <b>formatted</b> text</div>" www.host.com/page_to_print.html file.pdf

My question is: Is there an option to use <html><head></head><body><h1>This is a header</h1></body></html> in place of www.host.com/page_to_print.html?

Thanks for any help.

回答1:

Yes and no.

There is no native support, but you can pipe content into wkhtmltopdf using the windows command prompt pipe. Try this command:

echo "<h3>magical ponies</h3>" | wkhtmltopdf.exe - test.pdf

This reads like "echo this text, output it's stdout (standard out stream) to wkhtmltopdf stdin (standard in stream)". The dash - in the wkhtmltopdf command means that it takes it's input from stdin and not a file.

You could also echo HTML into a file, feed that file to wkhtmltopdf and delete that file inside a script.

Currently the best resources for documentation are http://wkhtmltopdf.org/usage/wkhtmltopdf.txt and http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf_0.10.0_rc2-doc.html - if you read through them, there is no mention of inputting a string of HTML like that.



回答2:

Just a correction to the answer provided by Nenotlep. As Jigar noted (in a comment to Nenotlep's answer), Nenotlep's command results in quotation marks preceding and following the actual text. On my system (Windows 10) this command is the correct solution:

echo ^<h3^>magical ponies^</h3^> | "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" - test.pdf

The echo command needs no quotation marks - but, if you do not put the text between quotation marks, the < and > characters need to be escaped (by ^).

Another way to try out is writing the text into a temporary file, which - on Windows - might even be faster as some sources state:

echo ^<h3^>magical ponies^</h3^> > temp.txt
"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" - test.pdf < temp.txt

(This can also be written in one line: just put an & between the two commands.)



回答3:

Using PowerShell, you can do it like this:

$html = "<h1>Magical Ponies</h1><p>Once upon a time in Horseland, there was a band of miniat
ure creatures..."
$html | .\wkhtmltopdf.exe - C:\temp\test.pdf

Just make sure you're running the code from within the \bin\ directory of wkhtmltopdf, otherwise, you'd have to provide a full path to the executable.



回答4:

In addition to the answer provided by pp. If you prefer not to escape the < > characters, you can also do the following:

echo | set /p="<h3>Magical ponies</h3>" | wkhtmltopdf - test.pdf