đź’ˇ Full working example available on GitHub: convert-password-protected-documents-to-pdf-dotnet
Password-on-demand conversion is a GroupDocs.Conversion workflow for .NET that postpones the password decision until a load actually fails, so a batch of plain and protected files needs no list of which is which. The usual order is a decision before opening, is this file protected and with which password. Here the order is reversed: the code decides after the failure, when it finally knows.
The Old Way Was Painful
Picture a folder that collects files from several senders: a few DOCX files, a PDF, a ZIP archive. Nothing in a file name says that it needs a password. To convert the folder you either open every file by hand to find out, or you attach a password to every load and hope that the right one reaches the right file. The first protected document that reaches a loop without a password stops it with a PasswordRequiredException, and the message names the format: “Password is required to convert password protected docx document”.
A ZIP archive makes it harder. The protected file is an entry inside the archive, so you cannot see it from the outside, and each entry needs its own answer. Convert the archive without any password logic and the protected entry comes back unchanged, which sounds harmless until a script appends .pdf to every output name. The file is then still the original protected DOCX, but its name says it is a PDF.
The real cost of guessing: a protected file saved under a
There’s a Better Way
GroupDocs.Conversion for .NET 26.11 calls the load options delegate, a Func<LoadContext, LoadOptions>, once per load attempt. The first attempt carries LoadContext.Attempt equal to 1. A load that fails because a password is required or wrong earns the delegate exactly one more call, and that call brings its own evidence: Attempt is 2, LoadContext.LoadFailure holds the failure, and LoadContext.FailedLoadOptions holds a copy of what was used. Set Password on the copy if it implements IPasswordLoadOptions, return it, and the document loads again.
The classes that implement IPasswordLoadOptions are WordProcessingLoadOptions, PdfLoadOptions, SpreadsheetLoadOptions, PresentationLoadOptions, NoteLoadOptions and CompressionLoadOptions. That is all the delegate needs to know about a document: it never inspects the file itself, it only checks whether the failed options accept a password. A lookup key is already in the context, because LoadContext.SourceFileName holds the file name, or the entry name inside an archive.
Before we start, you’ll need:
- .NET SDK 8.0 or later
- GroupDocs.Conversion for .NET 26.11.0 (get a temporary license to remove evaluation limits)
- One protected and one plain document, such as the sample’s
password_protected.docx(password12345) andsample.docx
The code below uses the namespaces GroupDocs.Conversion, GroupDocs.Conversion.Exceptions, GroupDocs.Conversion.FileTypes, GroupDocs.Conversion.Options.Convert and GroupDocs.Conversion.Options.Load.
Install with one command:
dotnet add package GroupDocs.Conversion --version 26.11.0
The New Way: Ask Only When Asked
Here is what the same task looks like with the second attempt. The examples come from the four methods of the sample project, and every output named below comes from running them.
Step 1 - Open Everything as It Is
The delegate returns null while Attempt is below 2, so every document is first opened without a password. A plain document never gets further: the sample records context.Attempt on every call, and sample.docx ends with one call, reported as “attempts 1”. Here password is a string parameter; the sample passes 12345.
Func<LoadContext, LoadOptions?> loadOptions = context =>
{
if (context.Attempt < 2
|| context.FailedLoadOptions is not IPasswordLoadOptions failed)
{
return null;
}
failed.Password = password;
return (LoadOptions)failed;
};
For password_protected.docx, attempt 1 fails with the message quoted above, the delegate runs again, and the second attempt converts: “attempts 2”. The failed copy is WordProcessingLoadOptions for the DOCX and PdfLoadOptions for the PDF, and both implement IPasswordLoadOptions.
Step 2 - Look the Password Up by File Name
For a folder, one password is not enough. The sample keeps a dictionary from file name to password and reads the key from LoadContext.SourceFileName. In the code below, passwords is that dictionary: password_protected.docx maps to 12345 and sample_with_password.pdf to a deliberately wrong value. A file with no entry gets null back, which means no retry.
Func<LoadContext, LoadOptions?> loadOptions = context =>
{
if (context.FailedLoadOptions is not IPasswordLoadOptions failed
|| !passwords.TryGetValue(context.SourceFileName, out string? password))
{
return null;
}
failed.Password = password;
return (LoadOptions)failed;
};
Because the delegate answers only when a failed copy accepts a password and the name has an entry, plain documents pass through it untouched.
Step 3 - Report Each Failure by Name
A batch needs to survive one bad file. Wrap each conversion in a try block and catch the two exception types. In the sample, loadOptions is the Step 2 delegate declared inside the loop, and outputFolder is the folder that receives the PDFs.
foreach (string inputPath in Directory.GetFiles("resources/inbox"))
{
string name = Path.GetFileName(inputPath);
try
{
using var converter = new Converter(inputPath, loadOptions);
converter.Convert(Path.Combine(outputFolder, name + ".pdf"),
new PdfConvertOptions());
}
catch (PasswordRequiredException e)
{
Console.WriteLine($" no password on file for {name}: {e.Message}");
}
catch (IncorrectPasswordException e)
{
Console.WriteLine($" wrong password on file for {name}: {e.Message}");
}
}
I ran this on the sample inbox of three documents. It converted sample.docx and password_protected.docx, and it reported sample_with_password.pdf by name with “The document password is incorrect”, because the sample stores a wrong password for that file on purpose. The delegate is never called a third time, so a wrong password fails once.
Step 4 - Convert the Entries of a ZIP Archive
The delegate is called for the archive and for each entry, and a protected entry is asked again on its own, with its own name in SourceFileName. The same dictionary therefore serves files and entries. SaveContext names each PDF from the entry name and the target extension. Here archivePath is resources/bundle.zip, outputFolder is the folder for the PDFs, and loadOptions is the Step 2 delegate.
using (var converter = new Converter(archivePath, loadOptions))
{
converter.Convert((SaveContext entry) =>
{
string name = $"{entry.SourceFileName}.{entry.TargetFormat.Extension}";
return File.Create(Path.Combine(outputFolder, name));
}, new PdfConvertOptions());
}
On bundle.zip, which holds password_protected.docx and sample.docx, this writes 2 PDFs, password_protected.docx.pdf and sample.docx.pdf, of 239,493 bytes each in the sample run.
Without any passwords the same archive still converts. sample.docx becomes sample.docx.pdf, and the protected entry comes back with SaveContext.TargetFormat equal to FileType.Unknown. Checking that value keeps the entry under its own name, and the kept file is byte-identical to the original password_protected.docx, 51,712 bytes.
using (var converter = new Converter(archivePath))
{
converter.Convert((SaveContext entry) =>
{
bool unchanged = entry.TargetFormat == FileType.Unknown;
string name = unchanged
? entry.SourceFileName
: $"{entry.SourceFileName}.{entry.TargetFormat.Extension}";
return File.Create(Path.Combine(outputFolder, name));
}, new PdfConvertOptions());
}
What happens to a protected file when I have no password for it?
It fails with PasswordRequiredException when the delegate returns null on attempt 2. I removed the PDF from the dictionary and ran the folder again: the message was “Password is required to convert password protected pdf document”. With no delegate at all, a protected DOCX fails the same way. Catch the exception per file, log the name, and the rest of the folder converts.
Side-by-Side: Without and With the Delegate
| Without the delegate | With the delegate (26.11) | |
|---|---|---|
| Protected DOCX | PasswordRequiredException: “Password is required to convert password protected docx document” |
Converts on attempt 2 with 12345 |
Protected entry in bundle.zip |
Handed back as the original file, with TargetFormat equal to FileType.Unknown |
Converts to password_protected.docx.pdf |
Both rows come from the sample run. A stored password that is wrong has no row here, because without a delegate nothing is supplied: with the delegate it ends in IncorrectPasswordException, once, and the folder method catches it per file. The sample’s inbox is built from exactly that mix: one plain document, one protected DOCX with a known password and one protected PDF with a wrong one.
Real-World Example: A Mixed Inbox
A job that imports a shared folder gets whatever the senders put there. With the second attempt, the import code holds a table of known passwords and nothing else. Plain documents convert on the first attempt. Protected documents with a current password convert on the second attempt. A document whose password is out of date shows up in the log under its own name, and the job moves to the next file. That is what the sample’s folder method printed: 2 documents converted, 1 reported.
What Else Can You Do with GroupDocs.Conversion for .NET?
- Count the attempts: record
context.Attemptas the sample does, and the 1 or 2 you end with tells you afterwards which documents were protected. - Read the failure:
LoadContext.LoadFailurecarries the exception that caused the retry, so the delegate can log its message before it answers. - Learn the context: the context objects guide lists the members of
LoadContext.
The load password-protected document page covers this feature in the documentation.
Conclusion
The folder of three documents needed no list of protected files. One delegate opened each document as it was, asked once when a load failed, and left the rest to two catch blocks. The archive needed one more check, TargetFormat against FileType.Unknown, so a protected entry could not pass as a PDF.
Ready to convert your own batch?
- Get a temporary license
- Read about loading password-protected documents
- Check the IPasswordLoadOptions reference
- Check out the sample project on GitHub