javascript - 读取chrome的ctrl+p数据

标签 javascript google-chrome google-chrome-extension

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

最佳答案

您可以使用 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 一起工作,那么你需要在这个 answer 之后检测浏览器类型.

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

<!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>

资源:

演示 enter image description here

关于javascript - 读取chrome的ctrl+p数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55187356/

相关文章:

javascript - 为什么 JavaScript 函数的参数返回 'undefined' ?

javascript - 自动网站登录打开Chrome

javascript - 从 Gmail API 批量获取超过 10,000 封电子邮件的电子邮件发件人

javascript - 在 CommonJS 模块中引入 jQuery 的更好方法?

javascript - 对 2D javascript 数组进行排序

javascript - 为什么这个 SVG 在 Chrome 上运行良好,但在 Firefox 上不可见?

javascript - 嵌入式 Google map 仅在 IE 上加载,但在 Mozilla Firefox 和 Google Chrome 上均不加载

javascript - 通过服务器消息单击按钮

security - 扩展和小书签的内容安全策略

javascript - 您将数据模型放在 dojo 应用程序的什么位置?