# Convert password-protected documents to PDF A technical walkthrough of 4 code patterns for converting password-protected Word and PDF documents to PDF with GroupDocs.Conversion for .NET, supplying a password only when a document asks for one. {{< alert style="info" >}} 💡 Full working example available on GitHub: [convert-password-protected-documents-to-pdf-dotnet](https://github.com/groupdocs-conversion/convert-password-protected-documents-to-pdf-dotnet) {{< /alert >}} ## Introduction Password-on-demand conversion is a GroupDocs.Conversion capability for .NET that converts a batch of Word and PDF documents to PDF when only some of them are password-protected. A folder of uploads or a ZIP archive does not say which files are protected, and a protected file looks like any other until the load fails. Since GroupDocs.Conversion 26.11 the load options delegate is called once per load attempt, so the failure itself becomes the moment to look up a password. This guide compares 4 methods built on that behavior: a single file, a folder, the entries of a ZIP archive, and a ZIP archive converted without any passwords. They differ in where the lookup happens and in what the code does when no usable password exists. ## What This Guide Covers The guide covers `LoadContext.Attempt`, `LoadContext.FailedLoadOptions` and `IPasswordLoadOptions` on the load side, and `SaveContext` on the save side. Every output named below comes from running the sample on its own resources: a plain `sample.docx`, a protected `password_protected.docx` (password `12345`), a protected `sample_with_password.pdf` and a `bundle.zip` holding the two Word files. The code on this page uses the namespaces `GroupDocs.Conversion`, `GroupDocs.Conversion.Exceptions`, `GroupDocs.Conversion.FileTypes`, `GroupDocs.Conversion.Options.Convert` and `GroupDocs.Conversion.Options.Load`. **Prerequisites:** - .NET SDK 8.0 or later - GroupDocs.Conversion for .NET 26.11.0 ```bash dotnet add package GroupDocs.Conversion --version 26.11.0 ``` Without a license the sample runs in evaluation mode and evaluation limits apply. A [temporary license](https://purchase.groupdocs.com/temporary-license) removes them while you test. ## Quick Decision Matrix | Scenario | Method | Why | |----------|--------|-----| | One file, maybe protected | Method 1 | The attempt count shows what happened | | Folder of mixed files, passwords by file name | Method 2 | Per-file errors, loop continues | | ZIP archive, passwords known | Method 3 | Same lookup, keyed by entry name | | ZIP archive, no passwords | Method 4 | Protected entries come back unchanged | ## Detailed Method Analysis ### Method 1: ConvertWithPasswordWhenAsked **Overview:** The smallest form of the idea. The delegate returns `null` on attempt 1 and answers with a password only on attempt 2. #### How It Works `LoadContext.Attempt` is 1 on the first load. If that load fails because a password is required, the delegate is asked again, this time with `Attempt` at 2, the exception in `LoadContext.LoadFailure` and the options that just failed, copied into `LoadContext.FailedLoadOptions`. A copy that implements `IPasswordLoadOptions` takes a `Password`, and returning it loads the document again. In the sample that copy is `WordProcessingLoadOptions` for the DOCX and `PdfLoadOptions` for the PDF. `inputPath`, `outputPath` and `password` are the method's parameters; the sample passes `12345` for `password_protected.docx`. #### When to Use - A single upload where the user may have typed a password. - A code path that must accept plain documents without a branch. - Not recommended for: a batch, unless you catch the exception around each call. #### Implementation ```csharp int attempts = 0; Func loadOptions = context => { attempts = context.Attempt; if (context.Attempt < 2 || context.FailedLoadOptions is not IPasswordLoadOptions failed) { return null; } Console.WriteLine($" asked again: {context.LoadFailure?.Message}"); failed.Password = password; return (LoadOptions)failed; }; ``` ```csharp using (var converter = new Converter(inputPath, loadOptions)) { converter.Convert(outputPath, new PdfConvertOptions()); } Console.WriteLine($" {Path.GetFileName(inputPath)}: attempts {attempts}"); return attempts; ``` #### Pros and Cons **Advantages:** - A plain document costs one delegate call: `sample.docx` ends with "attempts 1". - The returned count tells you which documents were protected. **Limitations:** - One password per call, so a folder needs Method 2. - A wrong password is not retried, because the delegate is never called a third time. ### Method 2: ConvertInbox **Overview:** Method 1 in a loop over a folder, with the password moved into a lookup keyed by file name. #### How It Works The sample keeps its passwords in a dictionary from file name to password. For each file the delegate checks that the failed options accept a password and that `LoadContext.SourceFileName` has an entry. A protected document with no entry gets `null` back and fails with `PasswordRequiredException`; a stored password that is wrong fails with `IncorrectPasswordException`. The loop catches both and carries on. `inboxFolder`, `outputFolder` and `passwords` are the method's parameters, and `passwords` receives the `Passwords` dictionary shown below. I ran this method over the sample inbox of three documents: 2 converted, and the third was reported by name with "The document password is incorrect". #### When to Use - A shared folder where protected and plain files are mixed. - A job that has to name each failed file in its log. #### Implementation ```csharp private static readonly Dictionary Passwords = new() { ["password_protected.docx"] = "12345", ["sample_with_password.pdf"] = "not-the-password" }; ``` ```csharp Func loadOptions = context => { if (context.FailedLoadOptions is not IPasswordLoadOptions failed || !passwords.TryGetValue(context.SourceFileName, out string? password)) { return null; } failed.Password = password; return (LoadOptions)failed; }; ``` The loop around that delegate declares `loadOptions` once per file and wraps the conversion in a `try` block. ```csharp int converted = 0; foreach (string inputPath in Directory.GetFiles(inboxFolder).OrderBy(path => path)) { string name = Path.GetFileName(inputPath); try { using (var converter = new Converter(inputPath, loadOptions)) { converter.Convert(Path.Combine(outputFolder, name + ".pdf"), new PdfConvertOptions()); } converted++; Console.WriteLine($" converted: {name}"); } 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}"); } } return converted; ``` #### Pros and Cons **Advantages:** - Only protected files reach the lookup. - Both failures are named: "Password is required to convert password protected docx document" and "The document password is incorrect". **Limitations:** - The sample's table is keyed by file name alone, so two files with the same name would get the same password. - The caller owns the reporting. ### Method 3: ConvertArchiveEntries **Overview:** The same delegate on a ZIP archive, with `SaveContext` deciding each output name. #### How It Works The delegate is called for the archive and for every entry. A protected Word document inside the archive is asked again on its own, with its own name in `SourceFileName`, so one dictionary serves loose files and entries alike. Each `SaveContext` carries `SourceFileName` and `TargetFormat`, and the sample joins them as `{SourceFileName}.{TargetFormat.Extension}`. On `bundle.zip` it writes `password_protected.docx.pdf` and `sample.docx.pdf`. `archivePath`, `outputFolder` and `passwords` are the method's parameters, with `passwords` the same dictionary as in Method 2. #### When to Use - Archives sent by someone who also sent the passwords. - A pipeline that treats folders and archives with one lookup. #### Implementation ```csharp int written = 0; Func loadOptions = context => { if (context.FailedLoadOptions is not IPasswordLoadOptions failed || !passwords.TryGetValue(context.SourceFileName, out string? password)) { return null; } Console.WriteLine($" password supplied for entry {context.SourceFileName}"); failed.Password = password; return (LoadOptions)failed; }; ``` ```csharp using (var converter = new Converter(archivePath, loadOptions)) { converter.Convert((SaveContext entry) => { written++; string name = $"{entry.SourceFileName}.{entry.TargetFormat.Extension}"; Console.WriteLine($" written: {name}"); return File.Create(Path.Combine(outputFolder, name)); }, new PdfConvertOptions()); } ``` #### Pros and Cons **Advantages:** - Two PDFs of 239,493 bytes each in the sample run, one per entry. - No second lookup table for archives. **Limitations:** - Every output name assumes a PDF, which is safe only when all entries convert. ### Method 4: KeepEntriesThatNeedAPassword **Overview:** A ZIP archive converted with no delegate at all, keeping whatever cannot be converted. #### How It Works The conversion still succeeds without a delegate. Plain entries become PDF files, and a protected entry is handed back unchanged with `SaveContext.TargetFormat` equal to `FileType.Unknown`. The sample checks that value and saves such an entry under its own name; the kept `password_protected.docx` is byte-identical to the original, 51,712 bytes. `archivePath` and `outputFolder` are the method's parameters. #### When to Use - A first pass over an archive before anyone has the passwords. - A step that must lose nothing, whatever the contents. - Not recommended for: a run that has to end with PDF files only. #### Implementation ```csharp int kept = 0; 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}"; kept += unchanged ? 1 : 0; string action = unchanged ? "kept as is" : "converted "; Console.WriteLine($" {action}: {name}"); return File.Create(Path.Combine(outputFolder, name)); }, new PdfConvertOptions()); } ``` #### Pros and Cons **Advantages:** - The archive converts even when nothing is known about its entries. - The `TargetFormat` check keeps a protected DOCX from carrying a `.pdf` name. **Limitations:** - The protected entry stays protected, so a second pass with passwords is needed. ## How do I tell which documents in a batch are protected? You do not have to. Open every document as it is, with the delegate returning `null` on attempt 1. A protected document fails with `PasswordRequiredException`, and that failure is what triggers the second delegate call: it arrives with `Attempt` at 2 and the failed options in `FailedLoadOptions`. A plain document makes exactly one call, which is how Method 1 counts attempts. ## Real-World Use Cases **A shared folder of mixed uploads.** Documents land in one folder and a stored password may be out of date. Method 2 converts 2 of the 3 sample documents and reports the stale one by name. **Archives from outside.** A ZIP archive arrives with a protected Word document among plain ones. Method 3 writes 2 PDFs when the password is known; Method 4 writes `sample.docx.pdf` and keeps `password_protected.docx` as it arrived. ## Common Pitfalls 1. **Supplying a password on attempt 1.** A password is only needed after a load has failed, so supplying one first means guessing for a document that may be plain. Return `null` while `Attempt` is below 2, as Method 1 does. 2. **Assuming every archive entry becomes a PDF.** A protected entry without a password is handed back unchanged, so appending `.pdf` saves the original DOCX under a misleading name. Compare `TargetFormat` with `FileType.Unknown` first, as Method 4 does. 3. **Expecting a third attempt.** A wrong password ends in `IncorrectPasswordException`. Catch it per file and report the name. ## FAQ **Q: Which classes accept a password through this mechanism?** A: Six load options classes implement `IPasswordLoadOptions`, among them `WordProcessingLoadOptions` and `PdfLoadOptions`, which the sample measured. **Q: What happens when no password is stored for a protected file?** A: The delegate returns `null` on attempt 2, which means no retry, and the conversion fails with `PasswordRequiredException`. Method 2 catches it and names the file. **Q: Is a license required?** A: No. Without one the sample runs in evaluation mode and evaluation limits apply. A [temporary license](https://purchase.groupdocs.com/temporary-license) removes them during testing. ## Conclusion All four methods rest on one change in how the load options delegate is called: a second call after a failed load, with the failed options in hand. Use Method 2 for a folder, Method 3 for an archive whose passwords you hold, and Method 4 for entries that have no password yet. ## See Also - [In-depth blog article about this project](https://blog.groupdocs.com/conversion/convert-password-protected-documents-to-pdf-net/) - [Load password-protected document](https://docs.groupdocs.com/conversion/net/load-password-protected-document/#supply-the-password-only-when-a-document-needs-it) - [Context objects: complete guide](https://docs.groupdocs.com/conversion/net/context-objects-complete-guide/) - [IPasswordLoadOptions in the API reference](https://reference.groupdocs.com/conversion/net/groupdocs.conversion.options.load/ipasswordloadoptions/) - [LoadContext in the API reference](https://reference.groupdocs.com/conversion/net/groupdocs.conversion/loadcontext/) - [GitHub repository](https://github.com/groupdocs-conversion/convert-password-protected-documents-to-pdf-dotnet) - [GroupDocs.Conversion for .NET documentation](https://docs.groupdocs.com/conversion/net/)