altgov3en altgov3en - 7 months ago 9
HTML Question

Print whole HTML page including pdf file inside iframe

I've got an assignment to embed relatively small pdf file inside html page and print the entire html pade including the pdf file inside the iframe.
Here is the structure of my html page:
enter image description here

Here is my code:



@media print{
body * {display:block;}
.toPrint{display:block; border:0; width:100%; min-height:500px}

<body>
<button onclick="window.print()">Print</button>

<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
<iframe class="toPrint" src="https://nett.umich.edu/sites/default/files/docs/pdf_files_scan_create_reducefilesize.pdf" style="width:100%; height:97vh;"></iframe>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
</body>





Currently I'm printing the page using css @media query. But unfortunately this media query prints the pdf's first page only.

What can I do print the entire pdf file?

Answer

I used Mozilla's pdf.js to solve my problem. It renders the pdf file on html5 canvas thus it allows to print the whole html page as required.

Here is the code (credit):

<html>
<body>

<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript">
function renderPDF(url, canvasContainer, options) {
    var options = options || { scale: 1 };
        
    function renderPage(page) {
        var viewport = page.getViewport(options.scale);
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var renderContext = {
          canvasContext: ctx,
          viewport: viewport
        };
        
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        canvasContainer.appendChild(canvas);
        
        page.render(renderContext);
    }
    
    function renderPages(pdfDoc) {
        for(var num = 1; num <= pdfDoc.numPages; num++)
            pdfDoc.getPage(num).then(renderPage);
    }
    PDFJS.disableWorker = true;
    PDFJS.getDocument(url).then(renderPages);
}   
</script> 
        <h3>MUST BE PRINTED</h3>
        <p> MUST BE PRINTED</p>
		<div id="holder"></div>
        <h3>MUST BE PRINTED</h3>
        <p> MUST BE PRINTED</p>

<script type="text/javascript">
renderPDF('yourFile.pdf', document.getElementById('holder'));
</script>  

</body>
</html>

Comments