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.
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:
PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, ... ); fs.AddDescription("specificname", false); writer.AddFileAttachment(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(true); target.EmbeddedFileName = "specificname"; PdfDestination dest = new PdfDestination(PdfDestination.FIT); dest.AddFirst(new PdfNumber(1)); PdfAction action = PdfAction.GotoEmbedded(null, target, dest, true);
You can use this action for an annotation, a Chunk, etc... For instance:
Chunk chunk = new Chunk(" (see info)"); chunk.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:
188.8.131.52 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...