Advanced Silent PDF Printing with Tray, Paper Size, Rotation & Pages Range Settings from Javascript
Product JSPrintManager Published 01/15/2019 Updated 11/05/2026 Author Neodynamic
Overview
In this walkthrough, you'll learn how to silently print PDF files from Javascript directly to the client printer without displaying a print dialog. You'll be able to print PDF files to the Default client printer as well as to any other installed printer at the client machine with advanced settings like Tray Name, Paper Size, Print Rotation, Pages Range and more! This solution works with any popular browser like Chrome, Edge, Firefox & Safari on Windows, Linux, Raspberry Pi & Mac systems!
Try JSPrintManager Online Demo!
Step-by-step
- Be sure you install in your dev machine JSPrintManager (JSPM) (Available for Windows, Linux, Raspberry Pi & Mac)
This small app must be installed on each client that will print from your website!
Since Chrome 142, browsers ask the user to allow Local Network Access the first time your website connects to the JSPrintManager App. - By using your favorite Web Development IDE or Text Editor, create a new HTML file like index.html
Copy/paste the following code snippets:HTML Code
<div style="text-align:center"> <h1>Advanced PDF Printing from Javascript</h1> <hr /> <fieldset> <legend>PDF file to print</legend> <label>Local file: <input type="file" id="localFile" accept=".pdf" /></label> <p>or...</p> <label>File URL (must include the file extension): <input type="text" id="fileUrl" size="50" value="https://neodynamic.com/temp/LoremIpsum.pdf" /></label> </fieldset> <fieldset> <legend>Target printer</legend> <label>Printer: <select id="lstPrinters" onchange="showSelectedPrinterInfo();"></select></label> <label>Tray: <select id="lstPrinterTrays"></select></label> <label>Paper: <select id="lstPrinterPapers"></select></label> <label>or custom paper: <input type="text" id="txtCustomPaper" placeholder="Custom.4x6in" title="Custom.WIDTHxHEIGHTin, Custom.WIDTHxHEIGHTcm or Custom.WIDTHxHEIGHTmm" /></label> <label>Media type: <select id="lstPrinterMediaTypes"></select></label> </fieldset> <fieldset> <legend>PDF printing settings</legend> <label>Rotation (clockwise): <select id="lstPrintRotation"> <option>None</option> <option>Rot90</option> <option>Rot180</option> <option>Rot270</option> </select> </label> <label>Pages range: <input type="text" id="txtPagesRange" placeholder="1,2,3,10-15" /></label> <label>Page sizing: <select id="lstPageSizing"> <option>None</option> <option>Fit</option> </select> </label> <label>Scale (%): <input type="number" id="txtPrintScale" value="100" min="1" max="300" /></label> <label><input type="checkbox" id="chkAutoRotate" /> Auto rotate</label> <label><input type="checkbox" id="chkAutoCenter" /> Auto center</label> <label><input type="checkbox" id="chkPrintInReverseOrder" /> Print in reverse order</label> <label><input type="checkbox" id="chkPrintAnnotations" /> Print annotations <em>(Windows only)</em></label> <label><input type="checkbox" id="chkPrintAsGrayscale" /> Print as grayscale <em>(Windows only)</em></label> <label>Duplex: <select id="lstDuplex"> <option value="">None</option> <option value="Driver">Driver duplex (if supported by the printer)</option> <option value="Manual">Manual duplex</option> </select> </label> <label>Driver duplex mode: <select id="lstDuplexMode"> <option>Default</option> <option>DuplexLongEdge</option> <option>DuplexShortEdge</option> </select> </label> </fieldset> <br /> <button type="button" onclick="doPrinting();">Print Now...</button> </div>Script References
- Download JSPrintManager.js
- Copy all of these *.js files to the same folder where your html page is located and then add the following script references to your page.
<!-- JSPrintManager.js (download it or install it with: npm install jsprintmanager) --> <script src="JSPrintManager.js"></script>Script Code
- Copy & paste the following script code into your page file:
<script> var clientPrinters = null; // Start the connection with the JSPrintManager Client App JSPM.JSPrintManager.auto_reconnect = true; JSPM.JSPrintManager.start(); JSPM.JSPrintManager.WS.onStatusChanged = function () { if (jspmWSStatus()) { // get the client installed printers with their trays, papers & media types JSPM.JSPrintManager.getPrintersInfo(JSPM.PrintersInfoLevel.Basic, '', JSPM.PrinterIcon.None).then(function (printersList) { clientPrinters = printersList; fillSelect('lstPrinters', clientPrinters, function (p) { return p.name; }); showSelectedPrinterInfo(); }); } }; // Do printing... function doPrinting() { if (jspmWSStatus()) { var printer = clientPrinters[document.getElementById('lstPrinters').selectedIndex]; // Create a ClientPrintJob var cpj = new JSPM.ClientPrintJob(); // Set the installed printer with the tray and paper to use var myPrinter = new JSPM.InstalledPrinter(printer.name, false, val('lstPrinterTrays'), val('txtCustomPaper') || val('lstPrinterPapers')); myPrinter.mediaType = val('lstPrinterMediaTypes'); /* // How to map PDF pages to printer trays (Windows only) var pageTrays = []; pageTrays.push(new JSPM.PageTrayItem(1, -1, 'Manual Feed')); pageTrays.push(new JSPM.PageTrayItem(2, -1, 'Tray 1')); myPrinter.pageTrays = pageTrays; */ // Driver duplex (only if the printer supports it) if (val('lstDuplex') == 'Driver' && printer.duplex === true) myPrinter.duplex = JSPM.DuplexMode[val('lstDuplexMode')]; cpj.clientPrinter = myPrinter; // Set the PDF file and its printing settings var myPdfFile = getFileToPrint(JSPM.PrintFilePDF, 'myFileToPrint.pdf'); myPdfFile.printRotation = JSPM.PrintRotation[val('lstPrintRotation')]; myPdfFile.printRange = val('txtPagesRange'); myPdfFile.pageSizing = JSPM.Sizing[val('lstPageSizing')]; myPdfFile.printScale = parseInt(val('txtPrintScale')); myPdfFile.printAnnotations = checked('chkPrintAnnotations'); myPdfFile.printAutoRotate = checked('chkAutoRotate'); myPdfFile.printAutoCenter = checked('chkAutoCenter'); myPdfFile.printInReverseOrder = checked('chkPrintInReverseOrder'); myPdfFile.printAsGrayscale = checked('chkPrintAsGrayscale'); myPdfFile.manualDuplex = (val('lstDuplex') == 'Manual'); cpj.files.push(myPdfFile); // Trace the print job status (optional) traceJob(cpj); // Send the print job to the client printer cpj.sendToClient(); } } // Check the connection status with the JSPrintManager Client App function jspmWSStatus() { var status = JSPM.JSPrintManager.websocket_status; if (status == JSPM.WSStatus.Open) { return true; } else if (status == JSPM.WSStatus.WaitingForUserResponse) { console.info('Waiting for the user to allow this website (JSPrintManager dialog or browser Local Network Access prompt)...'); } else if (status == JSPM.WSStatus.Blocked) { alert('JSPrintManager has blocked this website!'); } else if (status == JSPM.WSStatus.NotInstalled || status == JSPM.WSStatus.Closed) { alert('JSPrintManager Client App is not installed or not running! Download it from https://neodynamic.com/downloads/jspm'); } else if (status == JSPM.WSStatus.CertificateError) { alert('A TLS/SSL certificate error prevented the connection with JSPrintManager Client App.'); } else if (status == JSPM.WSStatus.ConnectionError) { alert('A network error (e.g. a firewall) prevented the connection with JSPrintManager Client App.'); } return false; } // Show the trays, papers and media types supported by the selected printer function showSelectedPrinterInfo() { var printer = clientPrinters[document.getElementById('lstPrinters').selectedIndex]; fillSelect('lstPrinterTrays', printer.trays); fillSelect('lstPrinterPapers', printer.papers); fillSelect('lstPrinterMediaTypes', printer.mediaTypes); // driver duplex is available only if the printer supports it document.getElementById('lstDuplex').options[1].disabled = (printer.duplex !== true); } // Create the file to print from the selected local file or from the specified URL function getFileToPrint(FileClass, urlFileName) { var localFile = document.getElementById('localFile').files[0]; if (localFile) return new FileClass(localFile, JSPM.FileSourceType.BLOB, localFile.name, 1); return new FileClass(val('fileUrl'), JSPM.FileSourceType.ExternalURL, urlFileName, 1); } // Log the print job status updates (optional) function traceJob(cpj) { cpj.onUpdated = function (data) { console.info(data); }; cpj.onFinished = function (data) { console.info(data); }; cpj.onError = function (data, isCritical) { console.error(data); }; } // Helpers function val(id) { return document.getElementById(id).value; } function checked(id) { return document.getElementById(id).checked; } // Fill a <select> element with a list of items function fillSelect(id, items, getText) { var select = document.getElementById(id); select.innerHTML = ''; for (var i = 0; i < items.length; i++) { var text = getText ? getText(items[i]) : items[i]; select.add(new Option(text, text)); } } </script> - That's it! Run your website and test it. Click on Print Now... to print the PDF file without print dialog with the specified settings and silently.
Useful? Share it!
| Tweet |
|
Related Articles
Advanced Silent Multipage TIF Printing with Tray, Paper Size, Rotation & Pages Range Settings from JavascriptHow to silently print multiple images with duplex setting from Javascript
How to trace Print Job Status from Javascript
Silent Word DOC Printing with Duplex, Reverse & Pages Range Settings from Javascript
Need help? Contact Support
We provide best-in-class customer service and support directly from members of our dev team! If we are available when you contact us, you will get a response in few minutes; otherwise the maximum turnaround is 24hs in most cases.