Skip to main content
Skip table of contents

How to attach files to a PDF?

I am struggling with attaching files to a PDF that I am generating at runtime. I manage to attach a file to the PDF, but I can't seem to reference them as links within the PDF.

iText in Action suggests I can do this as annotations or document level attachments. I don't find the book easy to follow or the code easy to understand though. There also seems to be scarce help on this around in the way of articles on the internet but apologies if I have missed anything.

Posted on StackOverflow on May 22, 2013 by DuncanOppaz


I'm sorry you didn't like my book.

Did you read chapter 16? You want to embed a file as a document-level attachment like this:

PdfFileSpec fs = PdfFileSpec.createEmbeddedFileSpec(pdfDoc, …);
pdfDoc.addFileAttachment("specificname", fs);

Inside the document, you want to create a link to that opens the PDF document described with the keyword "specificname". This is done through an action:

PdfTargetDictionary target = new PdfTargetDictionary(PdfName.P);
target.setName("specificname");
PdfAction action = PdfAction.createGoToE(PdfExplicitDestination.createFit(1), false, target);

You can use this action for an annotation, a Text, etc... For instance:

Text text = new Text(" (see info)");
text.setAction(action);

It is a common misconception to think that this will work for any attachment. However, ISO-32000-1 is very clear about the GotoE(mbedded) functionality:

12.6.4.4 Embedded Go-To Actions An embedded go-to action (PDF 1.6) is similar to a remote go-to action but allows jumping to or from a PDF file that is embedded in another PDF file (see 7.11.4, "Embedded File Streams").

If you meant to ask "I want to attach any file (such as a Docx, jpg,... file) to my PDF and add an action to the PDF that opens such a file upon clicking a link," then you're asking something that isn't supported in the PDF specification.

Feel free to read ISO-32000-1. If you didn't understand my book, you'll have to do an extra effort trying to read the PDF standard...

Click How to attach files to a PDF? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.