Javascript 使用JS将网页直接保存为PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28522749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save Web page directly to PDF using JS
提问by Abrar Jahin
I want to save web page directly to PDF.
我想将网页直接保存为 PDF。
What I have done is-
我所做的是——
<form>
<input type=button name=print value="Print" onClick="window.print()">
</form>
But it gives me option for print or save the page as PDF.
但它为我提供了打印或将页面另存为 PDF 的选项。
But what I want is when I click on the button, it directly save the page as PDF not showing any option.
但我想要的是当我点击按钮时,它直接将页面另存为 PDF 而不显示任何选项。
Is there any solution in JavaScript?
JavaScript 中有什么解决方案吗?
Thanks in advance for helping.
提前感谢您的帮助。
采纳答案by jperezov
The short answer is no, you cannot prevent users from seeing the option in their browser using just javascript.
简短的回答是否定的,您无法阻止用户仅使用 javascript 在浏览器中看到该选项。
The slightly-longer answer, is that you cando this with a bit more than javascript.
稍微长一点的答案是,您可以使用比 javascript 多一点的方法来做到这一点。
Using a service such as html2canvas, you can send a POST request to a page on your server. Use that page to convert the image to a PDF, and have it output the file as a download.
使用诸如html2canvas 之类的服务,您可以向服务器上的页面发送 POST 请求。使用该页面将图像转换为 PDF,并将其输出为下载文件。
Assuming you're using PHP:
假设您使用的是 PHP:
<?php
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='screen-shot.pdf'");
// The above headers will cause the file to automatically be downloaded.
// Use a library to convert the image to a PDF here.
An example library to convert an image to a PDF is mPDF, or TCPDF. Feel free to Google others, especially if you're not using PHP.
将图像转换为 PDF 的示例库是mPDF或TCPDF。随意谷歌其他人,特别是如果你不使用 PHP。
Do note that this solution is inferior to them just making the choice themselves, as the quality definitely won't be as nice.
请注意,此解决方案不如他们自己做出选择,因为质量肯定不会那么好。
回答by Eugene
Must notice here that the suggested solution converts HTML into image and then the raster image is converted into PDF.
这里必须注意,建议的解决方案是将 HTML 转换为图像,然后将光栅图像转换为 PDF。
If you want to save into PDF that is searchable (so can be archived and printed with best quality) and the text is printed clearly then you should consider one of these options:
如果您想保存为可搜索的 PDF(因此可以以最佳质量进行存档和打印)并且文本打印清晰,那么您应该考虑以下选项之一:
Ask user to save the page into PDF by providing instruction to do so for Google Chrome or Safari (both browsers are able to "print" page into PDF files). Maybe you may even try to show this instruction and invoke the printing dialog
Use some of client side javascript libraries to generate PDF from the data with the tool like jsPDF (free, open source)or similar
通过为 Google Chrome 或 Safari 提供说明,要求用户将页面保存为 PDF(两种浏览器都能够将页面“打印”为 PDF 文件)。也许您甚至可以尝试显示此指令并调用打印对话框
使用一些客户端 javascript 库通过jsPDF(免费,开源)或类似工具从数据生成 PDF

