簡體   English   中英

如何在HTML中打印一個PDF

[英]How to print a PDF in HTML

我想在瀏覽器中打印一個 PDF,它是由我的 ASP.NET Core 應用程序生成的。 我已經測試了無數文章和建議,但遺憾的是沒有適用於所有瀏覽器的通用解決方案。

iframe打印等解決方案在 iPadOS/iOS 上不起作用 - 對於包含多頁的文檔,它僅打印第一頁(並且頁面縮放不正確)。 embed不再工作。

Print.js看起來不再維護,所有者在去年的帳戶上沒有任何活動。 根據項目上的問題,移動設備有很多錯誤,不再修復。

來自 mozilla 的PDF.js也不適用於 iPadOS/iOS 上的舊版本。 使用演示頁面進行的測試表明,打印經常會卡住。 如這張中所述,主要目標是 Firefox - 他們不會太在意 safari 上的問題)。

我能想到的唯一解決方案是使用 iframe 在桌面設備上打印並在移動設備上顯示 PDF,讓用戶自己打印。 但是,特別是在 iPadOS 上,默認設置是“請求桌面網站”,Safari 顯示為 macOS。 所以無法從 user agent 判斷是否是 iPadOS。

有人對此有解決方案嗎?

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM