Printing the current page to pdf using wkhtmltopdf

前端 未结 1 1636
一向
一向 2021-01-22 05:28

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

相关标签:
1条回答
  • 2021-01-22 06:31

    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'.

    0 讨论(0)
提交回复
热议问题