如何解锁受密码保护的pdf

问题描述 投票:0回答:1

我创建了一个 api,为 pdf 添加密码并锁定它,现在我想制作一个删除密码的 api。 .Net6 网络 API

这是锁定的代码:

using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Security;

public async Task<CustomFile> AddPasswordToPdf(AddPasswordToPdfDto file)
{
    if (file.PdfUrl == null || file.PdfUrl.Length == 0)
    { 
        return null;
    }

    string originalFileName = Path.GetFileNameWithoutExtension(file.PdfUrl.FileName);

    using var memoryStream = new MemoryStream();
    file.PdfUrl.CopyTo(memoryStream);

    PdfDocument pdfDocument = PdfReader.Open(memoryStream, PdfDocumentOpenMode.Modify);

    PdfSecuritySettings securitySettings = pdfDocument.SecuritySettings; 
    securitySettings.UserPassword = file.Password;
    securitySettings.OwnerPassword = file.Password; 
    securitySettings.PermitAccessibilityExtractContent = false; 

    MemoryStream protectedPdfStream = new MemoryStream();
    pdfDocument.Save(protectedPdfStream, closeStream: false);

    protectedPdfStream.Seek(0, SeekOrigin.Begin);

    return new CustomFile(protectedPdfStream.ToArray(), "application/pdf", $"  {originalFileName}-PasswordProtected.pdf");
}

诗。我有密码,只需解锁即可

c# pdf passwords webapi pdfsharp
1个回答
0
投票

已知密码时取消 PDF 保护的示例代码:
https://pdfsharp.net/wiki/UnprotectDocument-sample.ashx

使用密码保护 PDF 的示例代码:
https://pdfsharp.net/wiki/ProtectDocument-sample.ashx

// Open the document with the owner password.
var document = PdfReader.Open(filenameDest, "owner");
var hasOwnerAccess = document.SecuritySettings.HasOwnerPermissions;
 
// A document opened with the owner password is completely unprotected
// and can be modified.
XGraphics gfx = XGraphics.FromPdfPage(document.Pages[0]);
gfx.DrawString("Some text...",
  new XFont("Times New Roman", 12), XBrushes.Firebrick, 50, 100);
 
// The modified document is saved without any protection applied.
PdfDocumentSecurityLevel level = document.SecuritySettings.DocumentSecurityLevel;
 
// If you want to save it protected, you must set the DocumentSecurityLevel
// or apply new passwords.
// In the current implementation the old passwords are not automatically
// reused. See 'ProtectDocument' sample for further information.
 
// Save the document...
document.Save(filenameDest);
© www.soinside.com 2019 - 2024. All rights reserved.