开发者

wkhtmltopdf: download a PDF to the user's HD

开发者 https://www.devze.com 2023-02-10 22:09 出处:网络
how to download automaticaly (to the user\'s 开发者_JAVA技巧HD) a pdf generated using wkhtmltopdf or snappy? You know.. a user click a link (\"Download this page as PDF\") and download the pdf to his/

how to download automaticaly (to the user's 开发者_JAVA技巧HD) a pdf generated using wkhtmltopdf or snappy? You know.. a user click a link ("Download this page as PDF") and download the pdf to his/her HD.

Regards

Javi


PHP: there are better ways of getting wkhtmltopdf working with PHP, however, I like to be able to print out what my command line is so that I can debug the resulting page that bit more easily. It is not just about code, but about having margins and other page details correct. Here the wkhtmltopdf is a binary in the web root, margins are set to zero, the background is turned off:

$do_it=$_SERVER["DOCUMENT_ROOT"]."/wkhtmltopdf --dpi 600 -B 0 -L 0 -R 0 -T 0 --no-background http://".$_SERVER['SERVER_NAME']."/".$filename." ".$_SERVER["DOCUMENT_ROOT"]."/".$pdf_url;
//var_dump($do_it); // uncomment to see your wkhtmltopdf parameters...
$whatever=passthru($do_it);
header('Content-disposition: attachment; filename='.$pdf_url);
header('Content-type: application/pdf');
readfile($pdf_url);

I don't think much comes back when running passthru when it comes to error messages, however, it does run whatever you send it. As for header, it is important to set the content type to PDF or else the browser will not know what to do with it.

The Snappy website actually also has a ready made example just for this.

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('http://www.github.com');


Here's how I do it in RoR

filename = "MyNew.pdf"
fullpath = "#{RAILS_ROOT}/tmp/charts/#{filename}"
# system issues a shell command
system "/usr/local/bin/wkhtmltopdf \"http://localhost/page/to/pdf?download=t\" #{fullpath}"

send_data(File.read(fullpath), :type => 'application/pdf', :filename => filename, :disposition => "attachment;filename=\"#{filename}\"")
0

精彩评论

暂无评论...
验证码 换一张
取 消