简体   繁体   English

使用客户端JavaScript将文件附加到PDF吗?

[英]Attach a file to a PDF using client-side JavaScript?

How can an arbitrary file (eg a XLSX) be attached/embedded to a PDF file using only client-side browser JavaScript? 如何仅使用客户端浏览器JavaScript将任意文件(例如XLSX)附加/嵌入到PDF文件?

If it matters, the XLSX is given by the user using a input file button and the PDF received from an external web service and encoded in base64. 如果重要的话,XLSX是由用户使用输入文件按钮给出的,而PDF是从外部Web服务接收并以base64编码的。

I am not looking for a complete solution (it would be great if it exists), but how would you approach this problem in a higher level way 我不是在寻找完整的解决方案(如果有的话,那会很好),但是您将如何以更高的层次来解决这个问题?

Files are attached using binary file streams, that looks like this in the PDF file: 使用二进制文件流附加文件,在PDF文件中如下所示:

32 0 obj
 <</Type /EmbeddedFile /Subtype /{mimetype} /Length 72>>
 stream
 {file data}
 endstream
 endobj

You could use JSPdf library for this case. 您可以在这种情况下使用JSPdf库 You have to took at JavaScript plugin and at addImage plugin source codes of this library to see how a file attachment could be done. 您必须阅读此库的JavaScript插件addImage插件源代码,才能了解如何完成文件附件。 I think that the JavaScript plugin source code is more understandable for this case. 我认为在这种情况下,JavaScript插件源代码更容易理解。

I am not looking for a complete solution 我不是在寻找完整的解决方案

Yes, a complete solution you have to write by yourself because now this library does not support a custom file attachment. 是的,您必须自己编写一个完整的解决方案,因为该库现在不支持自定义文件附件。

Files are attached using binary file streams, that looks like this in the PDF file: 使用二进制文件流附加文件,在PDF文件中如下所示:

 32 0 obj <</Type /EmbeddedFile /Subtype /{mimetype} /Length 72>> stream {file data} endstream endobj 

Yes, some like this you have to write. 是的,您必须写一些类似的东西。 You have to realize that you have to write a code for reading from a PDF file too. 您必须意识到,您还必须编写代码以读取PDF文件。

Alternative solution 替代解决方案

But, if it is too difficult or too much work for you then you have to think about doing of all this on the server side. 但是,如果这对您来说太困难或太多工作,那么您就必须考虑在服务器端完成所有这些工作。 You could send to your server a request using AJAX and the server do it and gives you a new PDF back. 您可以使用AJAX向服务器发送请求,服务器执行该请求,并返回新的PDF。

In this case you could edit a PDF server side with free PHP library like FPDI for example. 在这种情况下,您可以使用免费的PHP库(例如FPDI)编辑PDF服务器端。 With FPDI it is possible to read and to edit PDF documents (use createByFile() method to read a PDF). 使用FPDI,可以读取和编辑PDF文档(使用createByFile()方法读取PDF)。 The FPDI is extended version of FPDF library, which has the plugin for attachments . FPDI是FPDF库的扩展版本,它具有用于附件插件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM