简体   繁体   中英

Converting HTML to Output the body content to PDF

I'm looking for a way to convert the content in the body of a HTML webpage into a pdf when a button/image (link) is clicked.

I looked into jspdf and mPDF, but those solutions aren't quite producing what I want.

I'd like the entire contents between the body tags to be what a user can save as PDF - preferably with all of the styling (or as much as possible) preserved.

Shouldn't it be as simple as some code that essentially produces a screen shot of the page (although that might include unnecessary things such as URL bar, etc., and would likely render the PDF unsearchable in whatever storage set up that the user saves it to (but that isn't a priority right now)?

Summing up, I'm looking to have code (preferably some simple JS) that will achieve this goal of capturing content in the body tags, and saving it to a PDF at the user's command.

Thanks for attention and any insight :-)

try using dompdf, you can download it from here . If you get any error,

  1. Create the dompdf/lib/php-font-lib/classes/ directory
  2. Download this files
  3. In the zip file, take the contents of the src/FontLib/ folder and paste that into dompdf/lib/php-font-lib/classes/ folder

usage

require_once 'dompdf/dompdf_config.inc.php';
$html = "<html><body>HTML CODE
</body></html>";
$pdf = new DOMPDF();
$pdf->load_html($html);
$pdf->render();
$output = $pdf->output();
file_put_contents('output folder/file name.pdf', $output);
$pdf->stream('file name.pdf', array('Attachment' => 0));

make one php file which will contain code that will generate PDF file

ex. demo.php, this file will contain below code

require_once 'dompdf/dompdf_config.inc.php';
$html = file_get_contents('test.html');
$pdf = new DOMPDF();
$pdf->load_html($html);
$pdf->render();
$output = $pdf->output();
file_put_contents('output folder/file name.pdf', $output);
$pdf->stream('file name.pdf', array('Attachment' => 0));

now make html file which will contain what you want to desplay you in your pdf file

ex. test.html

<html>
<body>
    <h2>Hello</h2>
</body>
</html>

now, when you will open demo.php you will get pdf file with Hello text

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