6

I've generated a document with pdf.js and it shows correctly. I'don't have print button. How to add the button to allow users to print it ? I was using Chrome.

Dejo
  • 2,078
  • 3
  • 26
  • 38

3 Answers3

7

Try using the javascript-function window.print();, which opens the print-dialog.

You will have to add an button to your html, which triggers the command - its not possible within the pdf.

For this reason, you will need an iFrame, and use something like this:

function printIt() {
    var wnd = window.open('http://your-pdf-url');
    wnd.print();
}

<input type="button" value="Print" onclick=printIt()>

window.print() wouldn't work, because it would also print the surrounding html.

EDIT:

From your comment, I now know, that you want to print the content of a canvas-element - which is much easier.

You don't need an iframe, you can put the button on the same page, and use window.print();.

In order to only print the canvas-element, and to hide the surroundings (like the button), you can use css-Syntax like this:

@media print
{    
    .no-print, .no-print *
    {
        display: none !important;
    }
}

@media print specifies css-code, which only applies for a webpage, if it gets printed. If you now asign the class .no-print to everything except the canvas-element, only your pdf will be printed.

You can also use this css-code, if it's easier:

@media print
{    
    *
    {
        display: none;
    }
    canvas 
    {
        display: inline;
    }
}
maja
  • 17,250
  • 17
  • 82
  • 125
  • Thanks, but the problem is that I'don't have url for the pdf. I got the base64 representation of pdf from server, converted it to array and created pdf.js document from it. – Dejo Jan 30 '14 at 19:27
  • 1
    @Dejo: You are accessing your pdf via the browser - so there must be an url, which starts generating the pdf. If you put it into an iframe, you can also use `var wnd = document.getElementById("myframe").contentWindow;` – maja Jan 30 '14 at 19:33
  • Thx, but it would not be so easy, because it is rendered in the canvas element. – Dejo Jan 30 '14 at 20:15
  • then use window.print() and a few line of print-only css to hide the non-pdf stuff. – dandavis Jan 30 '14 at 20:16
  • not working, It's showing a blank page. Shouldn't be waiting for the pdf to load? – Anenth Sep 28 '17 at 12:52
1

If you want to keep everything in line and mess with jquery as little as possible you can try to something like:

<a href="#PATH_TO_PDF.pdf" target="_blank"  onclick="window.print()"> print PDF </a>
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
-2

I have been looking for a solution to this for so long and then I landed on this JS plugin:

http://printjs.crabbly.com/

It works like a charm!

Jonathan Roy
  • 461
  • 5
  • 4