Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print embedded PDF from browser with Javascript, HTML5, AngularJS

I'm loading a Base64 encoded PDF as a String into my JavaScript from my server. My client application is using AngularJS, HTML5.

My HTML looks like this:

<div id="printablePdfContainer">
  <iframe id="printablePdf" width="100%" height="100%"></iframe>
</div>

My JavaScript looks like this:

var pdfName = 'data:application/pdf;base64,' + data[0].PrintImage;
var embeddedPdf = document.getElementById('printablePdf');
embeddedPdf.setAttribute('src', pdfName);
$scope.printDocument(embeddedPdf);

My printDocument function looks like this:

$scope.printDocument = function() {
      var test = document.getElementById('printablePdf');
      if (typeof document.getElementById('printablePdf').print === 'undefined') {

        setTimeout(function(){$scope.printDocument();}, 1000);

      } else {

        var x = document.getElementById('printablePdf');
        x.print();
      }
    };

The printDocument function has been taken from a pre-existing question in stack overflow (Silent print an embedded PDF) which gives this as an answer to print an embedded PDF. However, this doesn't seem to work anymore. I'm always getting 'undefined' for the

typeof document.getElementById('printablePdf').print === 'undefined'

check. Seems like .print doesn't exist or something.

So, my question is this: How can I print an embedded PDF in HTML5, using JavaScript, and without opening a popup window?

like image 620
philhan Avatar asked Nov 12 '14 00:11

philhan


People also ask

How do I print a PDF in HTML?

Press the shortcut key Ctrl + P to print the page, and then in the print window that appears, change the Destination to Save as PDF or choose Adobe PDF as the printer.


2 Answers

Also answered here: Print Pdf from javascript embed tag

I'm going to post what I learned here after a lot of research for anyone in the future who might find this.

PDF's are displayed differently based on browser, browser version, browser configuration, and Operating System. There are a lot of variables so I'll talk about the most common situations here.

  • On all browsers I was unable to call any sort of print() method through Javascript, I was only able to use PdfActions. The OPENACTION would call print. I embedded these into the PDF using iText.

  • Chrome uses Adobe's viewer, which doesn't give access to any sort of print() method but does execute PdfActions embedded in the PDF. So you can embed an 'OpenAction' in a PDF and have the PDF call print whenever it's opened from any application that looks at those actions.

  • Firefox (above a certain version, all recent versions though) uses the Adobe viewer in Windows, which also recognizes PdfActions. However, in OSX it loses support for the Adobe viewer and switches to the baked in Firefox viewer (pdf.js). Which does not support PdfActions.

  • IE: I didn't really test much on IE. Mostly because I gave up on printing PDF's from Javascript after Firefox didn't work on OSX (a req. for me).

My PDF's were being generated by a server that I control so I ended up making service changes in my server and adding a get PNG service that generated a PNG based on the same markup that the PDF generation uses. Browsers handle images much better than PDFs, which I knew going in, but hoped that I would just be able to re-use the PDF generation service since it's used elsewhere in my code.

It doesn't answer the question, but it's all the information I have. My suggestion to anyone who might find this in the future: ditch PDF if possible in this case and go simpler. Otherwise, please update this question if you know how to call print() through Javascript in FF preview pdf viewer in OSX.

-Phil

like image 116
philhan Avatar answered Oct 20 '22 14:10

philhan


To print a base64 pdf you need to get around the fact that data URIs have no origin and are therefore blocked by modern browers.

See the note on the date URLs page on MDN: Data URLs.

In order to get around this have to either reference the same pdf directly, which is a no-no in this case, or convert the pdf to an object/ blob url.

See MDNs notes on creating an object/blob URL

function b64toBlob(b64Data, contentType) {
	var byteCharacters = atob(b64Data)

	var byteArrays = []

	for (let offset = 0; offset < byteCharacters.length; offset += 512) {
		var slice = byteCharacters.slice(offset, offset + 512),
			byteNumbers = new Array(slice.length)
		for (let i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i)
		}
		var byteArray = new Uint8Array(byteNumbers)

		byteArrays.push(byteArray)
	}

	var blob = new Blob(byteArrays, { type: contentType })
	return blob
}

var pdfObjectUrl = URL.createObjectURL(b64toBlob(data[0].PrintImage, 'application/pdf'))
var embeddedPdf = document.getElementById('printablePdf')
embeddedPdf.setAttribute('src', pdfObjectUrl)

// Then to print
embeddedPdf.contentWindow.print()

Once the data is inside an object URL the contentWindow will not be blocked by the browsers security. The print method will exist on the contentWindow of the iframe.

like image 32
Sam-Graham Avatar answered Oct 20 '22 15:10

Sam-Graham