Skip to main content
 首页 » 编程设计

c#之打开 PDFSharp 文档并保存删除密码

2024年02月20日21over140

出于 2 个不同的原因,我在 2 个不同的应用程序中使用 PDFSharp。第一个是密码保护文件,第二个是给文件加水印。这些流程都在自己的应用程序/工作流程中单独工作。问题是应用程序 1 只知道密码,应用程序 2 只知道水印,应用程序 1 使用默认所有者密码和动态用户密码,应用程序 2 使用所有者密码打开文档以应用水印。问题是密码没有保留,似乎 PDFSharp 在保存文档时忽略了以前的 PDF 密码?!

有没有办法在应用水印时保持安全设置,而无需再次明确定义密码?

我在 PDFSharp 论坛上发布了这个,但他们忽略了它,这不是一个好兆头吗?! http://forum.pdfsharp.net/viewtopic.php?f=2&t=2003&p=5737#p5737

亲切的问候,

请您参考如下方法:

我认为这是 PDF sharp 的局限性,因为我在该论坛上没有得到他们的回复或帮助。我打开了那里的代码并进行了以下更改以更正错误。首先,我在 SecurityHandler.cs 类上添加了一个新属性

public string OwnerPassword 
{ 
  set { SecurityHandler.OwnerPassword = value; } 
} 
 
/// <summary> 
/// TODO: JOSH 
/// </summary> 
public bool MaintainOwnerAndUserPassword 
{ 
    get { return SecurityHandler.MaintainOwnerAndUserPassword; } 
    set { SecurityHandler.MaintainOwnerAndUserPassword = value; } 
} 

然后我将 PdfDocument.cs 类的 doSave 方法更改为如下所示:

    void DoSave(PdfWriter writer) 
{ 
  if (this.pages == null || this.pages.Count == 0) 
    throw new InvalidOperationException("Cannot save a PDF document with no pages."); 
 
  try 
  { 
    bool encrypt = this.securitySettings.DocumentSecurityLevel != PdfDocumentSecurityLevel.None; 
    if (encrypt) 
    { 
      PdfStandardSecurityHandler securityHandler = this.securitySettings.SecurityHandler; 
      if (securityHandler.Reference == null) 
        this.irefTable.Add(securityHandler); 
      else 
        Debug.Assert(this.irefTable.Contains(securityHandler.ObjectID)); 
      this.trailer.Elements[PdfTrailer.Keys.Encrypt] = this.securitySettings.SecurityHandler.Reference; 
    } 
    else 
      this.trailer.Elements.Remove(PdfTrailer.Keys.Encrypt); 
 
    PrepareForSave(); 
 
    if (encrypt && !securitySettings.SecurityHandler.MaintainOwnerAndUserPassword) 
      this.securitySettings.SecurityHandler.PrepareEncryption(); 
 
... 

最后,我将 PDFSecuritySettings.cs 上的 CanSave 方法更改为:

    internal bool CanSave(ref string message) 
{ 
  if (this.documentSecurityLevel != PdfDocumentSecurityLevel.None) 
  { 
    if ((SecurityHandler.userPassword == null || SecurityHandler.userPassword.Length == 0) && 
        (SecurityHandler.ownerPassword == null || SecurityHandler.ownerPassword.Length == 0) && 
        !SecurityHandler.MaintainOwnerAndUserPassword) 
    { 
      message = PSSR.UserOrOwnerPasswordRequired; 
      return false; 
    } 
  } 
  return true; 
} 

这应该允许您设置 MaintainOwnerAndUserPassword 设置,假设您已经有一个散列的用户名和密码,它应该可以正常工作,

彻底结束。