How to create a pop-up window to display images and text?
iTextSharp.text.pdf.PdfAnnotation annot = iTextSharp.text.pdf.PdfAnnotation.CreateLink( stamper.Writer, c.rect, PdfAnnotation.HIGHLIGHT_INVERT, PdfAction.JavaScript("app.alert('action!')", stamper.Writer));
Posted on StackOverflow on May 31, 2014 by Buddhima Naween Rathnayake
You need a couple of annotations to achieve what you want.
Let me start with a simple text annotation:
Suppose that:
rect
andrect1
are rectangles that define coordinates,title
andcontents
arestring
objects with the content you want to show in the text annotation,
Then you need this code snippet to add the popup annotations:
// Create the text annotation
PdfTextAnnotation text = new PdfTextAnnotation(rect);
text.setIconName(new PdfName("Comment"))
.setTitle(new PdfString(title))
.setContents(contents)
.setOpen(false)
.setName(new PdfString("text"));
text.setFlags(PdfAnnotation.READ_ONLY | PdfAnnotation.NO_VIEW);
// Create the popup annotation
PdfPopupAnnotation popup = new PdfPopupAnnotation(new Rectangle(rect.getLeft() + 10, rect.getBottom() + 10, 190, 90));
// Add the text annotation to the popup
popup.setParent(text);
// Declare the popup annotation as popup for the text
text.setPopup(popup);
// Add both annotations
pdfDoc.getPage(1).addAnnotation(text);
pdfDoc.getPage(1).addAnnotation(popup);
// Create a button field
PdfButtonFormField field = PdfFormField.createPushButton(pdfDoc, rect, "button", "");
PdfAnnotation widget = field.getWidgets().get(0);
widget.remove(PdfName.AP);
// Show the popup onMouseEnter
PdfAction enter = PdfAction.createJavaScript(JS1);
widget.setAdditionalAction(PdfName.E, enter);
// Hide the popup onMouseExit
PdfAction exit = PdfAction.createJavaScript(JS2);
widget.setAdditionalAction(PdfName.X, exit);
// Add the button annotation
pdfDoc.getPage(1).addAnnotation(widget);
Two constants aren't explained yet:
JS1:
"var t = this.getAnnot(this.pageNum, 'text');
t.popupOpen = true;
var w = this.getField('button');
w.setFocus();"
JS2:
"var t = this.getAnnot(this.pageNum, 'text');
t.popupOpen = false;"
You can find a full example here.
If you also want an image, please take a look at the Advertisement example.
Here you have an advertisement that closes when you click "close this advertisement". This is also done using JavaScript. You need to combine the previous snippet with the code of the Advertisement example.
The key JavaScript methods you'll need are: getField()
and getAnnot()
. You'll have to change the properties to show or hide the content.
Click How to create a pop-up window to display images and text? if you want to see how to answer this question in iText 5.