【问题标题】:everytime i try to print pdf using this method it will always produce blank pdf每次我尝试使用这种方法打印 pdf 它总是会产生空白 pdf
【发布时间】:2023-03-08 19:34:01
【问题描述】:

所以我想使用按钮和 javascript 打印 pdf,但它总是会生成空白 pdf/空 pdf。我想要https://imgur.com/a/PsRqeBR之类的东西,但我得到了这个https://imgur.com/a/J7rzlSq

我尝试使用 window.open 然后 window.print 但它仍然产生空白 pdf,我也尝试将 url 放在 window.open 中而不是先声明它但没有用

HTML

<button type="button" onclick="printme()">click me...</button>

JavaScript

function printme(){
 var URL = "https://www.detik.com/";
 var W = window.open(URL);
 W.window.print();
}

【问题讨论】:

标签: javascript html


【解决方案1】:

你需要做 window.print() 而不是 w.window.print()

function printme(){
 var URL = "https://www.detik.com/";
 var W = window.open(URL);
 window.print();
}

【讨论】:

  • 您想将通过 window.open() 打开的整个网站打印为 pdf 吗?
  • 不完全是整个网站,只是想在我要打印的页面上打印html,您可以在我附加的链接上看到示例。
  • 也许这是你的解决方案stackoverflow.com/questions/8240472/…
  • 很有趣,这就是我得到原始代码的地方,呵呵,没用
【解决方案2】:

以下代码的来源是Print an external page without opening it
这在Printing a web page using just url and without opening new window?的答案之一中提到
我只修改了链接以包含您的网站地址:

<!doctype html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>MDN Example</title>
  <script type="text/javascript">
    function closePrint() {
      document.body.removeChild(this.__container__);
    }

    function setPrint() {
      this.contentWindow.__container__ = this;
      this.contentWindow.onbeforeunload = closePrint;
      this.contentWindow.onafterprint = closePrint;
      this.contentWindow.focus(); // Required for IE
      this.contentWindow.print();
    }

    function printPage(sURL) {
      var oHiddFrame = document.createElement("iframe");
      oHiddFrame.onload = setPrint;
      oHiddFrame.style.position = "fixed";
      oHiddFrame.style.right = "0";
      oHiddFrame.style.bottom = "0";
      oHiddFrame.style.width = "0";
      oHiddFrame.style.height = "0";
      oHiddFrame.style.border = "0";
      oHiddFrame.src = sURL;
      document.body.appendChild(oHiddFrame);
    }
  </script>
</head>

<body>


  <p><span onclick="printPage('https://www.detik.com');" style="cursor:pointer;text-decoration:underline;color:#0000ff;">Print external page!</span></p>

</body>

</html>

【讨论】:

  • 我试图运行你的恶魔,但我收到一条错误消息 Error: { "message": "SecurityError: Permission denied to access property \"__container__\" on cross-origin object", "filename ": "stacksnippets.net/js", "lineno": 22, "colno": 0 }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多