Print HTML from PHP directly to the client printer without print dialog or silent mode
Product WebClientPrint for PHP Published 09/27/2017 Updated 10/28/2020 Author Neodynamic
Overview
In this walkthrough, you'll learn how to print HTML content from a PHP website directly to the client printer without displaying a print dialog i.e. very silently. You'll be able to print HTML content to the Default client printer as well as to any other installed printer at the client machine. This solution works with any browser on Windows OS like IE, Edge, Chrome, Firefox, Opera & Safari as well as on Linux, Raspberry Pi & Mac systems!
The HTML content that we'll print is a simple business card made by pure HTML and CSS markup containing an image. The HTML Card looks like follows:
John Doe
Architect & Engineer
The HTML printing is performed by following these tasks:
- Step 1 The HTML content that needs to be printed is converted to a PNG image by leveraging html2canvas utility from pure Javascript code.
IMPORTANT! html2canvas is not supported by all browsers. Please refer to Browser Compatibility topic.NOTE: It's important that you specify inline style instead of CSS classes to specifying things like Font Family as well as is a good idea to use Data URI to display images in PNG or JPEG formats.
- Step 2 Once the HTML content was rendered to a PNG image by using html2canvas, we'll store it at the server side directory of our website through an AJAX POST in order we can get it later when we need to create the ClientPrintJob object.
- Step 3 Now once the PNG image was stored at server side directory, we'll invoke WebClientPrint Processor (WCPP) for starting printing it.
Requirements
Development/Server-side
WebClientPrint 6.0 for PHP (or greater)
PHP 5.3+
jQuery 1.10+
html2canvas 0.4+
Client-side
WebClientPrint Processor 6.0 for Windows, Linux, Raspberry Pi & Mac
Follow up these steps
- Download & install WebClientPrint for PHP
- Create a new PHP Website naming it PrintHtmlCardSample
- Now follow up the instructions for each PHP Classic or PHP MVC/Laravel:
• Create a new folder called wcpcache at your project's root folder
• Copy the WebClientPrint.php to your project's root folder
Creating Controllers
• Create a new PHP file at root folder and name it WebClientPrintController.php and then copy/paste the following code:
<?php //********************************* // IMPORTANT NOTE // 1. In this sample we store users related stuff (like // the list of printers and whether they have the WCPP // client utility installed) in the wcpcache folder BUT // you can change it to another different storage (like a DB)! // which will be required in Load Balacing scenarios // // 2. If your website requires user authentication, then // THIS FILE MUST be set to ALLOW ANONYMOUS access!!! // //********************************* include 'WebClientPrint.php'; use Neodynamic\SDK\Web\WebClientPrint; //IMPORTANT SETTINGS: //=================== //Set wcpcache folder RELATIVE to WebClientPrint.php file //FILE WRITE permission on this folder is required!!! WebClientPrint::$wcpCacheFolder = getcwd().'/wcpcache/'; if (file_exists(WebClientPrint::$wcpCacheFolder) == false) { //create wcpcache folder $old_umask = umask(0); mkdir(WebClientPrint::$wcpCacheFolder, 0777); umask($old_umask); } //=================== // Clean built-in Cache // NOTE: Remove it if you implement your own cache system WebClientPrint::cacheClean(30); //in minutes // Process WebClientPrint Request $urlParts = parse_url($_SERVER['REQUEST_URI']); if (isset($urlParts['query'])){ $query = $urlParts['query']; parse_str($query, $qs); //get session id from querystring if any $sid = NULL; if (isset($qs[WebClientPrint::SID])){ $sid = $qs[WebClientPrint::SID]; } try{ //get request type $reqType = WebClientPrint::GetProcessRequestType($query); if($reqType == WebClientPrint::GenPrintScript || $reqType == WebClientPrint::GenWcppDetectScript){ //Let WebClientPrint to generate the requested script //Get Absolute URL of this file $currentAbsoluteURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://"; $currentAbsoluteURL .= $_SERVER["SERVER_NAME"]; if($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") { $currentAbsoluteURL .= ":".$_SERVER["SERVER_PORT"]; } $currentAbsoluteURL .= $_SERVER["REQUEST_URI"]; $currentAbsoluteURL = substr($currentAbsoluteURL, 0, strrpos($currentAbsoluteURL, '?')); ob_start(); ob_clean(); header('Content-type: text/javascript'); echo WebClientPrint::generateScript($currentAbsoluteURL, $query); return; } else if ($reqType == WebClientPrint::ClientSetWcppVersion) { //This request is a ping from the WCPP utility //so store the session ID indicating this user has the WCPP installed //also store the WCPP Version if available if(isset($qs[WebClientPrint::WCPP_SET_VERSION]) && strlen($qs[WebClientPrint::WCPP_SET_VERSION]) > 0){ WebClientPrint::cacheAdd($sid, WebClientPrint::WCP_CACHE_WCPP_VER, $qs[WebClientPrint::WCPP_SET_VERSION]); } return; } else if ($reqType == WebClientPrint::ClientSetInstalledPrinters) { //WCPP Utility is sending the installed printers at client side //so store this info with the specified session ID WebClientPrint::cacheAdd($sid, WebClientPrint::WCP_CACHE_PRINTERS, strlen($qs[WebClientPrint::WCPP_SET_PRINTERS]) > 0 ? $qs[WebClientPrint::WCPP_SET_PRINTERS] : ''); return; } else if ($reqType == WebClientPrint::ClientSetInstalledPrintersInfo) { //WCPP Utility is sending the installed printers at client side with detailed info //so store this info with the specified session ID //Printers Info is in JSON format $printersInfo = $_POST['printersInfoContent']; WebClientPrint::cacheAdd($sid, WebClientPrint::WCP_CACHE_PRINTERSINFO, $printersInfo); return; } else if ($reqType == WebClientPrint::ClientGetWcppVersion) { //return the WCPP version for the specified Session ID (sid) if any ob_start(); ob_clean(); header('Content-type: text/plain'); echo WebClientPrint::cacheGet($sid, WebClientPrint::WCP_CACHE_WCPP_VER); return; } else if ($reqType == WebClientPrint::ClientGetInstalledPrinters) { //return the installed printers for the specified Session ID (sid) if any ob_start(); ob_clean(); header('Content-type: text/plain'); echo base64_decode(WebClientPrint::cacheGet($sid, WebClientPrint::WCP_CACHE_PRINTERS)); return; } else if ($reqType == WebClientPrint::ClientGetInstalledPrintersInfo) { //return the installed printers with detailed info for the specified Session ID (sid) if any ob_start(); ob_clean(); header('Content-type: text/plain'); echo base64_decode(WebClientPrint::cacheGet($sid, WebClientPrint::WCP_CACHE_PRINTERSINFO)); return; } } catch (Exception $ex) { throw $ex; } }
• Create a new PHP file and name it StoreImageFileController.php and then copy/paste the following code:
<?php //generate random file name $randFileName = 'MyFile'.uniqid(); //save image file on root website folder file_put_contents($randFileName, $_POST['base64ImageContent']); //return file name back to client ob_start(); ob_clean(); header('Content-type: text/plain'); echo $randFileName; ob_end_flush(); exit();
• Create a new PHP file and name it PrintHtmlCardController.php and then copy/paste the following code:
<?php include 'WebClientPrint.php'; use Neodynamic\SDK\Web\WebClientPrint; use Neodynamic\SDK\Web\DefaultPrinter; use Neodynamic\SDK\Web\InstalledPrinter; use Neodynamic\SDK\Web\PrintFile; use Neodynamic\SDK\Web\ClientPrintJob; // Process request // Generate ClientPrintJob? only if clientPrint param is in the query string $urlParts = parse_url($_SERVER['REQUEST_URI']); if (isset($urlParts['query'])) { $rawQuery = $urlParts['query']; parse_str($rawQuery, $qs); if (isset($qs[WebClientPrint::CLIENT_PRINT_JOB])) { $useDefaultPrinter = ($qs['useDefaultPrinter'] === 'checked'); $printerName = urldecode($qs['printerName']); $filePath = $qs['imageFileName']; //create a temp file name for our image file... //Because we know the Card size is 3.125in x 4.17in, we can specify //it through a special format in the file name (see http://goo.gl/upaazT) so the //printing output size is honored; otherwise the output will be sized to Page Width & Height //specified by the printer driver default setting $fileName = 'MyFile'.uniqid().'-PW=3.125-PH=4.17'.'.png'; //Create a ClientPrintJob obj that will be processed at the client side by the WCPP $cpj = new ClientPrintJob(); //Create a PrintFile object with the PNG file $cpj->printFile = new PrintFile($filePath, $fileName, null); if ($useDefaultPrinter || $printerName === 'null'){ $cpj->clientPrinter = new DefaultPrinter(); }else{ $cpj->clientPrinter = new InstalledPrinter($printerName); } //Send ClientPrintJob back to the client ob_start(); ob_clean(); header('Content-type: application/octet-stream'); echo $cpj->sendToClient(); ob_end_flush(); exit(); } }
Creating Web Pages
• The default page is for detecting whether the client machine has the WebClientPrint Processor (WCPP) Utility installed. Create a new PHP page and name it index.php. Then copy/paste the following code:
<?php session_start(); include 'WebClientPrint.php'; use Neodynamic\SDK\Web\WebClientPrint; ?> <!DOCTYPE html> <html> <head> <title>Detecting WebClientPrint Processor...</title> <style> body{font: 13px 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif;} </style> </head> <body> <div id="msgInProgress"> <div id="mySpinner" style="width:32px;height:32px"></div> <br /> Detecting WCPP utility at client side... <br /> Please wait a few seconds... <br /> </div> <div id="msgInstallWCPP" style="display:none;"> <h3>#1 Install WebClientPrint Processor (WCPP)!</h3> <p> <strong>WCPP is a native app (without any dependencies!)</strong> that handles all print jobs generated by the <strong>WebClientPrint PHP component</strong> at the server side. The WCPP is in charge of the whole printing process and can be installed on <strong>Windows, Linux, Raspberry Pi & Mac!</strong> </p> <p> <a href="http://www.neodynamic.com/downloads/wcpp/" target="_blank">Download and Install WCPP from Neodynamic website</a><br /> </p> <h3>#2 After installing WCPP...</h3> <p> <a href="PrintHtmlCard.php">You can go and test the printing page</a> </p> </div> <!-- Add Reference to jQuery at Google CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript"> var wcppPingTimeout_ms = 60000; //60 sec var wcppPingTimeoutStep_ms = 500; //0.5 sec function wcppDetectOnSuccess(){ // WCPP utility is installed at the client side // redirect to WebClientPrint sample page // get WCPP version var wcppVer = arguments[0]; if(wcppVer.substring(0, 1) == "6") window.location.href = "PrintHtmlCard.php"; else //force to install WCPP v6.0 wcppDetectOnFailure(); } function wcppDetectOnFailure() { // It seems WCPP is not installed at the client side // ask the user to install it $('#msgInProgress').hide(); $('#msgInstallWCPP').show(); } </script> <?php //Get Absolute URL of this page $currentAbsoluteURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://"; $currentAbsoluteURL .= $_SERVER["SERVER_NAME"]; if($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") { $currentAbsoluteURL .= ":".$_SERVER["SERVER_PORT"]; } $currentAbsoluteURL .= $_SERVER["REQUEST_URI"]; //WebClientPrinController.php is at the same page level as WebClientPrint.php $webClientPrintControllerAbsoluteURL = substr($currentAbsoluteURL, 0, strrpos($currentAbsoluteURL, '/')).'/WebClientPrintController.php'; // Create WCPP detection script echo WebClientPrint::createWcppDetectionScript($webClientPrintControllerAbsoluteURL, session_id()); ?> </body> </html>
• Add a new PHP page and name it PrintHtmlCard.php. Copy/paste the following code:
<?php session_start(); include 'WebClientPrint.php'; use Neodynamic\SDK\Web\WebClientPrint; ?> <!DOCTYPE html> <html> <head> <title>How to directly Print HTML Content without Preview or Printer Dialog</title> </head> <body> <!-- Store User's SessionId --> <input type="hidden" id="sid" name="sid" value="<?php echo session_id(); ?>" /> <h2>Print HTML Card</h2> <p>This card is 300px x 400px ⇔ 3.125in x 4.17in (300/96 and 400/96 respectivelly)</p> <div id="card" style="width: 300px; height:400px; border-radius: 10px; background-color:antiquewhite;"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfMAAAHyCAMAAADIjdfcAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAYBQTFRFM22C0LKTQX6aSEhIRoSiSoyuMGp+0cjRRICdNXCFQH2ZP3uWs7OwJ11xhoeGR2VzSIalSousPnqVSoqrOHOKz6jORoalPHmT/ubPR4enR4WkRYSjPXqUoYt2VVVVQ4GeOnaPSYqs5NbjOXSNS4ytrGeqcXBvdIeENnGIRVZdRUVFSl9o/vDjOVll4sWlRXSKLlpp/dy8sKqXN1FaUVFR8cqjO3eQTExMPnuWk5uYbZKet5yCR4OgRElL0b2jW4mboKWiRm19TIOa/dKoT4efQk1STI2vUVtf////Rn6apFiiU1dZSIioQHePQoCcSYmpRYKgRYOhQX+bQHSLRIKgQ4GdRIOhSIinQHyXPHiROnWNPnmTSImqO3iRQn+cQoCdSImpSYqqOnWOQX6ZSYioQ4CdOXSMuoK56ebpjnxs8/Pz5r2eUFVXc2hdXl5f/dWuXFZRUE1L+fT58+rz/vz5Z19X/vjxQXCEXHp+OHSOak5pSH+bRnuUklWRgW6AU0pTDizfXgAAHjtJREFUeNrs3etjE8d2APAxohKxPRZ140DBXqe6tYikGBljX9coMiiKasVcqHmlUFJyb9Nb2WBjDAFze932X69k+aHHrnYeZ2bOked8SfIFVvvLOXNmZneW/TPC+JvI+MeT+NuI+Ie/C40//ennn3/+4x//pTP+0BX/+Yd/bcbf98Xldnx1FEf/eq03Ll4/jYtH8eg0fjqKp+3YPInmv892x7Oj+POlS5d++eVhZ7w6icftuNAVv452xvPuGOuJycnJ6WZMTjJPft7IMZp7crPk08yTnzdyfOae3DQ5O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ud50LaNs3tB8EG7f1d3KSZkPJL9SCAgm+qr0IRNdjfsEvTQXb+JYLLmzFk4r0QPFpdd24/6a2kRNakBnseRX3P0InelaStk8o1XaHd6teWHzOPIDh79Co7hPqC3DtZu4LMU0FzePI3fYwmkleqBhvkVvoibTxLE4cpctnFaip1TNGxql3WWaCzdxLI7csfmSdnGfkjWf0yjtS05vlmATx+LIXwQB0UR/rWi+kSLZwYkP6CyO/MCxufoC7Liq+f8STXMJ84HkLyoB1USfUFqGa8b/EU1z0SaOxZC/SAdkE31Lzfx/qKa5aBPHYshfrAdkE31cZel1Y+O/qaa5aBP3/wIMAI6prfGsFSkIAAAAAElFTkSuQmCC" alt="Avatar" style="width:100%;border-radius: 10px 10px 0 0;"> <div style="padding: 2px 16px;"> <h3 style="font:bold 20px Arial">John Doe</h3> <p style="font:normal 14px Arial">Architect & Engineer</p> </div> </div> <div> <label class="checkbox"> <input type="checkbox" id="useDefaultPrinter" /> <strong>Print to Default printer</strong> or... </label> </div> <div id="loadPrinters"> Click to load and select one of the installed printers! <br /> <input type="button" onclick="javascript:jsWebClientPrint.getPrinters();" value="Load installed printers..." /> <br /><br /> </div> <div id="installedPrinters" style="visibility:hidden"> <label for="installedPrinterName">Select an installed Printer:</label> <select name="installedPrinterName" id="installedPrinterName"></select> </div> <script type="text/javascript"> var wcppGetPrintersTimeout_ms = 60000; //60 sec var wcppGetPrintersTimeoutStep_ms = 500; //0.5 sec function wcpGetPrintersOnSuccess() { // Display client installed printers if (arguments[0].length > 0) { var p = arguments[0].split("|"); var options = ''; for (var i = 0; i < p.length; i++) { options += '<option>' + p[i] + '</option>'; } $('#installedPrinters').css('visibility', 'visible'); $('#installedPrinterName').html(options); $('#installedPrinterName').focus(); $('#loadPrinters').hide(); } else { alert("No printers are installed in your system."); } } function wcpGetPrintersOnFailure() { // Do something if printers cannot be got from the client alert("No printers are installed in your system."); } </script> <br /> <input id="printBtn" type="button" style="font-size:18px" value="Print HTML Card..." /> // Add Reference to jQuery at Google CDN <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> <?php //Get Absolute URL of this page $currentAbsoluteURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://"; $currentAbsoluteURL .= $_SERVER["SERVER_NAME"]; if($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") { $currentAbsoluteURL .= ":".$_SERVER["SERVER_PORT"]; } $currentAbsoluteURL .= $_SERVER["REQUEST_URI"]; //WebClientPrinController.php is at the same page level as WebClientPrint.php $webClientPrintControllerAbsoluteURL = substr($currentAbsoluteURL, 0, strrpos($currentAbsoluteURL, '/')).'/WebClientPrintController.php'; //PrintHtmlCardController.php is at the same page level as WebClientPrint.php $printHtmlCardControllerAbsoluteURL = substr($currentAbsoluteURL, 0, strrpos($currentAbsoluteURL, '/')).'/PrintHtmlCardController.php'; //Specify the ABSOLUTE URL to the WebClientPrintController.php and to the file that will create the ClientPrintJob object echo WebClientPrint::createScript($webClientPrintControllerAbsoluteURL, $printHtmlCardControllerAbsoluteURL, session_id()); ?> // REFERENCE to html2canvas utility https://github.com/niklasvh/html2canvas <script src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-rc.5/html2canvas.min.js" type="text/javascript"></script> // HTML Printing Logic <script> $(document).ready(function(){ $("#printBtn").click(function () { //1. generate an image of HTML content through html2canvas utility html2canvas(document.getElementById('card'), { scale: 5 }).then(function (canvas) { var b64Prefix = "data:image/png;base64,"; var imgBase64DataUri = canvas.toDataURL("image/png"); var imgBase64Content = imgBase64DataUri.substring(b64Prefix.length, imgBase64DataUri.length); //2. save image base64 content to server-side Application Cache $.ajax({ type: "POST", url: 'StoreImageFileController.php', data: { base64ImageContent : imgBase64Content}, success: function (imgFileName) { //alert("The image file: " + imgFileName + " was created at server side. Continue printing it..."); //2. Print the stored image file specifying the created file name jsWebClientPrint.print('useDefaultPrinter=' + $('#useDefaultPrinter').attr('checked') + '&printerName=' + $('#installedPrinterName').val() + '&imageFileName=' + imgFileName); } }); }); }); }); </script> </body> </html>
WebClientPrint Setup for Laravel 8+
• Create a new folder called WebClientPrint under app folder of your project
• Copy the WebClientPrint.php to that WebClientPrint folder
• Create a new folder called wcpcache under the WebClientPrint folder
Creating Controllers
• Add a new Controller to your project and name it WebClientPrintController.php. Then copy/paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; //********************************* // IMPORTANT NOTE // 1. In this sample we store users related stuff (like // the list of printers and whether they have the WCPP // client utility installed) in the wcpcache folder BUT // you can change it to another different storage (like a DB)! // which will be required in Load Balacing scenarios // // 2. If your website requires user authentication, then // THIS FILE MUST be set to ALLOW ANONYMOUS access!!! // // 3. EXCLUDE this Controller from CSRF Protection // Ref https://laravel.com/docs/5.5/csrf#csrf-excluding-uris //********************************* //Includes WebClientPrint classes include_once(app_path() . '\WebClientPrint\WebClientPrint.php'); use Neodynamic\SDK\Web\WebClientPrint; class WebClientPrintController extends Controller { public function processRequest(Request $request){ //IMPORTANT SETTINGS: //=================== //Set wcpcache folder RELATIVE to WebClientPrint.php file //FILE WRITE permission on this folder is required!!! WebClientPrint::$wcpCacheFolder = app_path() . '/WebClientPrint/wcpcache/'; //=================== // Clean built-in Cache // NOTE: Remove it if you implement your own cache system WebClientPrint::cacheClean(30); //in minutes //get session id from querystring if any $sid = NULL; if ($request->has(WebClientPrint::SID)){ $sid = $request->input(WebClientPrint::SID); } try{ //get query string from url $query = substr($request->fullUrl(), strpos($request->fullUrl(), '?')+1); //get request type $reqType = WebClientPrint::GetProcessRequestType($query); if($reqType == WebClientPrint::GenPrintScript || $reqType == WebClientPrint::GenWcppDetectScript){ //Let WebClientPrint to generate the requested script //Get Absolute URL of this file $currentAbsoluteURL = substr($request->fullUrl(), 0, strrpos($request->fullUrl(), '?')); // Return WebClientPrint's javascript code return response(WebClientPrint::generateScript($currentAbsoluteURL, $query)) ->header('Content-Type', 'text/javascript'); } else if ($reqType == WebClientPrint::ClientSetWcppVersion) { //This request is a ping from the WCPP utility //so store the session ID indicating this user has the WCPP installed //also store the WCPP Version if available if($request->has(WebClientPrint::WCPP_SET_VERSION) && strlen($request->input(WebClientPrint::WCPP_SET_VERSION)) > 0){ WebClientPrint::cacheAdd($sid, WebClientPrint::WCP_CACHE_WCPP_VER, $request->input(WebClientPrint::WCPP_SET_VERSION)); } return; } else if ($reqType == WebClientPrint::ClientSetInstalledPrinters) { //WCPP Utility is sending the installed printers at client side //so store this info with the specified session ID WebClientPrint::cacheAdd($sid, WebClientPrint::WCP_CACHE_PRINTERS, strlen($request->input(WebClientPrint::WCPP_SET_PRINTERS)) > 0 ? $request->input(WebClientPrint::WCPP_SET_PRINTERS) : ''); return; } else if ($reqType == WebClientPrint::ClientSetInstalledPrintersInfo) { //WCPP Utility is sending the installed printers at client side with detailed info //so store this info with the specified session ID //Printers Info is in JSON format $printersInfo = $request->input('printersInfoContent'); WebClientPrint::cacheAdd($sid, WebClientPrint::WCP_CACHE_PRINTERSINFO, $printersInfo); return; } else if ($reqType == WebClientPrint::ClientGetWcppVersion) { //return the WCPP version for the specified Session ID (sid) if any return response(WebClientPrint::cacheGet($sid, WebClientPrint::WCP_CACHE_WCPP_VER)) ->header('Content-Type', 'text/plain'); } else if ($reqType == WebClientPrint::ClientGetInstalledPrinters) { //return the installed printers for the specified Session ID (sid) if any return response(base64_decode(WebClientPrint::cacheGet($sid, WebClientPrint::WCP_CACHE_PRINTERS))) ->header('Content-Type', 'text/plain'); } else if ($reqType == WebClientPrint::ClientGetInstalledPrintersInfo) { //return the installed printers with detailed info for the specified Session ID (sid) if any return response(base64_decode(WebClientPrint::cacheGet($sid, WebClientPrint::WCP_CACHE_PRINTERSINFO))) ->header('Content-Type', 'text/plain'); } } catch (Exception $ex) { throw $ex; } } }
• Exclude WebClientPrintAPIController & StoreImageFileController (we'll be creating it later) from CSRF Protection by editing app\Http\Middleware\VerifyCsrfToken.php so it looks like the following code:
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'WebClientPrintController', 'StoreImageFileController' ]; }
• Edit the HomeController so it looks like the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Session; //Includes WebClientPrint classes include_once(app_path() . '\WebClientPrint\WebClientPrint.php'); use Neodynamic\SDK\Web\WebClientPrint; class HomeController extends Controller { public function index(){ $wcppScript = WebClientPrint::createWcppDetectionScript(action('WebClientPrintController@processRequest'), Session::getId()); return view('home.index', ['wcppScript' => $wcppScript]); } public function printHtmlCard(){ $wcpScript = WebClientPrint::createScript(action('WebClientPrintController@processRequest'), action('PrintHtmlCardController@printFile'), Session::getId()); return view('home.printHtmlCard', ['wcpScript' => $wcpScript]); } }
• Add a new Controller and name it StoreImageFileController and paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Session; class StoreImageFileController extends Controller { public function createFile(Request $request){ //generate random file name $randFileName = 'MyFile'.uniqid(); //save image file on root website folder file_put_contents($randFileName, base64_decode($request->input('base64ImageContent'))); //return file name back to client return response($randFileName) ->header('Content-Type', 'text/plain'); } }
• Add a new Controller and name it PrintHtmlCardController and paste the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; //********************************* // IMPORTANT NOTE // ============== // If your website requires user authentication, then // THIS FILE MUST be set to ALLOW ANONYMOUS access!!! // //********************************* //Includes WebClientPrint classes include_once(app_path() . '\WebClientPrint\WebClientPrint.php'); use Neodynamic\SDK\Web\WebClientPrint; use Neodynamic\SDK\Web\Utils; use Neodynamic\SDK\Web\DefaultPrinter; use Neodynamic\SDK\Web\InstalledPrinter; use Neodynamic\SDK\Web\PrintFile; use Neodynamic\SDK\Web\ClientPrintJob; use Session; class PrintHtmlCardController extends Controller { public function printFile(Request $request){ if ($request->exists(WebClientPrint::CLIENT_PRINT_JOB)) { $useDefaultPrinter = ($request->input('useDefaultPrinter') === 'checked'); $printerName = urldecode($request->input('printerName')); $filePath = $request->input('imageFileName'); //create a temp file name for our image file... //Because we know the Card size is 3.125in x 4.17in, we can specify //it through a special format in the file name (see http://goo.gl/upaazT) so the //printing output size is honored; otherwise the output will be sized to Page Width & Height //specified by the printer driver default setting $fileName = 'MyFile'.uniqid().'-PW=3.125-PH=4.17'.'.png'; //Create a ClientPrintJob obj that will be processed at the client side by the WCPP $cpj = new ClientPrintJob(); //Create a PrintFile object with the PNG file $cpj->printFile = new PrintFile($filePath, $fileName, null); if ($useDefaultPrinter || $printerName === 'null'){ $cpj->clientPrinter = new DefaultPrinter(); }else{ $cpj->clientPrinter = new InstalledPrinter($printerName); } //Send ClientPrintJob back to the client return response($cpj->sendToClient()) ->header('Content-Type', 'application/octet-stream'); } } }
Creating/Editing Views
• Edit the resources / views / layouts / app.blade.php file so it looks like follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>WebClientPrint for PHP</title> </head> <body> <div> @yield('body') </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> @yield('scripts') </body> </html>
• The default View is for detecting whether the client machine has the WebClientPrint Processor (WCPP) Utility installed. Edit the resources / views / home / index.blade.php file and add the folowing section to the BODY:
@extends('layouts.app') @section('body') <div id="msgInProgress"> <h3>Detecting WCPP utility at client side...</h3> <h3>Please wait a few seconds...</h3> <br /> </div> <div id="msgInstallWCPP" style="display:none;"> <h3>#1 Install WebClientPrint Processor (WCPP)!</h3> <p> <strong>WCPP is a native app (without any dependencies!)</strong> that handles all print jobs generated by the <strong>WebClientPrint for PHP component</strong> at the server side. The WCPP is in charge of the whole printing process and can be installed on <strong>Windows, Linux, Mac & Raspberry Pi!</strong> </p> <p> <a href="//www.neodynamic.com/downloads/wcpp/" target="_blank" >Download and Install WCPP from Neodynamic website</a><br /> </p> <h3>#2 After installing WCPP...</h3> <p> <a href="{{action('HomeController@printHtmlCard')}}" >You can go and test the printing page...</a> </p> </div> @endsection @section('scripts') <script type="text/javascript"> var wcppPingTimeout_ms = 60000; //60 sec var wcppPingTimeoutStep_ms = 500; //0.5 sec function wcppDetectOnSuccess(){ // WCPP utility is installed at the client side // redirect to WebClientPrint sample page // get WCPP version var wcppVer = arguments[0]; if(wcppVer.substring(0, 1) == "6") window.location.href = '{{action('HomeController@printHtmlCard')}}'; else //force to install WCPP v6.0 wcppDetectOnFailure(); } function wcppDetectOnFailure() { // It seems WCPP is not installed at the client side // ask the user to install it $('#msgInProgress').hide(); $('#msgInstallWCPP').show(); } </script> {!! // Register the WCPP Detection script code // The $wcpScript was generated by HomeController@index $wcppScript; !!} @endsection
• Add a new View with the following name and under such folders: resources / views / home / printHtmlCard.blade.php Then, copy/paste the folowing code:
@extends('layouts.app') @section('body') <h2>Print HTML Card</h2> <p>This card is 300px x 400px ⇔ 3.125in x 4.17in (300/96 and 400/96 respectivelly)</p> <div id="card" style="width: 300px; height:400px; border-radius: 10px; background-color:antiquewhite;"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfMAAAHyCAMAAADIjdfcAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAYBQTFRFM22C0LKTQX6aSEhIRoSiSoyuMGp+0cjRRICdNXCFQH2ZP3uWs7OwJ11xhoeGR2VzSIalSousPnqVSoqrOHOKz6jORoalPHmT/ubPR4enR4WkRYSjPXqUoYt2VVVVQ4GeOnaPSYqs5NbjOXSNS4ytrGeqcXBvdIeENnGIRVZdRUVFSl9o/vDjOVll4sWlRXSKLlpp/dy8sKqXN1FaUVFR8cqjO3eQTExMPnuWk5uYbZKet5yCR4OgRElL0b2jW4mboKWiRm19TIOa/dKoT4efQk1STI2vUVtf////Rn6apFiiU1dZSIioQHePQoCcSYmpRYKgRYOhQX+bQHSLRIKgQ4GdRIOhSIinQHyXPHiROnWNPnmTSImqO3iRQn+cQoCdSImpSYqqOnWOQX6ZSYioQ4CdOXSMuoK56ebpjnxs8/Pz5r2eUFVXc2hdXl5f/dWuXFZRUE1L+fT58+rz/vz5Z19X/vjxQXCEXHp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MGzRLu9SAzkTIn1j/BaDFXcZ8jsJBA5oDOhMgf+niLGeNG55VXobratzfUkpzmQGdCZC/TAe0En1LwzyjdzyYmw5Oxzyc/GUhoJXo45Ln+4Y2cROkSrvMNgsTIH/p4ifodHFZ1WW4TnON/+n2XdyvBSXzKPIDJ+ZgxV3OvAFQ2p3cr3kV8yjyKxUnvwGsuKekzOf0Szv2L/KwePIr6YBaor9VXYY7a9wDUh2c1KoMiye/sh6QS/SMunmGZmmXaOJYPPkVR79B53XFVXXzKd3SvuTodi1Img8iP3BlHsAU94aC+Wt6aS7exLFYclfDud50LaNs3tB8EG7f1d3KSZkPJL9SCAgm+qr0IRNdjfsEvTQXb+JYLLmzFk4r0QPFpdd24/6a2kRNakBnseRX3P0InelaStk8o1XaHd6teWHzOPIDh79Co7hPqC3DtZu4LMU0FzePI3fYwmkleqBhvkVvoibTxLE4cpctnFaip1TNGxql3WWaCzdxLI7csfmSdnGfkjWf0yjtS05vlmATx+LIXwQB0UR/rWi+kSLZwYkP6CyO/MCxufoC7Liq+f8STXMJ84HkLyoB1USfUFqGa8b/EU1z0SaOxZC/SAdkE31Lzfx/qKa5aBPHYshfrAdkE31cZel1Y+O/qaa5aBP3/wIMAI6prfGsFSkIAAAAAElFTkSuQmCC" alt="Avatar" style="width:100%;border-radius: 10px 10px 0 0;"> <div style="padding: 2px 16px;"> <h3 style="font:bold 20px Arial">John Doe</h3> <p style="font:normal 14px Arial">Architect & Engineer</p> </div> </div> <div> <label class="checkbox"> <input type="checkbox" id="useDefaultPrinter" /> <strong>Print to Default printer</strong> or... </label> </div> <div id="loadPrinters"> Click to load and select one of the installed printers! <br /> <input type="button" onclick="javascript:jsWebClientPrint.getPrinters();" value="Load installed printers..." /> <br /><br /> </div> <div id="installedPrinters" style="visibility:hidden"> <label for="installedPrinterName">Select an installed Printer:</label> <select name="installedPrinterName" id="installedPrinterName"></select> </div> <script type="text/javascript"> var wcppGetPrintersTimeout_ms = 60000; //60 sec var wcppGetPrintersTimeoutStep_ms = 500; //0.5 sec function wcpGetPrintersOnSuccess() { // Display client installed printers if (arguments[0].length > 0) { var p = arguments[0].split("|"); var options = ''; for (var i = 0; i < p.length; i++) { options += '<option>' + p[i] + '</option>'; } $('#installedPrinters').css('visibility', 'visible'); $('#installedPrinterName').html(options); $('#installedPrinterName').focus(); $('#loadPrinters').hide(); } else { alert("No printers are installed in your system."); } } function wcpGetPrintersOnFailure() { // Do something if printers cannot be got from the client alert("No printers are installed in your system."); } </script> <br /> <input id="printBtn" type="button" style="font-size:18px" value="Print HTML Card..." /> @endsection @section('scripts') {!! // Register the WebClientPrint script code // The $wcpScript was generated by PrintHtmlCardController@index $wcpScript; !!} <!-- REFERENCE to html2canvas utility https://github.com/niklasvh/html2canvas --> <script src="https://github.com/niklasvh/html2canvas/releases/download/v0.5.0-beta4/html2canvas.min.js" type="text/javascript"></script> <!-- HTML Printing Logic --> <script> $(document).ready(function(){ $("#printBtn").click(function () { //1. generate an image of HTML content through html2canvas utility html2canvas($('#card')).then(function (canvas) { var b64Prefix = "data:image/png;base64,"; var imgBase64DataUri = canvas.toDataURL("image/png"); var imgBase64Content = imgBase64DataUri.substring(b64Prefix.length, imgBase64DataUri.length); //2. save image base64 content to server-side Application Cache $.ajax({ type: "POST", url: "{{action('StoreImageFileController@createFile')}}", data: { base64ImageContent : imgBase64Content}, success: function (imgFileName) { //alert("The image file: " + imgFileName + " was created at server side. Continue printing it..."); //2. Print the stored image file specifying the created file name jsWebClientPrint.print('useDefaultPrinter=' + $('#useDefaultPrinter').attr('checked') + '&printerName=' + $('#installedPrinterName').val() + '&imageFileName=' + imgFileName); } }); }); }); }); </script> @endsection
• Finally, add the following routes to routes / web.php
Route::get('/', 'HomeController@index'); Route::get('home', 'HomeController@index'); Route::get('home/index', 'HomeController@index'); Route::get('home/printHtmlCard', 'HomeController@printHtmlCard'); Route::any('PrintHtmlCardController', 'PrintHtmlCardController@printFile'); Route::any('StoreImageFileController', 'StoreImageFileController@createFile'); Route::any('WebClientPrintController', 'WebClientPrintController@processRequest');
• Edit the app\Providers\RouteServiceProvider.php and uncommet the line
protected $namespace = 'App\\Http\\Controllers';
- That's it! Run your website and test it.