NoPassReversePages.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Pdf.Security;
using GrapeCity.Documents.Text;

namespace DsPdfWeb.Demos
{
    // This example shows how to load a password protected PDF without specifying the password,
    // and change (reverse) the order of the pages in the PDF.
    // The modified PDF is saved and re-opened with the password so that we can show it in the demo.
    public class NoPassReversePages
    {
        public int CreatePDF(Stream stream)
        {
            using var fsSrc = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands-password-user.pdf"));
            // Set up DecryptionOptions to allow loading password protected PDFs without password:
            var dopt = new DecryptionOptions() { ThrowExceptionIfInvalidPassword = false };
            var docSrc = new GcPdfDocument();
            docSrc.Load(fsSrc, dopt);

            for (int i = 0; i < docSrc.Pages.Count / 2; ++i)
                docSrc.Pages.Swap(i, docSrc.Pages.Count - 1 - i);

            // Demo site specific:
            // We save the modified password protected document to a temp file,
            // and load it again with the password, so that the demo site can show it
            // without asking the user for a password (the block is to delete the temp file):
            var fn = Path.GetTempFileName();
            {
                docSrc.Save(fn);
                var doc = new GcPdfDocument();
                using var fs = File.OpenRead(fn);
                doc.Load(fs, "user");
                doc.Save(stream);
            }
            File.Delete(fn);
            return docSrc.Pages.Count;
        }
    }
}