密码保护PDF文件

时间:2012-09-12 07:45:37

标签: c#

我有以下内容:

  • 例程X,每天创建一个PDF文件。
  • 例程Y,它将此文件附加到Outlook电子邮件并将其发送给收件人。

以上都在VBA中。它们是从C#控制台应用程序调用的。

创建PDF后,我需要密码保护它。 要在不购买第三方软件的情况下通过VBA执行此操作非常复杂。

使用C#最简单的解决方案是什么?

(我怀疑我们花的金额与答案的复杂程度之间会有反比关系!)

1 个答案:

答案 0 :(得分:15)

PDFSharp应该能够使用密码保护PDF文件:

// Open an existing document. Providing an unrequired password is ignored.
PdfDocument document = PdfReader.Open(filename, "some text");

PdfSecuritySettings securitySettings = document.SecuritySettings;

// Setting one of the passwords automatically sets the security level to 
// PdfDocumentSecurityLevel.Encrypted128Bit.
securitySettings.UserPassword  = "user";
securitySettings.OwnerPassword = "owner";

// Don't use 40 bit encryption unless needed for compatibility reasons
//securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

// Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = true;
securitySettings.PermitFullQualityPrint = false;
securitySettings.PermitModifyDocument = true;
securitySettings.PermitPrint = false;

// Save the document...
document.Save(filename);

参考:
http://www.pdfsharp.net/wiki/ProtectDocument-sample.ashx