The simple trick to print reports without opening a new tab page or open a PDF file in a new tab in the browser. Usually for web applications if you want to print reports, web programmers make PDF reports using class libraries such as FPDF which are then displayed in a new tab. The problem is how do we display the print dialog without opening the report page. Of course using javascript. Okay, just follow the short tutorial below.
I am not the first person to invent this technique, I get this way from the site stackoverflow.com. The basic concept of this way is browser will load the report pages that will be printed into a hidden iframe. hen on page report, will add JQuery code to open the print dialog.
Please see the following video preview of how this script works:
Table of Contents
Tutorial print report without open new page with Javascript
1. Create an index.php file and copy the following code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <!DOCTYPE html> <html> <head> <title>How to print report without open new tab in browser</title> </head> <body> <h1>How to print report without open new tab in browser</h1> <h2>seegatesite.com</h2> <button id="btn1">Invoice 1</button> <button id="btn2">Invoice 2</button> <h1>PRINT DIRECTLY REPORT PAGE FROM BROWSER</h1> <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <script> $("#btn1").click(function(){ $("#printabel").remove(); loadOtherPage1(); }); $("#btn2").click(function(){ $("#printabel").remove(); loadOtherPage2(); }); function loadOtherPage1() { $("<iframe id='printabel'>") .hide() .attr("src", "invoice.php") .appendTo("body"); } function loadOtherPage2() { $("<iframe id='printabel'>") .hide() .attr("src", "invoice2.php") .appendTo("body"); } </script> </body> </html> |
2. Create 2 pieces of files with names invoice.php, invoice2.php
3. Copy the following code and copy to the invoice.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html> <html> <head> <style type="text/css" media="print"> @page { size: auto; /* auto is the initial value */ margin: 0; /* this affects the margin in the printer settings */ padding: 30px; } body{ padding: 30px; } </style> </head> <body> <p>Hello world, print me please</p> <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <script> $(document).ready(function () { window.print(); }); </script> </body> </html> |
5. Please copy the invoice template from https://github.com/WesCossick and paste to the invoice2.php
6. Put index.php, invoice.php, invoice2.php in one folder
7. Open a browser and run index.php
Finished , please run it on your browser
References:
http://stackoverflow.com/questions/8240472/printing-a-web-page-using-just-url-and-without-opening-new-window
http://stackoverflow.com/questions/585254/how-to-remove-the-url-from-the-printing-page
THIS IS WORK FINE, BUT WITH CLEAN URL NOT WORKING PLEASE SUGGEST ME SOME GUIDELINES, THANKS