Spire.PDF 是一款功能强大的组件,支持给PDF文档添加动作。如打开文档执行的动作,前一个动作完成后执行的动作,关闭文档执行的动作。以下示例将介绍如何给PDF文档添加动作。
添加在打开PDF 文档后执行的动作
C#
//初始化一个PdfDocument实例
PdfDocument document = new PdfDocument();
//设置文本字体
Font font=new Font("微软雅黑",20f);
PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(font, true);
//添加两张页面并添加文本
PdfPageBase page2 = document.Pages.Add();
page1.Canvas.DrawString("第一张页面",trueTypeFont, new PdfSolidBrush(Color.Black), 10, 10);
PdfPageBase page2 = document.Pages.Add();
page2.Canvas.DrawString("第二张页面", trueTypeFont, new PdfSolidBrush(Color.Black), 10, 10);
//javascript代码
String script
= "app.alert({"
+ " cMsg: \"您好,我是第一个动作!\","
+ " nIcon: 3,"
+ " cTitle: \"JavaScript Action\""
+ "});";
// 创建PdfJavaScriptAction实例 action1
PdfJavaScriptAction action1 = new PdfJavaScriptAction(script);
//设置action1在打开PDF文档后执行
document.AfterOpenAction = action1;
VB.NET
'初始化一个PdfDocument实例
Dim document As New PdfDocument()
'设置文本字体
Dim font As New Font("微软雅黑", 20F)
Dim trueTypeFont As New PdfTrueTypeFont(font, True)
'添加两张页面并添加文本
Dim page2 As PdfPageBase = document.Pages.Add()
page1.Canvas.DrawString("第一张页面", trueTypeFont, New PdfSolidBrush(Color.Black), 10, 10)
Dim page2 As PdfPageBase = document.Pages.Add()
page2.Canvas.DrawString("第二张页面", trueTypeFont, New PdfSolidBrush(Color.Black), 10, 10)
'javascript代码
Dim script As [String] = "app.alert({" + " cMsg: ""您好,我是第一个动作!""," + " nIcon: 3," + " cTitle: ""JavaScript Action""" + "});"
' 创建PdfJavaScriptAction实例 action1
Dim action1 As New PdfJavaScriptAction(script)
'设置action1在打开PDF文档后执行
document.AfterOpenAction = action1
添加在第一个动作完成后执行的动作
C#
//创建一个PdfGoToAction定向到PDF文档的第2页
PdfDestination dest = new PdfDestination(page1);
PdfGoToAction action2 = new PdfGoToAction(dest);
//设置action2在action1完成后执行,即跳转到PDF的第2页
action1.NextAction = action2;
VB.NET
'创建一个PdfGoToAction定向到PDF文档的第2页
Dim dest As New PdfDestination(page1)
Dim action2 As New PdfGoToAction(dest)
'设置action2在action1完成后执行,即跳转到PDF的第2页
action1.NextAction = action2
添加在关闭PDF文档前执行的动作
C#
script
= "app.alert({"
+ " cMsg: \"谢谢您的查看,再见!\","
+ " nIcon: 3,"
+ " cTitle: \"JavaScript Action\""
+ "});";
PdfJavaScriptAction action3 = new PdfJavaScriptAction(script);
document.BeforeCloseAction = action3;
//保存文档
document.SaveToFile("结果文档.pdf");
VB.NET
script = "app.alert({" + " cMsg: ""谢谢您的查看,再见!""," + " nIcon: 3," + " cTitle: ""JavaScript Action""" + "});"
Dim action3 As New PdfJavaScriptAction(script)
document.BeforeCloseAction = action3
'保存文档
document.SaveToFile("结果文档.pdf")