[javascript] How to send a pdf file directly to the printer using JavaScript?

How to send a PDF file directly to the printer using JavaScript?

I found two answers in a forum:

<embed src="vehinvc.pdf" id = "Pdf1" name="Pdf1" hidden>
<a onClick="document.getElementById('Pdf1').printWithDialog()" style="cursor:hand;">Print file</a>

and

<OBJECT id = "Pdf2" name="Pdf2" CLASSID="clsid:CA8A9780-280D-11CF-A24D-444553540000" WIDTH="364" HEIGHT="290">
     <PARAM NAME='SRC' VALUE="file.pdf">
</OBJECT>
<a onClick="document.Pdf2.printWithDialog()">Print file</a> 

But my problem is that it just works on IE, and doesnt work in Firefox or Chrome.

Is there any solution for this?

This question is related to javascript html pdf printing

The answer is


There are two steps you need to take.

First, you need to put the PDF in an iframe.

  <iframe id="pdf" name="pdf" src="document.pdf"></iframe>

To print the iframe you can look at the answers here:

Javascript Print iframe contents only

If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>:

  <iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>

the loader can look like this:

function isLoaded()
{
  var pdfFrame = window.frames["pdf"];
  pdfFrame.focus();
  pdfFrame.print();
}

This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).

I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.


a function to house the print trigger...

function printTrigger(elementId) {
    var getMyFrame = document.getElementById(elementId);
    getMyFrame.focus();
    getMyFrame.contentWindow.print();
}

an button to give the user access...

(an onClick on an a or button or input or whatever you wish)

<input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
an iframe pointing to your PDF...

<iframe id="iFramePdf" src="myPdfUrl.pdf" style="dispaly:none;"></iframe>

More : http://www.fpdf.org/en/script/script36.php


Try this: Have a button/link which opens a webpage (in a new window) with just the pdf file embedded in it, and print the webpage.

In head of the main page:

<script type="text/javascript">
function printpdf() 
{
myWindow=window.open("pdfwebpage.html");
myWindow.close;  //optional, to close the new window as soon as it opens
//this ensures user doesn't have to close the pop-up manually
}
</script>

And in body of the main page:

<a href="printpdf()">Click to Print the PDF</a>

Inside pdfwebpage.html:

<html>
<head>    
</head>

<body onload="window.print()">
<embed src="pdfhere.pdf"/>

</body>
</html>

<?php

$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];

if($browser_ver['browser'] == 'IE') {
?>

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
    html { height:100%; }
</style>
<script>
    function printIt(id) {
        var pdf = document.getElementById("samplePDF");
        pdf.click();
        pdf.setActive();
        pdf.focus();
        pdf.print();
    }
</script>
</head>

<body style="margin:0; height:100%;">

<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>


</body>
</html>

<?php
} else {
?>
<HTML>
<script Language="javascript">

function printfile(id) { 
    window.frames[id].focus();
    window.frames[id].print();
} 

</script>
<BODY marginheight="0" marginwidth="0">

<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>

<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">

</BODY>
</HTML>
<?php
}
?>

I think this Library of JavaScript might Help you:

It's called Print.js

First Include

<script src="print.js"></script>
<link rel="stylesheet" type="text/css" href="print.css">

It's basic usage is to call printJS() and just pass in a PDF document url: printJS('docs/PrintJS.pdf')

What I did was something like this, this will also show "Loading...." if PDF document is too large.

<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
    Print PDF with Message
</button>

However keep in mind that:

Firefox currently doesn't allow printing PDF documents using iframes. There is an open bug in Mozilla's website about this. When using Firefox, Print.js will open the PDF file into a new tab.


This is actually a lot easier using a dataURI, because you can just call print on the returned window object.

// file is a File object, this will also take a blob
const dataUrl = window.URL.createObjectURL(file);

// Open the window
const pdfWindow = window.open(dataUrl);

// Call print on it
pdfWindow.print();

This opens the pdf in a new tab and then pops the print dialog up.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to pdf

ImageMagick security policy 'PDF' blocking conversion How to extract table as text from the PDF using Python? Extract a page from a pdf as a jpeg How can I read pdf in python? Generating a PDF file from React Components Extract Data from PDF and Add to Worksheet How to extract text from a PDF file? How to download PDF automatically using js? Download pdf file using jquery ajax Generate PDF from HTML using pdfMake in Angularjs

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application