Print a webpage to pdf document using php
I can see there are a few options for doing this. My question is does any one know of a way that I can simply pass a php web page into a pdf creator and it outputs exactly the same as if it was viewed via a browser? Taking into consideration CSS, images and p开发者_StackOverflowhp functions etc.
Thanks
Think wkhtmltopdf is the answer you are looking for as it uses WebKit to render the webpage just like it would look in a browser and then converts it to a PDF. This saves you writing a load of PHP code to organise the layout of your PDF.
Details from their site:
Simple shell utility to convert html to pdf using the webkit rendering engine, and qt.
Searching the web, I have found several command line tools that allow you to convert a HTML-document to a PDF-document, however they all seem to use their own, and rather incomplete rendering engine, resulting in poor quality. Recently QT 4.4 was released with a WebKit widget (WebKit is the engine of Apples Safari, which is a fork of the KDE KHtml), and making a good tool became very easy.
- Convert web pages into PDF documents using webkit
- Adding headers and footers (static version only)
- TOC generation (static version only)
- Batch mode conversions
- (Linux) No longer requires an XServer to be running (however the X11 client libs must be installed)
For code and more information on wkhtmltopdf integration with PHP see https://github.com/aur1mas/Wkhtmltopdf
This is a two-part question really.
Making a screen shot of a web site into an image has many good answers on SO
To generate a PDF, use e.g. the fpdf library.
The fact that it's a PHP web page makes no difference. In order to create a PDF that looks like the web page should look, you need to render the page - this is what a web browser does when you visit it.
You'll need to use a web browser engine such as Gecko to produce the page layout, then export that as an image and stick it in a PDF. This can be done programatically.
There are php modules/classes for PDF generation, and there are ways of using CSS to better prepare a page for printing (to pdf).
PHP cannot 'see' the page as the browser sees it.
In more recent years chrome headless has drastically improved for rendering html to direct PDF output, there can be limitations so not always suited to everyone.
One UpToDate project to "Make PDF" on a PHP base is https://github.com/chrome-php/chrome
Requirements Requires PHP 7.3-8.2 and a chrome/chromium 65+ executable.
example usages
// get page title
$pageTitle = $page->evaluate('document.title')->getReturnValue();
// screenshot - Say "Cheese"!
精彩评论