简体   繁体   中英

How to print a PDF in HTML

I would like to print a PDF in the browser, which was generated by my ASP.NET Core application. I have already tested countless articles and recommendations, but unfortunately there is no universal solution for all browsers.

Solutions like printing from an iframe doesn't work on iPadOS/iOS - for a document with multiple pages it prints only the first page (and the page is scaled incorrectly). The embed is not working anymore.

Print.js looks like that it is not maintained anymore and the owner has no activity on his account in the last year. Based on the issues on project, there are lot of bugs for mobile devices, which were not fixed anymore.

PDF.js from mozilla is also not working with the legacy version on iPadOS/iOS. Testing with the demo page has shown, that the printing often gets stuck. As mentioned in this ticket , the primary target is Firefox - they will not care much about issues on safari).

The only solution I can think of would be to print on desktop devices using an iframe and display the PDF on mobile devices, leaving it to the user to print it themselves. However, on iPadOS in particular, the default setting is "Request Desktop website" and Safari shows as macOS. So it is not possible to determine from the user agent whether it is an iPadOS.

Has anyone a solution for this?

<html>
<head>
    <title>Print PDF using Dynamic iFrame</title>
</head>
<body>
    <input type="button" id="bt" 
        onclick="print('../sample.pdf')" 
            value="Print PDF" />
</body>

<script>
    let print = (doc) => {
        let objFra = document.createElement('iframe');     // Create an IFrame.
        objFra.style.visibility = 'hidden';                // Hide the frame.
        objFra.src = doc;                   // Set source.

        document.body.appendChild(objFra);  // Add the frame to the web page.

        objFra.contentWindow.focus();       // Set focus.
        objFra.contentWindow.print();       // Print it.
    }
    
    // Using regular js features.
    
//     function print(doc) {
//         var objFra = document.createElement('iframe');
//         objFra.style.visibility = 'hidden';
//         objFra.src = doc;                  
//         document.body.appendChild(objFra);
//         objFra.contentWindow.focus();  
//         objFra.contentWindow.print();  
//     }
</script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM