我的项目要求我添加“另存为 PDF”功能。我一直在寻找一个纯 JavaScript 解决方案,该解决方案仅在客户端执行此操作,但是,我被告知它无法实现,至少目前是这样。
jsPDF目前还是一个有限版本,不支持图表等。因此,现在我正在寻找一个稳定的开源免费解决方案来设置服务器 Web 服务,该服务从客户端接收数据并发送回生成的 PDF 文件或链接供用户保存到磁盘上。
来自客户端的数据是由客户端用户决定的,这意味着,不是整个页面。用户可以选择将地图、表格或全部保存为 PDF 文件。
有什么建议吗?
PS:Windows环境下
My project requires me to add a "SaveAs PDF" feature. I was looking for a pure JavaScript solution which does this just in client end, however, was told that it's not implementable, at least for now.
jsPDF currently is still a limited version, not support graph and others. So now I am looking for a stable open-srouce free solution to set up a server web service, that receive data from client-end and send back the produced PDF file or a link for user to save to their disk.
The data from client is determined by client user, which means, not the whole page. User can choose to save a map, a table, or all of them into PDF file.
Any recommendations?
PS: in Windows environment
发布评论
评论(2)
您可以查看 ReportLab 工具包 - 它包含一个开源 Python 库,用于创建 PDF。 (您没有指定所需的服务器端语言,但 Python 得到了相当广泛的支持。)
如果您需要可以用 Javascript 编码的东西,一个选择可能是 PhantomJS.该工具允许您从命令行运行无头 Webkit 浏览器,除其他外,它还可以将网页渲染并保存为 PDF。 Slippy 使用这种方法,因此您也许能够从该项目中获取示例代码。在 PhantomJS 中编写 PDF 创建脚本可能比在 Python 中快得多,但也可能慢得多(它必须启动 Webkit 实例)并且服务器安装可能会很复杂。
You might check out the ReportLab Toolkit - it includes an Open Source Python library for creating PDFs. (You didn't specify what server-side language you wanted, but Python is pretty widely supported.)
If you need something that can be coded in Javascript, one option might be PhantomJS. This tool allows you to run a headless Webkit browser from the command line, and among other things it can render and save webpages as PDFs. Slippy uses this approach, so you might be able to get example code from that project. Scripting the PDF creation would probably be much faster in PhantomJS than in Python, but it's likely to be much slower (it has to fire up a Webkit instance) and server installation might be complicated.
我在 javascript 中创建了这个函数,它在 iframe 上发送到服务器:
我对输入名称和值进行编码以便能够发送数据。
在我的服务器上,我使用的是 php,因此要对其进行解码,您需要:rawurldecode。如果将输入的名称定义为“fileName”和“file”,您可以这样写:
之后,要强制下载,您需要发送正确的标头。我正在使用这个函数:
如果您不需要从 javascript 发送文件,因为它是在服务器端创建的,只需将文件的路径添加到下载函数中即可。
如果您使用 PHP,则可以使用 fpdf 生成 pdf。
I've create this function in javascript which send on iframe to the server:
I'm encoding the input name and value to be able to send data.
On my server, I'm using php, so to decode this, you need: rawurldecode. If you define the name of the inputs as "fileName" and "file" you can write this:
After than, to force the download, you need to send the corrects header. I'm using this function:
If you don't need to send the file from javascript because it's created on the server side, just add the path of your file to the download function.
If you're using PHP, You can use fpdf to generate the pdf.