Print a pdf without visually opening it

前端 未结 2 492
一向
一向 2021-01-31 03:40

The thing I want to build is that by clicking a button I want to trigger the print of a PDF file, but without opening it.

+-----------+
| Print PDF |
+----------         


        
2条回答
  •  醉酒成梦
    2021-01-31 04:12

    UPDATE: This link details an elegant solution that involves editing the page properties for the first page and adding an action on Page Open. Works across all browsers (as browsers will execute the JavaScript placed in the actions section). Requires Adobe Acrobat Pro.


    It seems 2016 brings no new advancements to the printing problem. Had a similar issue and to make the printing cross-browser I solved it using PDF.JS but had to make a one-liner addition to the source (they ask you to build upon it in anyways).

    The idea:

    • Download the pre-built stable release from https://mozilla.github.io/pdf.js/getting_started/#download and add the "build" and "web" folders to the project.
    • The viewer.html file is what renders out PDFs with a rich interface and contains print functionality. I added a link in that file to my own JavaScript that simply triggers window.print() after a delay.

    The link added to viewer:

        
        
        
    
    

    The autoPrint.js javascript:

    (function () {
        function printWhenReady() {
            if (PDFViewerApplication.initialized) {
                window.print();
            }
            else {
                window.setTimeout(printWhenReady, 3000);
            }
        };
    
        printWhenReady();
    })();
    
    • I could then put calls to viewer.html?file= in the src of an iframe and hide it. Had to use visibility, not display styles because of Firefox: