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.
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