PDF 标准包括对 JavaScript 的支持,但正如 @Wes Hardaker 指出的那样,并不是每个 PDF 阅读器都支持它。然而,有时有总比没有好。
这是Adobe官方的Acrobat JavaScript 脚本编写指南。您最感兴趣的可能是doc
对象有一个名为的方法getURL()
。要使用它,你只需调用:
app.doc.getURL('http://www.google.com/');
将该事件绑定到文档的打开事件,您就拥有了一个跟踪器。我不太熟悉在 Adobe Acrobat 中创建事件,但从代码中创建事件非常简单。下面的代码是一个完整的 VS2010 C# WinForms 应用程序,它使用开源库 iTextSharp (5.1.1.0)。它创建一个 PDF 并将 JavaScript 添加到打开事件中。
一些笔记:只要文档访问外部资源,Adobe Acrobat 和 Reader 都会向用户发出警告。大多数其他 PDF 阅读器可能也会这样做。这是非常烦人的,因此仅出于这个原因就不应该这样做。就我个人而言,我不在乎是否有人跟踪我的文档打开情况,我只是不想每次都收到提示。其次,重申一下,此代码适用于 Adobe Acrobat 和 Adobe Reader,可能至少可以追溯到 V6,但可能适用于其他 PDF 阅读器,也可能不适用于。第三,没有安全的方法来唯一地识别用户。这样做将要求您创建并存储一些相当于“cookie”的内容,这将要求您写入用户的文件系统,这将被认为是不安全的。这意味着您只能检测打开次数,而不能检测唯一打开次数。第四,这可能并非在所有地方都是合法的。某些司法管辖区要求您在跟踪用户时通知他们,并为他们提供一种方式来查看您正在收集哪些信息。
但综上所述,我不能因为不喜欢而不给出答案。
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//File that we will create
string OutputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Events.pdf");
//Standard PDF creation setup
using (FileStream fs = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
{
//Open our document for writing
doc.Open();
//Create an action that points to the built-in app.doc object and calls the getURL method on it
PdfAction act = PdfAction.JavaScript("app.doc.getURL('http://www.google.com/');", writer);
//Set that action as the documents open action
writer.SetOpenAction(act);
//We need to add some content to this PDF to be valid
doc.Add(new Paragraph("Hello"));
//Close the document
doc.Close();
}
}
}
this.Close();
}
}
}