Hello Gabriele Rossi,
If you want to print a PDF from an ASP.NET Web Forms (.aspx) page using JavaScript and window.print()
, the most straightforward approach is to embed the PDF in an <iframe>
and then call window.print()
. This method works best if your users’ browsers natively support PDF viewing.
Simple IFrame Method (Prints the Current Page with the PDF):
function printPDF(url) {
// Remove any existing print iframe
var existing = document.getElementById('pdf-print-iframe');
if (existing) existing.remove();
// Create a new iframe for the PDF
var iframe = document.createElement('iframe');
iframe.id = 'pdf-print-iframe';
iframe.src = url;
iframe.style.width = '100vw';
iframe.style.height = '100vh';
iframe.style.border = 'none';
iframe.style.display = 'block';
// When the PDF loads, print the page
iframe.onload = function () {
window.print();
};
// Replace the page content with just the PDF for printing
document.body.innerHTML = '';
document.body.appendChild(iframe);
}
Usage in ASPX:
<asp:Button ID="btnPrintPDF" runat="server" Text="Print PDF" OnClientClick="printPDF('Documents/test.pdf'); return false;" />
- Place your PDF in a
Documents
folder in your project.
- Make sure the path in the button matches the PDF location.
How This Works
- When the user clicks the button, the PDF is embedded in an iframe that fills the page.
- The page content is replaced with just the PDF.
-
window.print()
is called, so the browser prints the current page, which now contains only the PDF.
*Notes
- This method prints the PDF as rendered by the browser’s built-in PDF viewer inside the iframe.
- The printout quality and features (such as selectable text) depend on the browser’s PDF support.
- If you need to restore the original page content after printing, you’ll need to save it before replacing it.
- If you need more advanced features (like cross-browser rendering or fallback for browsers without PDF support), you can look into solutions like PDF.js, but for most cases, the iframe method is simple and effective.
I hope this helps! If you have further questions or run into issues, feel free to ask.