Attach a file to a PDF using client-side JavaScript?
Asked Answered
G

1

7

How can an arbitrary file (eg a XLSX) be attached/embedded to a PDF file using only client-side browser JavaScript?

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.

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:

32 0 obj
 <</Type /EmbeddedFile /Subtype /{mimetype} /Length 72>>
 stream
 {file data}
 endstream
 endobj
Gollin answered 5/11, 2018 at 18:37 Comment(5)
Is the PDF being viewed at the time?Boarfish
The file should be attached to the pdf before displaying the pdf to the user.Gollin
What are you hoping to do with the xlsx? Like what would a successful solution do?Herwig
@Victor, if you are satisfied with my answer below, please mark it as accepted on the left side from my answer and / or upvote it.Chrysoberyl
@Chrysoberyl yes, you are right. Im sorry.Gollin
C
3

You could use JSPdf library for this case. 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. I think that the JavaScript plugin source code is more understandable for this case.

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:

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.

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.

In this case you could edit a PDF server side with free PHP library like FPDI for example. With FPDI it is possible to read and to edit PDF documents (use createByFile() method to read a PDF). The FPDI is extended version of FPDF library, which has the plugin for attachments.

Chrysoberyl answered 11/11, 2018 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.