是否可以使用 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 一起工作,那么你需要在这个 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>
资源:
关于javascript - 读取chrome的ctrl+p数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55187356/