Search code examples
c#pdfpasswordswebapipdfsharp

How to unlock password protected PDF?


I created an API that adds a password to the PDF and locks it, now I want to make one that removes the password.
.NET 6 web API

Here is the code for locking:

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");
}

PS: I have the password, I just need to unlock it.


Solution

  • Sample code that unprotects a PDF when the password is known:
    https://pdfsharp.net/wiki/UnprotectDocument-sample.ashx

    Sample code that protects a PDF with a password:
    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);