javascript - 读取chrome的ctrl+p数据
问题描述
chrome扩展是否可以读取ctrl+p数据并将其保存为pdf或html而不显示打印屏幕?
解决方案
您可以使用 JavaScript 和任何可以保存 pdf 文档的免费 html 到 pdf 生成器来解决这个问题。
这是我分步解决的方法:
- 禁用并覆盖ctrl+p功能,使其不显示打印屏幕。
- 在步骤 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>
资源:
推荐阅读
- c# - 注释正则表达式不起作用
- java - 尝试在画布纹理视图 android 上绘制时出现空指针异常?
- android - java.lang.NoSuchMethodError:没有静态方法
- java - 这里k - 1 和--k 的区别,真的不明白
- php - 从 PHP 中的“提交”按钮插入 mysql 值不起作用
- android - Cordova 8 中未生成签名的 APK
- c# - 单击子按钮时删除父用户控件
- c - 不要正确加密wincrypt
- java - 应用程序在 android studio 的 managedQuery 行中崩溃
- java - 如何从java中的字符串动态获取别名和列