How do I get the browser to print a PDF version of a web page?

Consider a static HTML page as test.html , and the print version of the page is stored in test.pdf . How can I set my browser to download and print test.pdf instead of test.html when visitors tell their browser to print?

If this is not possible, how can I enter the print button (using JavaScript) on the HTML page to do this?

+6
source share
3 answers

You cannot force the browser to print another file other than what the user is requesting / viewing. It will be a security nightmare!

Option 1 (JS (on request) and HTML)

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

 <!-- 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> 
+8
source

You cannot capture the print command in the browser, but you can block the keyboard shortcuts (although I would not recommend it), so when the user types with ctrl/cmd + p , he redirects to PDF (or does something else). This is a mythical usability field, but you should probably just create a large link that says "Printable Version" and link it to a PDF (or a version of a page using printable CSS).

Other good options are to simply define some rules for the print media type in your CSS file, then browsers will apply them when the user prints without any hacks or javascript.

But since you asked that I created a small shortcut to capture the script for the print command. This is a bit complicated due to the mac command line 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 )); }​ 

It's pretty cool, but don't use it :)

+3
source

This is how the W3C tells you:

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

Remember, as far as I can tell, the browser does not support this one . Unfortunately.

+2
source

Source: https://habr.com/ru/post/910513/


All Articles