Print Dialog & Preview

Need to print something? Fancy with the print dialogue box? Technically, the printing process is easy with the javascript Windows Print Method window.print(). The print() method opens the Print Dialog Box, which lets the user to select preferred printing options. This tutorial will show how to print the specific content using the print() method.

Developer are recommended to create new page for the view and set the layout template to false in order remove the bootstrap template CSS (if any). Assumed that the developer needs to print something on document details, we need to create a new public function (print_virtual) as shown below. This public function contain controller to view the record and the layout has been set to FALSE. 

public function print_virtual($id = null) {
$this->layout = false;
if (!$this->Document->exists($id)) {
            throw new NotFoundException(__('Invalid Document'));
$options = array('conditions' => array('Lic.' . $this->Document->primaryKey => $id));
$this->set('document', $this->Document->find('first', $options));

Next, create new file in View/Documents and name it as print_virtual.ctp to create a template for the print page. Start the template with basic HTML5 tagging and in the body tag, include the window.print() as shown below:

<!DOCTYPE html>
			<meta charset="UTF-8">
						echo $this->Html->css('yourCSS');
						echo $this->Html->script('youScript');
<body onload="window.print()">
<!--Your Content Here-->
<!--Your Content Here-->
<!--Your Content Here-->
<!--Your Content Here-->
<!--Your Content Here-->

Create your own CSS for print_virtual page since we already removed the Boostratp CSS in the controller. To access the page, just create a simple button that give command to call the print_virtual page as shown below:

<?php echo $this->Html->link(__('<i class="fas fa-print"></i> Print'), array('action' => 'print_virtual', $document['Document']['id']), array('class' => 'btn bg-purple btn-flat btn-sm', 'escape' => false, 'target' => '_blank')); ?>

Expected output:

That all. Happy coding!