在按钮上加载和打印PDF的可能方法单击使用javascript

时间:2014-08-13 04:43:27

标签: javascript jquery iframe

您能否告诉我加载和打印应该适用于所有浏览器的pdf文件的可能方法。目前我正在使用iframe来显示文件然后触发打印方法,但它在IE中不起作用。我搜索了很多,但解决方案都没有。请让我知道任何替代方法来做到这一点。以下是我的示例代码: -

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="pdfpoc.aspx.cs" Inherits="Game.pdfpoc" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function printpdf() 
{
    alert("pdfprint");
    var iframe = document.frames ? window.frames.frames["frPDF"] : document.getElementById("frPDF");
    var ifWin = iframe.contentWindow || iframe;
    try {

        ifWin.focus();
        ifWin.print();
    }
    catch (e) {
        window.print(false);
        //or when you get Invalid calling object error for IE9 and above
        //set the browser into IE8 compatibility mode will work
    }

    return false;
}
function changeSource() {
    console.log("change");
    var src = $("#frPDF").attr('src');
    console.log("src", src);

    if (src == "NCTP.pdf") {
        // $("#frPDF").attr('src', "NCTP1.pdf");
        url = "NCTP1.pdf";
    }
    else {
        //  $("#frPDF").attr('src', "NCTP.pdf");
        url = "NCTP.pdf";

    }
    console.log("Url" + url);
    var iframe = $('#frPDF')[0]; // reference to IFRAME element
    $.get(url, function () {
        iframe.src = url;
        $("#frPDF").load(function () {
            printpdf();
        });
        // $("#frPDF").trigger('onload');
    }).error(function () { alert('PDF not found'); });
    return false;
}
</script>
</head>

<body>
<form id="form1" runat="server">
  <input type="button" value="Change Source" onclick="javascript:changeSource()" />
  <div> Its not the part of Iframè <br />
    IFRAME PDF: <br />
    <iframe id="frPDF" height="800" width="800" src="NB.pdf?a=1"></iframe>
  </div>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

对于IE浏览器,最好使用pdf的embed-tag,看看这个(我替换你的pdf源代码)。它适用于IE 8+和Chrome(以及Opera ofc)

<input type="button" value="Change Source" name="btnChangeSource"  />
<div> Its not the part of Iframè <br />
    IFRAME PDF: <br />
    <embed id="frPDF" type="application/pdf" height="800" width="800" src="http://eurecaproject.eu/files/5013/9885/7113/example4.pdf"></embed>
 </div>

Solution for IE/Chrome/Opera

答案 1 :(得分:0)

jQuery(document).ready(function($) {
  function print(url)
  {
      var _this = this,
          iframeId = 'iframeprint',
          $iframe = $('iframe#iframeprint');
      $iframe.attr('src', url);

      $iframe.load(function() {
          _this.callPrint(iframeId);
      });
  }

  //initiates print once content has been loaded into iframe
  function callPrint(iframeId) {
      var PDF = document.getElementById(iframeId);
      PDF.focus();
      PDF.contentWindow.print();
  }
});
相关问题