Skip to main content
Skip table of contents

How to open an MS Word attachment by clicking an image?

How can I make an image clickable so that an attached MS word document opens?

I have some PDFs here where there are some images (an MS Word icon with the MS word file name beneath the icon) which open the attached ms word document by clicking on the images. I wonder how can I do this with the iText library. I can add the images and attach the MS word documents but I haven't figured out how I can apply something like an action (GoToE seems only available for PDF attachments) or a link?

Posted on StackOverflow on Jun 23, 2015 by Pali

Please take a look at section 12.6.4.4 in ISO-32000-1 (that is the PDF specification). That section is titled "Embedded Go-To Actions":

ISO-32000-1, section 12.6.4.4

ISO-32000-1, section 12.6.4.4

As you've found out, the behavior you describe is by specification. The GoToE action is for jumping to and form a PDF file that is embedded in another PDF file. Other document formats aren't supported because.

Your only option is to introduce a file attachment annotation instead of an Embedded file along with a GoToE action. See for instance the FileAttachmentAnnot example:

public void createPdf(String imgSrc, String path, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Rectangle rect = new Rectangle(36, 700, 100, 100);
    PdfFileSpec fs = PdfFileSpec.createEmbeddedFileSpec(pdfDoc, path, null, "test.docx", null, null, false);
    PdfAnnotation attachment = new PdfFileAttachmentAnnotation(rect, fs)
            .setContents("Click me");

    PdfFormXObject xObject = new PdfFormXObject(rect);
    ImageData imageData = ImageDataFactory.create(imgSrc);
    PdfCanvas canvas = new PdfCanvas(xObject, pdfDoc);
    canvas.addImage(imageData, rect, true);
    attachment.setNormalAppearance(xObject.getPdfObject());

    pdfDoc.addNewPage().addAnnotation(attachment);
    pdfDoc.close();
}

In this example, we create a PdfAnnotation and we define a custom appearance for this annotation (instead of the pin or the paperclip symbol). I used an image because that's what you seem to want. Check out the result here (this works with Adobe Reader, but not all PDF viewers support this).

Click How to open an MS Word attachment by clicking an image? 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.