示例#1
0
        public static void SearchAndReplace(string template, string path, string currentUser, string period, List <ViewModels.UserTableViewModel> stats)
        {
            WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(template, false);
            var newDoc = wordprocessingDocument.Clone();

            File.Copy(template, path);
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(path, true))
            {
                string docText = null;

                using (StreamReader sr = new StreamReader(wordDocument.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }

                docText = ReplaceByWord(docText, "currentDateTempl", DateTime.Now.ToString("dd.MM.yyyy"));
                docText = ReplaceByWord(docText, "currentUser", currentUser);
                docText = ReplaceByWord(docText, "period", period);

                using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
                {
                    sw.Write(docText);
                }
                EditTable(wordDocument, stats);
                wordDocument.Save();
            }
        }
示例#2
0
 private static byte[] GetByteArray(WordprocessingDocument labelDoc)
 {
     using (var documentStream = new MemoryStream())
         using (var wordDocument = (WordprocessingDocument)labelDoc.Clone(documentStream))
         {
             documentStream.Seek(0, SeekOrigin.Begin);
             return(documentStream.ToArray());
         }
 }
示例#3
0
文件: MyWord.cs 项目: iccknu/Mjolnir
 public void Save()
 {
     mainDocumentPart.Document.Save();
     wordProcessingDocument.Save();
     //rewriting whole file
     using (Stream stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
     {
         using (OpenXmlPackage docfile = wordProcessingDocument.Clone(stream))
         {
             docfile.Save();
         }
     }//stream is not automaticaly closed when document closed (when using Clone)
 }
示例#4
0
    public async Task <string> Translate(IFormFile file, bool translateHeader, bool translateFooter)
    {
        var filePath = Path.GetTempFileName();

        Console.WriteLine($"[FILE] {filePath}");
        using (var ms = new MemoryStream())
        {
            await file.CopyToAsync(ms);

            using (WordprocessingDocument worddoc = WordprocessingDocument.Open(ms, true))
            {
                OpenXmlPowerTools.SimplifyMarkupSettings settings = new OpenXmlPowerTools.SimplifyMarkupSettings
                {
                    AcceptRevisions                   = false,
                    NormalizeXml                      = false, //setting this to false reduces translation quality, but if true some documents have XML format errors when opening
                    RemoveBookmarks                   = true,
                    RemoveComments                    = true,
                    RemoveContentControls             = true,
                    RemoveEndAndFootNotes             = true,
                    RemoveFieldCodes                  = true,
                    RemoveGoBackBookmark              = true,
                    RemoveHyperlinks                  = false,
                    RemoveLastRenderedPageBreak       = true,
                    RemoveMarkupForDocumentComparison = true,
                    RemovePermissions                 = false,
                    RemoveProof           = true,
                    RemoveRsidInfo        = true,
                    RemoveSmartTags       = true,
                    RemoveSoftHyphens     = true,
                    RemoveWebHidden       = true,
                    ReplaceTabsWithSpaces = false
                };
                OpenXmlPowerTools.MarkupSimplifier.SimplifyMarkup(worddoc, settings);
                Body body  = worddoc.MainDocumentPart.Document.Body;
                var  texts = body.Descendants <Text>();
                foreach (var text in texts)
                {
                    if (!string.IsNullOrWhiteSpace(text.Text))
                    {
                        text.Text = await this.CallTranslator(text.Text);
                    }
                }
                var clone = worddoc.Clone(filePath);
                clone.Close();
                worddoc.Close();
            }
        }
        return(filePath);
    }
        public bool putDataToFile(List <string> data)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(pathFile, false))
            {
                var docNew = (WordprocessingDocument)doc.Clone(Directory.GetCurrentDirectory() + "\\output.docx", true);
                var body   = docNew.MainDocumentPart.Document.Body;

                var count = 0;

                foreach (var para in body.Elements <Paragraph>())
                {
                    foreach (var run in para.Elements <Run>())
                    {
                        foreach (var text in run.Elements <Text>())
                        {
                            text.Text = data[count];
                            count++;
                        }
                    }
                }
                docNew.Close();
                // using (WordprocessingDocument docNew = WordprocessingDocument.Create(Directory.GetCurrentDirectory() +  "\\output.docx", WordprocessingDocumentType.Document))
                // {
                //     // copy parts from source document to new document
                //     foreach (var part in doc.Parts)
                //         docNew.AddPart(part.OpenXmlPart, part.RelationshipId);
                //
                //     var body = docNew.MainDocumentPart.Document.Body;
                //
                //     var count = 0;
                //
                //     foreach (var para in body.Elements<Paragraph>())
                //     {
                //         foreach (var run in para.Elements<Run>())
                //         {
                //             foreach (var text in run.Elements<Text>())
                //             {
                //                 text.Text = data[count];
                //                 count++;
                //             }
                //         }
                //     }
                //     docNew.Close();
                // }
                doc.Close();
            }
            return(true);
        }
