简体   繁体   English

使用javascript仅在一页内打印IFrame中的PDF文件

[英]Print PDF File in IFrame using javascript getting one page only

here is my code to print a pdf file. 这是我打印pdf文件的代码。 here while printing time iam getting one page only i need a solution for that 在这里打印时间我只有一页我需要一个解决方案

  function printPdf(){
     var ifr = document.getElementById("frame1");
         //PDF is completely loaded. (.load() wasn't working properly with PDFs)
     ifr.onreadystatechange = function () {
        if (ifr.readyState == 'complete') {
              ifr.contentWindow.focus();
              ifr.contentWindow.print();
           }
       }
 }

I suspect that's because the whole window gets printed (which has the current view of the iframe with the 1st page of the PDF rendered). 我怀疑这是因为整个窗口都被打印出来(其中包含iframe的当前视图以及PDF的第一页)。 Use <object> instead: 改为使用<object>

<!DOCTYPE html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

    <script>
    function PrintPdf() {
        idPrint.disabled = 0;
        idPdf.Print();
    }

    function idPdf_onreadystatechange() {
        if (idPdf.readyState === 4)
            setTimeout(PrintPdf, 1000);
    }
    </script>

</head>

<body>
    <button id="idPrint" disabled=1 onclick="PrintPdf()">Print</button>
    <br>
    <object id="idPdf" onreadystatechange="idPdf_onreadystatechange()"
        width="300" height="400" type="application/pdf"
        data="test.pdf?#view=Fit&scrollbar=0&toolbar=0&navpanes=0">
        <span>PDF plugin is not available.</span>
    </object>
</body>

This code is verified with IE. 此代码已通过IE验证。 Other browsers will still render the PDF, but may not print it. 其他浏览器仍将呈现PDF,但可能无法打印。

[UPDATE] If you need dynamic loading and printing, the changes to the above code are minimal: [更新]如果您需要动态加载和打印,对上述代码的更改是最小的:

<!DOCTYPE html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

    <script>
    function PrintPdf() {
        idPdf.Print();
    }

    function idPdf_onreadystatechange() {
        if (idPdf.readyState === 4)
            setTimeout(PrintPdf, 1000);
    }

    function LoadAndPrint(url)
    {
        idContainer.innerHTML = 
            '<object id="idPdf" onreadystatechange="idPdf_onreadystatechange()"'+
                'width="300" height="400" type="application/pdf"' +
                'data="' + url + '?#view=Fit&scrollbar=0&toolbar=0&navpanes=0">' +
                '<span>PDF plugin is not available.</span>'+
            '</object>';
    }
    </script>
</head>

<body>
    <button id="idPrint" onclick="LoadAndPrint('http://localhost/example.pdf')">Load and Print</button>
    <br>
    <div id="idContainer"></div>
</body>
<iframe src="teste.pdf" id="meupdf" width="800" height="600" />

function printPdf) {

    var PDF = document.getElementById("meupdf");
    PDF.focus();
    PDF.contentWindow.print();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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