简体   繁体   中英

Printing the current page to pdf using wkhtmltopdf

Recently installed wkhtmltopdf. Was trying to capture the entire page in its current state, however, the below method seems to navigate to the initial state of that page without all the input fields that the user has entered.

PHP

shell_exec('wkhtmltopdf http://localhost/www/bolt/invoice.php invoice.pdf');

I was wondering if someone knew of an implementation of wkhtmltopdf that captures the current state of the page including any text entered in the text fields??

I appreciate any suggestions.

Many thanks in advance!

wkhtmltopdf hits the page independently of your current browsing session. If you hit it like that, you're going to get what anyone would see when they first go to your page. Probably what you want to do is save the current page using an output buffer, and then run wkhtmltopdf on the saved page. Here's some sample code:

sub.php

<?php
$documentTemplate = file_get_contents ("template.html");
foreach ($_POST as $key => $postVar)
{
    $documentTemplate = 
    preg_replace ("/name=\"$key\"/", "value=\"$postVar\"", $documentTemplate);
}
file_put_contents ("out.html", $documentTemplate);
shell_exec ("wkhtmltopdf out.html test.pdf");
?>

template.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <h1>This is a page</h1>
    <form action="sub.php" method="post" accept-charset="utf-8">
        My Test Field:
        <input type="text" name="test_field" value="">
        <input type="submit" value = "submit">
    </form>
</body>
</html>

Probably in the long run you should have some kind of base template that both pages would use, and one have some markers like value='%valueOfThisVariable%' in your input fields that you can replace with blanks when you present the fields to the user, and fill with the user data when you create the page that you want to write to pdf. Right now it's just going through and replacing all the name='this_name' with value='this_name->value'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM