Decrypt PDF File in C++

Use PdfFileSecurity for this task. The examples below retain the original C++ code and API Reference steps.

Decrypt PDF with owner password

Decrypt the PDF using the owner password and save the result.

  1. Create PdfFileSecurity.
  2. Bind the PDF input with Facade::BindPdf().
  3. Decrypt the bound PDF with PdfFileSecurity::MfDecryptFile().
  4. Save the resulting PDF with PdfFileSecurity::Save().
  5. Close the facade with PdfFileSecurity::Close().
#include <Aspose.PDF.Cpp/Facades/PdfFileSecurity.h>
#include <system/string.h>

namespace Facades::Examples::PDF_FileSecurity
{
using namespace System;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Facades;

void DecryptPdfWithOwnerPassword(String inputFile, String outputFile)
{
    auto fileSecurity = MakeObject<PdfFileSecurity>();
    fileSecurity->BindPdf(inputFile);
    fileSecurity->MfDecryptFile(u"owner_password");
    fileSecurity->Save(outputFile);
    fileSecurity->Close();
}
} // namespace Facades::Examples::PDF_FileSecurity

Try decrypt PDF without exception

Check TryDecryptFile and save only when it returns true; otherwise print a diagnostic.

  1. Create PdfFileSecurity.
  2. Bind the PDF input with Facade::BindPdf().
  3. Attempt decryption and check the result of PdfFileSecurity::TryDecryptFile().
  4. Save the PDF with PdfFileSecurity::Save() only after the operation succeeds.
  5. Close the facade with PdfFileSecurity::Close().
  6. Print the results or diagnostic messages shown in the example.
#include <Aspose.PDF.Cpp/Facades/PdfFileSecurity.h>
#include <iostream>
#include <system/string.h>

namespace Facades::Examples::PDF_FileSecurity
{
using namespace System;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Facades;

void TryDecryptPdfWithoutException(String inputFile, String outputFile)
{
    auto fileSecurity = MakeObject<PdfFileSecurity>();
    fileSecurity->BindPdf(inputFile);
    if (fileSecurity->TryDecryptFile(u"owner_password"))
    {
        fileSecurity->Save(outputFile);
    }
    else
    {
        std::cout << "Decryption failed. Check password or document security." << std::endl;
    }
    fileSecurity->Close();
}
} // namespace Facades::Examples::PDF_FileSecurity