We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

C# when merging a list of document streams losing security settings from all documents

Hi there, I’m working with a list of streams which were previously documents. We’re attempting to merge these all into one document through this process and everything works, except the security setting are lost. I’m hoping there is something I’m missing here that would prevent that. In my test case I have password protected one document with Restricted Editing > Filling in forms. The second is protected with a password and Only Changes with exceptions within.

public static void MergeDocuments(IEnumerable<Stream> streams, ref Stream destination)
{
    if (destination == null)
        throw new ArgumentNullException(nameof(destination));

    var documentStreams = streams.ToList();

    if (documentStreams.Count == 0)
        new Document().Save(destination, null);

    var finalDocument = new Document();
    finalDocument.RemoveAllChildren();

    using (documentStreams.WithReset())
    {
        foreach (var documentStream in documentStreams)
        {
            documentStream.Position = 0;
            var document = new Document(documentStream);

            // Each Document should start with a new page
            document.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;

            document.FirstSection.PageSetup.RestartPageNumbering = true;
            document.FirstSection.PageSetup.PageStartingNumber = 1;
            document.FirstSection.HeadersFooters.LinkToPrevious(false);

            RemoveEmptyHeaderAndFooter(document);

           // Update each document with new pages
            document.UpdatePageLayout();
            finalDocument.AppendDocument(document, ImportFormatMode.KeepSourceFormatting);
        }
    }

    // refer to Aspose api docs → https://docs.aspose.com/words/net/join-and-append-documents/#controlling-how-page-numbering-is-handled
    ConvertNumPageFieldsToPageRef(finalDocument);

    foreach (Section section in finalDocument.Sections)
    {
        if (section.HeadersFooters.Count == 0)
        {
            var pageSetup = section.PageSetup;
            pageSetup.FooterDistance = 0;
            pageSetup.HeaderDistance = 0;
        }
        section.HeadersFooters.LinkToPrevious(false);
    }

    // This needs to be called in order to update the new fields with page numbers.
    finalDocument.UpdatePageLayout();

    finalDocument.Save(destination, null);
}

@bsmithlti Protection is applied to whole document. Please see our documentation to learn more about protection. So you should either merge your documents to the main protected document or protect the output document before saving.