Googlebot
Googlebot

Reputation: 15683

How can I force the browser to print a PDF version of a webpage?

Consider a static HTML page as test.html, and a printable version of the page has been stored in test.pdf. How can I guide browser to load and print test.pdf instead of test.html when visitors tell their browser to print?

If it's not possible how can I introduce a print button (using JavaScript) within the HTML page to do so?

Upvotes: 9

Views: 19413

Answers (3)

Ky -
Ky -

Reputation: 32153

Here is the way the W3C says you should:

<LINK REL="alternate" HREF="/path/to/PDFVersion.pdf" TYPE="application/pdf" MEDIA="print" TITLE="PDF version" />

Mind you, as far as I can tell, no browser currently supports this. Sorry.

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108520

You can’t hijack the print command in the browser, but you can hijack keyboard shortcuts (although I wouldn’t recommend it) so that when the user prints using ctrl/cmd + p, it redirects to a PDF (or does something else). This is a usability minefield though, you should probably just create a big link that says "Printable version" and link it to the PDF (or a version of the page that uses a print-friendly CSS).

Another good options is to simply define some rules for the print media type in your CSS file, then the browsers will apply those when the user prints, without any hacks or javascript at all.

But since you asked I created a small shortcut hijacking script for the print command. It‘s kind of tricky because of the mac command key, but something like:

var cmd = false;

$(document).on('keydown', function(e) {

    if(detectMacCommand(e.which)) {
        cmd = true;
        return;
    }

    // now detect print (ctr/cmd + p)
    if ( e.which == 80 && ( e.ctrl || cmd ) ) {
        e.preventDefault();
        alert('redirect to PDF');
    }

}).on('keyup', function(e) {

    if(detectMacCommand(e.which)) {
        cmd = false;
        return;
    }

});

function detectMacCommand(key) {
    return ( $.browser.mozilla && key == 224 ||
             $.browser.opera   && key == 17 ||
             $.browser.webkit  && ( key == 91 || key == 93 ));
}
​

That’s pretty cool, but don’t use it :)

Upvotes: 3

James Hill
James Hill

Reputation: 61842

You cannot force the browser to print a different file than the user is requesting/viewing. That would be a security nightmare!

Option 1 (JS (as requested) & HTML)

I suggest creating a printable version link on your site that will direct the user to the .pdf (opening the PDF in a new window would be preferable).

<!-- JS -->
<script type="text/javascript">
    function LoadPrintableVersion() {
        window.open("Test.pdf");
    }
</script>

<!-- HTML -->
<span id="spanPrintableVersion" onclick="LoadPrintableVersion()">
    Printable Version
</span>

Option 2 (pure html)

<a href="test.pdf" target="_blank">Printable Version</a>

Upvotes: 8

Related Questions