示例#6
0
        public byte[] BuildTemplate(string fileName)
        {
            var bytes = File.ReadAllBytes(fileName);
            var ms    = new MemoryStream();

            ms.Write(bytes, 0, bytes.Length);
            ms.Position = 0;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true)) {
                var body = wordDoc.MainDocumentPart.Document.Body;
                ReplaceTable(body);
                ReplaceTemplate(body);
                ReplacePicture(wordDoc.MainDocumentPart, body);
                using (var ms2 = new MemoryStream()) {
                    wordDoc.Clone(ms2);
                    return(ms2.ToArray());
                }
            };
            ms.Dispose();
        }
示例#7
0
        public static byte[] GetRentalAgreement(RentalAgreementDocViewModel reportModel, string name)
        {
            try
            {
                char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[] { 10 });
                char   crLf       = characters[0];

                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Rental Agreement template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        using (MemoryStream agreementStream = new MemoryStream())
                        {
                            WordprocessingDocument agreementDocument = (WordprocessingDocument)wordTemplate.Clone(agreementStream);
                            agreementDocument.Save();

                            // create note
                            string note = "";
                            if (reportModel.Note != null)
                            {
                                foreach (NoteLine line in reportModel.Note)
                                {
                                    if (!string.IsNullOrEmpty(note))
                                    {
                                        note += $"{crLf.ToString()}{line.Line}";
                                    }
                                    else
                                    {
                                        note += $"{line.Line}";
                                    }
                                }
                            }

                            // equipment full name
                            string equipmentName = $"{reportModel.Equipment.Year}/" +
                                                   $"{reportModel.Equipment.Make}/" +
                                                   $"{reportModel.Equipment.Model}/" +
                                                   $"{reportModel.Equipment.Size}/" +
                                                   $"{reportModel.Equipment.SerialNumber}";

                            // rates included in total
                            string rateString1 = "";
                            string comment1    = "";
                            if (reportModel.RentalAgreementRatesWithTotal != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesWithTotal)
                                {
                                    if (!string.IsNullOrEmpty(rateString1))
                                    {
                                        rateString1 += $"{crLf.ToString()}{rate.RateString}";
                                        comment1    += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        rateString1 += $"{rate.RateString}";
                                        comment1    += $"{rate.Comment}";
                                    }
                                }
                            }

                            // rates not included in total
                            string rateString2 = "";
                            string comment2    = "";
                            if (reportModel.RentalAgreementRatesWithoutTotal != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesWithoutTotal)
                                {
                                    if (!string.IsNullOrEmpty(rateString2))
                                    {
                                        rateString2 += $"{crLf.ToString()}{rate.RateString}";
                                        comment2    += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        rateString2 += $"{rate.RateString}";
                                        comment2    += $"{rate.Comment}";
                                    }
                                }
                            }

                            // agreement conditions
                            string comment3 = "";
                            if (reportModel.RentalAgreementConditions != null)
                            {
                                foreach (HetRentalAgreementCondition cond in reportModel.RentalAgreementConditions)
                                {
                                    var conditionComment = string.IsNullOrEmpty(cond.Comment) ? cond.ConditionName : cond.Comment;

                                    if (!string.IsNullOrEmpty(comment3))
                                    {
                                        comment3 += $"{crLf.ToString()}{conditionComment}";
                                    }
                                    else
                                    {
                                        comment3 += $"{conditionComment}";
                                    }
                                }
                            }

                            // rates not included in total
                            string overtimeRate    = "";
                            string overtimeComment = "";
                            if (reportModel.RentalAgreementRatesOvertime != null)
                            {
                                foreach (HetRentalAgreementRate rate in reportModel.RentalAgreementRatesOvertime.OrderByDescending(x => x.Comment))
                                {
                                    if (!string.IsNullOrEmpty(overtimeRate))
                                    {
                                        overtimeRate    += $"{crLf.ToString()}{rate.RateString}";
                                        overtimeComment += $"{crLf.ToString()}{rate.Comment}";
                                    }
                                    else
                                    {
                                        overtimeRate    += $"{rate.RateString}";
                                        overtimeComment += $"{rate.Comment}";
                                    }
                                }
                            }

                            Dictionary <string, string> values = new Dictionary <string, string>
                            {
                                { "classification", reportModel.Classification },
                                { "equipmentCode", reportModel.Equipment.EquipmentCode },
                                { "number", reportModel.Number },
                                { "organizationName", reportModel.Equipment.Owner.OrganizationName },
                                { "address1", reportModel.Equipment.Owner.Address1 },
                                { "address2", reportModel.Equipment.Owner.Address2 },
                                { "ownerCode", reportModel.Equipment.Owner.OwnerCode },
                                { "workPhoneNumber", reportModel.Equipment.Owner.PrimaryContact.WorkPhoneNumber },
                                { "mobilePhoneNumber", reportModel.Equipment.Owner.PrimaryContact.MobilePhoneNumber },
                                { "faxPhoneNumber", reportModel.Equipment.Owner.PrimaryContact.FaxPhoneNumber },
                                { "equipmentFullName", equipmentName },
                                { "noteLine", note },
                                { "baseRateString", reportModel.BaseRateString },
                                { "rateComment", reportModel.RateComment },
                                { "projectNumber", reportModel.Project.ProvincialProjectNumber },
                                { "projectName", reportModel.Project.Name },
                                { "district", reportModel.Project.District.Name },
                                { "estimateHours", reportModel.EstimateHours.ToString() },
                                { "estimateStartWork", reportModel.EstimateStartWork },
                                { "localAreaName", reportModel.Equipment.LocalArea.Name },
                                { "workSafeBcpolicyNumber", reportModel.Equipment.Owner.WorkSafeBcpolicyNumber },
                                { "agreementCity", reportModel.AgreementCity },
                                { "datedOn", reportModel.DatedOn },
                                { "rateString1", rateString1 },
                                { "comment1", comment1 },
                                { "agreementTotalString", reportModel.AgreementTotalString },
                                { "rateString2", rateString2 },
                                { "comment2", comment2 },
                                { "comment3", comment3 },
                                { "overtimeRate", overtimeRate },
                                { "overtimeComment", overtimeComment },
                                { "doingBusinessAs", reportModel.DoingBusinessAs },
                                { "emailAddress", reportModel.EmailAddress }
                            };

                            // update main document
                            MergeHelper.ConvertFieldCodes(agreementDocument.MainDocumentPart.Document);
                            MergeHelper.MergeFieldsInElement(values, agreementDocument.MainDocumentPart.Document);
                            agreementDocument.MainDocumentPart.Document.Save();

                            wordDocument = (WordprocessingDocument)agreementDocument.Clone(documentStream);

                            agreementDocument.Close();
                            agreementDocument.Dispose();
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#8
0
        public static byte[] GetOwnerVerification(OwnerVerificationReportModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      ownerCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (HetOwner owner in reportModel.Owners)
                        {
                            ownerCount++;

                            using (MemoryStream ownerStream = new MemoryStream())
                            {
                                WordprocessingDocument ownerDocument = (WordprocessingDocument)wordTemplate.Clone(ownerStream);
                                ownerDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", owner.Classification },
                                    { "districtAddress", reportModel.DistrictAddress },
                                    { "districtContact", reportModel.DistrictContact },
                                    { "organizationName", owner.OrganizationName },
                                    { "address1", owner.Address1 },
                                    { "address2", owner.Address2 },
                                    { "reportDate", reportModel.ReportDate },
                                    { "ownerCode", owner.OwnerCode },
                                    { "sharedKeyHeader", owner.SharedKeyHeader },
                                    { "sharedKey", owner.SharedKey },
                                    { "workPhoneNumber", owner.PrimaryContact.WorkPhoneNumber }
                                };

                                // update classification number first [ClassificationNumber]
                                owner.Classification = owner.Classification.Replace("&", "&amp;");
                                bool found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("ClassificationNumber"))
                                            {
                                                // replace text
                                                text.InnerXml = text.InnerXml.Replace("<w:t>ClassificationNumber</w:t>",
                                                                                      $"<w:t xml:space='preserve'>ORCS: {owner.Classification}</w:t>");

                                                found = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // update merge fields
                                MergeHelper.ConvertFieldCodes(ownerDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, ownerDocument.MainDocumentPart.Document);
                                ownerDocument.MainDocumentPart.Document.Save();

                                // setup table for equipment data
                                Table     equipmentTable = GenerateEquipmentTable(owner.HetEquipment);
                                Paragraph tableParagraph = null;
                                found = false;

                                foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("Owner Equipment Table"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(equipmentTable);
                                }

                                ownerDocument.MainDocumentPart.Document.Save();
                                ownerDocument.Save();

                                // merge owner into the master document
                                if (ownerCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in ownerDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)ownerDocument.Clone(documentStream);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = ownerDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = ownerDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = ownerDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    ownerDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph         para      = new Paragraph();
                                    SectionProperties sectProp  = new SectionProperties();
                                    SectionType       secSbType = new SectionType()
                                    {
                                        Val = SectionMarkValues.OddPage
                                    };
                                    PageSize pageSize = new PageSize()
                                    {
                                        Width = 11900U, Height = 16840U, Orient = PageOrientationValues.Portrait
                                    };
                                    PageMargin pageMargin = new PageMargin()
                                    {
                                        Top = 2642, Right = 23U, Bottom = 278, Left = 23U, Header = 714, Footer = 0, Gutter = 0
                                    };

                                    // page numbering throws out the "odd page" section breaks
                                    //PageNumberType pageNum = new PageNumberType() {Start = 1};

                                    sectProp.AppendChild(secSbType);
                                    sectProp.AppendChild(pageSize);
                                    sectProp.AppendChild(pageMargin);
                                    //sectProp.AppendChild(pageNum);

                                    ParagraphProperties paragraphProperties = new ParagraphProperties(sectProp);
                                    para.AppendChild(paragraphProperties);

                                    mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{ownerCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    ownerDocument.Close();
                                    ownerDocument.Dispose();

                                    ownerStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(ownerStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#9
0
 public void DoWorkCloningOpenXmlPackage()
 {
     using WordprocessingDocument sourceWordDocument = WordprocessingDocument.Open(SourcePath, false);
     using var wordDocument = (WordprocessingDocument)sourceWordDocument.Clone(DestPath, true);
     ChangeWordprocessingDocument(wordDocument);
 }
示例#10
0
        /// <summary>
        /// Saves the document to the supplied stream
        /// </summary>
        /// <param name="stream"></param>
        public void SaveAs(Stream stream)
        {
            Save();

            document.Clone(stream);
        }
示例#11
0
        public static byte[] GetSeniorityList(SeniorityListReportViewModel reportModel, string name)
        {
            try
            {
                // ******************************************************
                // get document template
                // ******************************************************
                Assembly assembly = Assembly.GetExecutingAssembly();
                byte[]   byteArray;
                int      recordCount = 0;

                using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName))
                {
                    byteArray = new byte[templateStream.Length];
                    templateStream.Read(byteArray, 0, byteArray.Length);
                    templateStream.Close();
                }

                using (MemoryStream documentStream = new MemoryStream())
                {
                    WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true);

                    // add a main document part
                    wordDocument.AddMainDocumentPart();

                    using (MemoryStream templateStream = new MemoryStream())
                    {
                        templateStream.Write(byteArray, 0, byteArray.Length);
                        WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true);

                        if (wordTemplate == null)
                        {
                            throw new Exception("Owner Verification template not found");
                        }

                        // ******************************************************
                        // merge document content
                        // ******************************************************
                        foreach (SeniorityListRecord seniorityList in reportModel.SeniorityListRecords)
                        {
                            recordCount++;

                            using (MemoryStream listStream = new MemoryStream())
                            {
                                WordprocessingDocument listDocument = (WordprocessingDocument)wordTemplate.Clone(listStream);
                                listDocument.Save();

                                Dictionary <string, string> values = new Dictionary <string, string>
                                {
                                    { "classification", reportModel.Classification },
                                    { "printedOn", reportModel.PrintedOn },
                                    { "districtName", seniorityList.DistrictName },
                                    { "localAreaName", seniorityList.LocalAreaName },
                                    { "districtEquipmentTypeName", seniorityList.DistrictEquipmentTypeName }
                                };

                                // update main document
                                MergeHelper.ConvertFieldCodes(listDocument.MainDocumentPart.Document);
                                MergeHelper.MergeFieldsInElement(values, listDocument.MainDocumentPart.Document);
                                listDocument.MainDocumentPart.Document.Save();

                                // setup table for seniority list
                                Table seniorityTable = GenerateSeniorityTable(seniorityList.SeniorityList, seniorityList);

                                // find our paragraph
                                Paragraph tableParagraph = null;
                                bool      found          = false;

                                foreach (OpenXmlElement paragraphs in listDocument.MainDocumentPart.Document.Body.Elements())
                                {
                                    foreach (OpenXmlElement paragraphRun in paragraphs.Elements())
                                    {
                                        foreach (OpenXmlElement text in paragraphRun.Elements())
                                        {
                                            if (text.InnerText.Contains("SeniorityListTable"))
                                            {
                                                // insert table here...
                                                text.RemoveAllChildren();
                                                tableParagraph = (Paragraph)paragraphRun.Parent;
                                                found          = true;
                                                break;
                                            }
                                        }

                                        if (found)
                                        {
                                            break;
                                        }
                                    }

                                    if (found)
                                    {
                                        break;
                                    }
                                }

                                // append table to document
                                if (tableParagraph != null)
                                {
                                    Run run = tableParagraph.AppendChild(new Run());
                                    run.AppendChild(seniorityTable);
                                }

                                listDocument.MainDocumentPart.Document.Save();
                                listDocument.Save();

                                // merge owner into the master document
                                if (recordCount == 1)
                                {
                                    // update document header
                                    foreach (HeaderPart headerPart in listDocument.MainDocumentPart.HeaderParts)
                                    {
                                        MergeHelper.ConvertFieldCodes(headerPart.Header);
                                        MergeHelper.MergeFieldsInElement(values, headerPart.Header);
                                        headerPart.Header.Save();
                                    }

                                    wordDocument = (WordprocessingDocument)listDocument.Clone(documentStream);

                                    listDocument.Close();
                                    listDocument.Dispose();
                                }
                                else
                                {
                                    // DELETE document header from owner document
                                    listDocument.MainDocumentPart.DeleteParts(listDocument.MainDocumentPart.HeaderParts);

                                    List <HeaderReference> headers = listDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList();

                                    foreach (HeaderReference header in headers)
                                    {
                                        header.Remove();
                                    }

                                    // DELETE document footers from owner document
                                    listDocument.MainDocumentPart.DeleteParts(listDocument.MainDocumentPart.FooterParts);

                                    List <FooterReference> footers = listDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList();

                                    foreach (FooterReference footer in footers)
                                    {
                                        footer.Remove();
                                    }

                                    // DELETE section properties from owner document
                                    List <SectionProperties> properties = listDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList();

                                    foreach (SectionProperties property in properties)
                                    {
                                        property.Remove();
                                    }

                                    listDocument.Save();

                                    // insert section break in master
                                    MainDocumentPart mainPart = wordDocument.MainDocumentPart;

                                    Paragraph pageBreak = new Paragraph(new Run(new Break {
                                        Type = BreakValues.Page
                                    }));

                                    mainPart.Document.Body.InsertAfter(pageBreak, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();

                                    // append document body
                                    string altChunkId = $"AltChunkId{recordCount}";

                                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

                                    listDocument.Close();
                                    listDocument.Dispose();

                                    listStream.Seek(0, SeekOrigin.Begin);
                                    chunk.FeedData(listStream);

                                    AltChunk altChunk = new AltChunk {
                                        Id = altChunkId
                                    };

                                    Paragraph para3 = new Paragraph();
                                    Run       run3  = para3.InsertAfter(new Run(), para3.LastChild);
                                    run3.AppendChild(altChunk);

                                    mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild);
                                    mainPart.Document.Save();
                                }
                            }
                        }

                        wordTemplate.Close();
                        wordTemplate.Dispose();
                        templateStream.Close();
                    }

                    // ******************************************************
                    // secure & return completed document
                    // ******************************************************
                    wordDocument.CompressionOption = CompressionOption.Maximum;
                    SecurityHelper.PasswordProtect(wordDocument);

                    wordDocument.Close();
                    wordDocument.Dispose();

                    documentStream.Seek(0, SeekOrigin.Begin);
                    byteArray = documentStream.ToArray();
                }

                return(byteArray);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }