我认为这是 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 设置,并假设您已经有一个散列的用户名和密码,它应该可以正常工作,
完了,走吧。