从itextsharp批注弹出一个窗口以显示图像和文本

问题描述 投票:1回答:2

我想在C#项目中添加并弹出窗口,以通过单击itextsharp批注显示图像和文本。

iTextSharp.text.pdf.PdfAnnotation annot = iTextSharp.text.pdf.PdfAnnotation.CreateLink(stamper.Writer, c.rect, PdfAnnotation.HIGHLIGHT_INVERT, PdfAction.JavaScript("app.alert('action!')", stamper.Writer));

以上代码用于显示警报,我想根据我的需要对其进行自定义,有人可以给我一个选项。我对javascript不熟悉。还是我可以使用其他选项?

c# javascript itextsharp
2个回答
3
投票

您需要几个注释来实现您想要的。

让我从简单的文本注释开始:

假设:

  • [writer是您的PdfWriter实例,
  • [rect1rect2是定义坐标的矩形,
  • [titlecontentsstring对象,其内容要在文本注释中显示,

然后您需要以下代码片段来添加弹出注释:

// Create the text annotation
PdfAnnotation text = PdfAnnotation.CreateText(writer, rect1, title, contents, false, "Comment");
text.Name = "text";
text.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_NOVIEW;
// Create the popup annotation
PdfAnnotation popup = PdfAnnotation.CreatePopup(writer, rect2, null, false);
// Add the text annotation to the popup
popup.Put(PdfName.PARENT, text.IndirectReference);
// Declare the popup annotation as popup for the text
text.Put(PdfName.POPUP, popup.IndirectReference);
// Add both annotations
writer.AddAnnotation(text);
writer.AddAnnotation(popup);
// Create a button field
PushbuttonField field = new PushbuttonField(wWriter, rect1, "button");
PdfAnnotation widget = field.Field;
// Show the popup onMouseEnter
PdfAction enter = PdfAction.JavaScript(JS1, writer);
widget.SetAdditionalActions(PdfName.E, enter);
// Hide the popup onMouseExit
PdfAction exit = PdfAction.JavaScript(JS2, writer);
widget.SetAdditionalActions(PdfName.X, exit);
// Add the button annotation
writer.AddAnnotation(widget);

尚未解释两个常量:

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;"

当然,这在我的书中进行了解释,更具体地说在第7章中进行了解释。您可以找到完整的示例here。如果需要C#示例,请寻找相应的示例here

如果您还需要图像,请看以下示例:advertisement.pdf

此处您有一个广告,当您单击“关闭此广告”时,该广告将关闭。这也可以使用JavaScript完成。您需要将之前的代码段与Advertisement示例的代码结合在一起。

您需要的关键JavaScript方法是:getField()getAnnot()。您必须更改属性以显示或隐藏内容。


0
投票

我通过使用附件而不是弹出窗口解决了这个问题。下面的代码将在您的pdf中放置一个图像,单击该图像将以全分辨率打开图像。

PdfReader reader = new PdfReader(ClassLoader.getSystemClassLoader().getResourceAsStream("source.pdf"));
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("target.pdf"));

PdfAnnotation imgAttach = PdfAnnotation.createFileAttachment(stamper.getWriter(), new Rectangle(100, 100, 200, 200), "", null, "PATH/TO/image.jpeg", "image.jpeg");

PdfAppearance app = stamper.getOverContent(1).createAppearance(100, 100);
Image img = Image.getInstance("PATH/TO/image.jpeg");
img.scaleAbsolute(100, 100);
img.setAbsolutePosition(100, 100);
app.addImage(img);

imgAttach.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app);

stamper.addAnnotation(imgAttach, 1);
stamper.getOverContent(1).addImage(img);
stamper.close();
© www.soinside.com 2019 - 2024. All rights reserved.