Javascript:如何从 HTML 表单或 div 创建 pdf 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30639568/
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
Javascript: How to create pdf file from HTML form or div
提问by keewee279
I am new to Javascript / jQuery and am looking for a way to add a button to a page that allows the user to create a pdffrom a pre-defined form or div (e.g. by adding a class).
我是 Javascript / jQuery 的新手,正在寻找一种向页面添加按钮的方法,该按钮允许用户从预定义的表单或 div(例如通过添加类)创建 pdf。
I did some research but could not find a way to do this in JS or jQuery.
我做了一些研究,但找不到在 JS 或 jQuery 中做到这一点的方法。
Is there a way to realise this on client side via Javascript / jQuery or can someone tell me a freeware plugin that supports this ?
有没有办法通过 Javascript / jQuery 在客户端实现这一点,或者有人可以告诉我支持这个的免费软件插件吗?
The only plugin I found is TCPDFbut this seems to be pretty large and I did not see a way there where I can limit this to a certain form or div on a page (instead of printing the whole page).
我发现的唯一插件是TCPDF但这似乎非常大,我没有看到可以将其限制为页面上的某种形式或 div(而不是打印整个页面)的方法。
Note:I do not need to cover images, just plain HTML like form fields or tables and text.
注意:我不需要覆盖图像,只需要像表单字段或表格和文本这样的纯 HTML。
Many thanks in advance for any help with this, Mike
非常感谢您对此的任何帮助,迈克
回答by Moppo
you could try with jsPDF
你可以试试jsPDF
it's free and client side.
它是免费的和客户端。
You can see from their 'HTML Render' example that you can create a PDF from a portion of your HTML
您可以从他们的“HTML Render”示例中看到,您可以从 HTML 的一部分创建 PDF
EDIT
编辑
Probably jsPDF doesn't support CSS
可能 jsPDF 不支持 CSS
If you need it, you could try as an alternative phantomJS, but it's a command-line tool and it captures a web page as a screenshot. Not sure if that's what you're searching for
如果您需要它,您可以尝试作为替代phantomJS,但它是一个命令行工具,它捕获网页作为屏幕截图。不确定这是否是您要搜索的内容
回答by Nikolay Bronskiy
As in a previous answer I recommend to use tiny but powerful and safe js library Print.js
与之前的答案一样,我建议使用小巧但功能强大且安全的 js 库Print.js
Example:
例子:
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
pretty easy
相当容易
回答by Ali
also a good one and simple is pdfmake
it is simple and clean library to create a pdf from HTML and you can decide to print it or not later ,
从 HTML 创建 pdf 是一个简单而干净的库,您可以决定以后是否打印,
a sample of basic usage below
下面的基本用法示例
var docDefinition = {
content: [
'First paragraph',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
]
};
var pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream('pdfs/basics.pdf'));
pdfDoc.end();