首页 > 解决方案 > 读取chrome的ctrl+p数据

问题描述

chrome扩展是否可以读取ctrl+p数据并将其保存为pdf或html而不显示打印屏幕?

标签: javascriptgoogle-chromegoogle-chrome-extension

解决方案


您可以使用 JavaScript 和任何可以保存 pdf 文档的免费 html 到 pdf 生成器来解决这个问题。

这是我分步解决的方法:

  1. 禁用并覆盖ctrl+p功能,使其不显示打印屏幕。
  2. 在步骤 1 中覆盖时,调用您想要的任何函数,例如 Html 到 Pdf 生成器,可以保存文档并保存。

而已。现在代码看起来如何?

在这个解决方案中,我使用了 jQuery 和 jsPdf 生成器。

所以在你的代码中添加cdns

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>

在此处插入以下 jQuery 代码以禁用和覆盖打印功能后:

//Override ctrl+p and excute another function
$(document).bind("keyup keydown", function(e){
  if(e.ctrlKey && e.keyCode == 80){
    Print(); 
    e.preventDefault();
  }
});

创建一个调用 pdfGenerator 函数或多个其他函数的打印函数:

//Print My Way
function Print(){
  console.log("for testing to see if this is called");
  pdfGenerator()
}

//Use any other print method, in this case I print/save html to pdf as downloadable
function pdfGenerator(){
  var doc = new jsPDF();
  doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
  });
  // instead of Test.pdf you can make give the name of the page.
  doc.save('Test.pdf');
}

这就对了。如果您需要它仅与 Chrome 一起使用,那么您需要在此答案之后检测浏览器类型。

要在此处查看所有这些示例,请查看完整代码:

<!doctype html>

<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
</head>

<body>
  <p>This is my page and ctrl+p will prevent print screen but print this page as downloadable pdf</p>

<script>
  //Override ctrl+p and excute another function
  $(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.keyCode == 80){
      Print(); 
      e.preventDefault();
    }
  });

  //Print My Way
  function Print(){
    pdfGenerator()
    //additional function do something else.
  }

  //Use any other print method, in this case I print/save html to pdf as downloadable
  function pdfGenerator(){
    var doc = new jsPDF();
    doc.fromHTML($('body').get(0), 15, 15, {
      'width': 170, 
    });
    doc.save('Test.pdf');
  }
</script>

</body>
</html>

资源:

演示 在此处输入图像描述


推荐阅读