Exemple #1
0
        static void Main(string[] args)
        {
            Document doc = new Document("../../data/document.doc");
            doc.AcceptAllRevisions();

            doc.Save("AsposeAcceptChanges.doc", SaveFormat.Doc);
        }
Exemple #2
0
        static void Main(string[] args)
        {
            Document doc = new Document("../../data/document.doc");

            doc.AcceptAllRevisions();

            doc.Save("AsposeAcceptChanges.doc", SaveFormat.Doc);
        }
 public void AcceptAllRevisions()
 {
     //ExStart
     //ExFor:Document.AcceptAllRevisions
     //ExId:AcceptAllRevisions
     //ExSummary:Shows how to accept all tracking changes in the document.
     Document doc = new Document(MyDir + "Document.doc");
     doc.AcceptAllRevisions();
     //ExEnd
 }
        public void IsRevision()
        {
            //ExStart
            //ExFor:Paragraph.IsDeleteRevision
            //ExFor:Paragraph.IsInsertRevision
            //ExSummary:Shows how to work with revision paragraphs.
            Document  doc  = new Document();
            Body      body = doc.FirstSection.Body;
            Paragraph para = body.FirstParagraph;

            para.AppendChild(new Run(doc, "Paragraph 1. "));
            body.AppendParagraph("Paragraph 2. ");
            body.AppendParagraph("Paragraph 3. ");

            // The above paragraphs are not revisions.
            // Paragraphs that we add after starting revision tracking will register as "Insert" revisions.
            doc.StartTrackRevisions("John Doe", DateTime.Now);

            para = body.AppendParagraph("Paragraph 4. ");

            Assert.True(para.IsInsertRevision);

            // Paragraphs that we remove after starting revision tracking will register as "Delete" revisions.
            ParagraphCollection paragraphs = body.Paragraphs;

            Assert.AreEqual(4, paragraphs.Count);

            para = paragraphs[2];
            para.Remove();

            // Such paragraphs will remain until we either accept or reject the delete revision.
            // Accepting the revision will remove the paragraph for good,
            // and rejecting the revision will leave it in the document as if we never deleted it.
            Assert.AreEqual(4, paragraphs.Count);
            Assert.True(para.IsDeleteRevision);

            // Accept the revision, and then verify that the paragraph is gone.
            doc.AcceptAllRevisions();

            Assert.AreEqual(3, paragraphs.Count);
            Assert.That(para, Is.Empty);
            Assert.AreEqual(
                "Paragraph 1. \r" +
                "Paragraph 2. \r" +
                "Paragraph 4.", doc.GetText().Trim());
            //ExEnd
        }
        static void Main(string[] args)
        {
            // Check for license and apply if exists
            string licenseFile = AppDomain.CurrentDomain.BaseDirectory + "Aspose.Words.lic";
            if (File.Exists(licenseFile))
            {
                // Apply Aspose.Words API License
                Aspose.Words.License license = new Aspose.Words.License();
                // Place license file in Bin/Debug/ Folder
                license.SetLicense("Aspose.Words.lic");
            }

            Document doc = new Document("../../data/document.doc");
            doc.AcceptAllRevisions();

            doc.Save("AsposeAcceptChanges.doc", SaveFormat.Doc);
        }
        private static void AcceptRevisions(string dataDir)
        {
            // ExStart:AcceptAllRevisions
            Document doc = new Document(dataDir + "Document.doc");

            // Start tracking and make some revisions.
            doc.StartTrackRevisions("Author");
            doc.FirstSection.Body.AppendParagraph("Hello world!");

            // Revisions will now show up as normal text in the output document.
            doc.AcceptAllRevisions();

            dataDir = dataDir + "Document.AcceptedRevisions_out.doc";
            doc.Save(dataDir);
            // ExEnd:AcceptAllRevisions
            Console.WriteLine("\nAll revisions accepted.\nFile saved at " + dataDir);
        }
Exemple #7
0
        public void AcceptRevisions()
        {
            //ExStart:AcceptAllRevisions
            Document  doc  = new Document();
            Body      body = doc.FirstSection.Body;
            Paragraph para = body.FirstParagraph;

            // Add text to the first paragraph, then add two more paragraphs.
            para.AppendChild(new Run(doc, "Paragraph 1. "));
            body.AppendParagraph("Paragraph 2. ");
            body.AppendParagraph("Paragraph 3. ");

            // We have three paragraphs, none of which registered as any type of revision
            // If we add/remove any content in the document while tracking revisions,
            // they will be displayed as such in the document and can be accepted/rejected.
            doc.StartTrackRevisions("John Doe", DateTime.Now);

            // This paragraph is a revision and will have the according "IsInsertRevision" flag set.
            para = body.AppendParagraph("Paragraph 4. ");
            Assert.True(para.IsInsertRevision);

            // Get the document's paragraph collection and remove a paragraph.
            ParagraphCollection paragraphs = body.Paragraphs;

            Assert.AreEqual(4, paragraphs.Count);
            para = paragraphs[2];
            para.Remove();

            // Since we are tracking revisions, the paragraph still exists in the document, will have the "IsDeleteRevision" set
            // and will be displayed as a revision in Microsoft Word, until we accept or reject all revisions.
            Assert.AreEqual(4, paragraphs.Count);
            Assert.True(para.IsDeleteRevision);

            // The delete revision paragraph is removed once we accept changes.
            doc.AcceptAllRevisions();
            Assert.AreEqual(3, paragraphs.Count);
            Assert.That(para, Is.Empty);

            // Stopping the tracking of revisions makes this text appear as normal text.
            // Revisions are not counted when the document is changed.
            doc.StopTrackRevisions();

            // Save the document.
            doc.Save(ArtifactsDir + "WorkingWithRevisions.AcceptRevisions.docx");
            //ExEnd:AcceptAllRevisions
        }
Exemple #8
0
        internal static void ExportWordFile(string filename)
        {
            try
            {
                var      path = $"original\\{filename}";
                Document doc  = new Document(path);

                if (doc.ProtectionType != ProtectionType.NoProtection)
                {
                    doc.Unprotect();
                }

                if (doc.HasRevisions)
                {
                    doc.AcceptAllRevisions();
                    doc.TrackRevisions = false;
                }
                doc.HyphenationOptions.AutoHyphenation = false;
                doc.ViewOptions.ViewType = Aspose.Words.Settings.ViewType.PageLayout;

                var             text    = String.Format("Διανομή μέσω 'ΙΡΙΔΑ' από {0} την {1}(LT) με UID: {2}", "Aspose Test App", DateTime.Now.ToString("dd/MM/yy HH:mm"), "0042");
                DocumentBuilder builder = new DocumentBuilder(doc);
                // Create the footer.
                builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
                builder.Writeln(text);

                var properties = doc.BuiltInDocumentProperties;
                properties["Title"].Value  = "Δοκιμή Εγγράφου";
                properties["Author"].Value = "Aspose Test Word";

                var extIndex = filename.LastIndexOf(".");
                filename = filename.Remove(extIndex);
                filename = filename.Insert(extIndex, ".pdf");

                var outputPath = $"revised\\{filename}";
                doc.Save(outputPath, SaveFormat.Pdf);

                Console.WriteLine("Converted word document");
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }
Exemple #9
0
        static void Main(string[] args)
        {
            // Check for license and apply if exists
            string licenseFile = AppDomain.CurrentDomain.BaseDirectory + "Aspose.Words.lic";

            if (File.Exists(licenseFile))
            {
                // Apply Aspose.Words API License
                Aspose.Words.License license = new Aspose.Words.License();
                // Place license file in Bin/Debug/ Folder
                license.SetLicense("Aspose.Words.lic");
            }

            Document doc = new Document("../../data/document.doc");

            doc.AcceptAllRevisions();

            doc.Save("AsposeAcceptChanges.doc", SaveFormat.Doc);
        }
        public static void Run()
        {
            //ExStart:AcceptAllRevisions
            // The path to the documents directory.
            string   dataDir = RunExamples.GetDataDir_WorkingWithDocument();
            Document doc     = new Document(dataDir + "Document.doc");

            // Start tracking and make some revisions.
            doc.StartTrackRevisions("Author");
            doc.FirstSection.Body.AppendParagraph("Hello world!");

            // Revisions will now show up as normal text in the output document.
            doc.AcceptAllRevisions();

            dataDir = dataDir + "Document.AcceptedRevisions_out_.doc";
            doc.Save(dataDir);
            //ExEnd:AcceptAllRevisions
            Console.WriteLine("\nAll revisions accepted.\nFile saved at " + dataDir);
        }
        public static void Run()
        {
            // ExStart:AcceptAllRevisions
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
            Document doc = new Document(dataDir + "Document.doc");

            // Start tracking and make some revisions.
            doc.StartTrackRevisions("Author");
            doc.FirstSection.Body.AppendParagraph("Hello world!");

            // Revisions will now show up as normal text in the output document.
            doc.AcceptAllRevisions();

            dataDir = dataDir + "Document.AcceptedRevisions_out.doc";
            doc.Save(dataDir);
            // ExEnd:AcceptAllRevisions
            Console.WriteLine("\nAll revisions accepted.\nFile saved at " + dataDir);
        }        
        public void IsRevision()
        {
            //ExStart
            //ExFor:Paragraph.IsDeleteRevision
            //ExFor:Paragraph.IsInsertRevision
            //ExSummary:Shows how to work with revision paragraphs.
            // Create a blank document, populate the first paragraph with text and add two more
            Document  doc  = new Document();
            Body      body = doc.FirstSection.Body;
            Paragraph para = body.FirstParagraph;

            para.AppendChild(new Run(doc, "Paragraph 1. "));
            body.AppendParagraph("Paragraph 2. ");
            body.AppendParagraph("Paragraph 3. ");

            // We have three paragraphs, none of which registered as any type of revision
            // If we add/remove any content in the document while tracking revisions,
            // they will be displayed as such in the document and can be accepted/rejected
            doc.StartTrackRevisions("John Doe", DateTime.Now);

            // This paragraph is a revision and will have the according "IsInsertRevision" flag set
            para = body.AppendParagraph("Paragraph 4. ");
            Assert.True(para.IsInsertRevision);

            // Get the document's paragraph collection and remove a paragraph
            ParagraphCollection paragraphs = body.Paragraphs;

            Assert.AreEqual(4, paragraphs.Count);
            para = paragraphs[2];
            para.Remove();

            // Since we are tracking revisions, the paragraph still exists in the document, will have the "IsDeleteRevision" set
            // and will be displayed as a revision in Microsoft Word, until we accept or reject all revisions
            Assert.AreEqual(4, paragraphs.Count);
            Assert.True(para.IsDeleteRevision);

            // The delete revision paragraph is removed once we accept changes
            doc.AcceptAllRevisions();
            Assert.AreEqual(3, paragraphs.Count);
            Assert.That(para, Is.Empty);
            //ExEnd
        }
Exemple #13
0
        internal static void CompareWordFiles(string originalFile, string revisedFile)
        {
            try
            {
                Document original = new Document($"original\\{originalFile}");
                Document revised  = new Document($"original\\{revisedFile}");

                if (original.ProtectionType != ProtectionType.NoProtection)
                {
                    original.Unprotect();
                }

                if (revised.ProtectionType != ProtectionType.NoProtection)
                {
                    revised.Unprotect();
                }

                if (original.HasRevisions)
                {
                    original.AcceptAllRevisions();
                }

                if (revised.HasRevisions)
                {
                    revised.AcceptAllRevisions();
                }

                CompareOptions options = new CompareOptions();
                options.IgnoreFormatting                    = true;
                options.IgnoreHeadersAndFooters             = true;
                original.TrackRevisions                     = true;
                original.HyphenationOptions.AutoHyphenation = false;
                // original now contains changes as revisions.
                var author = "aspose tester";
                original.Compare(revised, author, DateTime.Now, options);

                var final = new MemoryStream();
                if (revisedFile.EndsWith(".docx"))
                {
                    original.Save(final, SaveFormat.Docx);
                }
                else if (revisedFile.EndsWith(".doc"))
                {
                    original.Save(final, SaveFormat.Doc);
                }
                else if (revisedFile.EndsWith(".docm"))
                {
                    original.Save(final, SaveFormat.Docm);
                }
                else if (revisedFile.EndsWith(".odt"))
                {
                    original.Save(final, SaveFormat.Odt);;
                }

                using (FileStream file = new FileStream($"revised\\new_{revisedFile}", FileMode.Create, System.IO.FileAccess.Write))
                    final.WriteTo(file);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
        public void AcceptAllRevisions()
        {
            //ExStart
            //ExFor:Document.AcceptAllRevisions
            //ExSummary:Shows how to accept all tracking changes in the document.
            Document doc = new Document(MyDir + "Document.doc");

            // Start tracking and make some revisions.
            doc.StartTrackRevisions("Author");
            doc.FirstSection.Body.AppendParagraph("Hello world!");

            // Revisions will now show up as normal text in the output document.
            doc.AcceptAllRevisions();
            doc.Save(MyDir + @"\Artifacts\Document.AcceptedRevisions.doc");
            //ExEnd
        }
Exemple #15
0
        /*
         * private string getConnectionString()
         * {
         *  return ConfigurationManager.ConnectionStrings["WFEmailSender.Properties.Settings.WFdbConnectionString"].ConnectionString;
         * }
         */
        #endregion

        ////////////////////////////////////////////////////// convert files ///////////////////////////////////////////////////////////
        private bool convertFiles()
        {
            object missing  = System.Reflection.Missing.Value;
            object falseVal = false;

            try
            {
                var files = Directory.GetFiles(tbSourceDir.Text, sourceFilesFormat);
                foreach (string file in files)
                {
                    docFileNames.Add(Path.GetFileName(file));
                }
            }
            catch (Exception err)
            {
                lblStatus.Text = err.Message;
            }

            Application app = new Application();

            try
            {
                foreach (var file in docFileNames)
                {
                    var      sourceFilePath   = tbSourceDir.Text + "\\" + file;
                    var      sourcePathCasted = (Object)sourceFilePath;
                    Document doc = app.Documents.Open(ref sourcePathCasted, ref missing,
                                                      ref falseVal, ref missing, ref missing, ref missing, ref missing,
                                                      ref missing, ref missing, ref missing, ref missing, ref missing,
                                                      ref missing, ref missing, ref missing, ref missing);

                    doc.Activate();

                    var destinationName = file.Replace(sourceFilesFormat, ".pdf");
                    var destinationPath = tbDestDir.Text + "\\" + destinationName;

                    // get document properties
                    var properties = getProperties(doc);

                    var pdfDestinationName = properties.DocumentNo + " - " + properties.DocumentType + " - " + "InstantPot.pdf";
                    var pdfDestinationPath = tbDestDir.Text + "\\" + pdfDestinationName;

                    properties.DocFileDir = pdfDestinationPath;
                    allDocumentsProperties.Add(properties);

                    var destinationPathCasted = (Object)pdfDestinationPath;
                    doc.AcceptAllRevisions();
                    doc.SaveAs(destinationPathCasted, WdSaveFormat.wdFormatPDF,
                               ref missing, ref missing, ref missing, ref missing, ref missing,
                               ref missing, ref missing, ref missing, ref missing, ref missing,
                               ref missing, ref missing, ref missing, ref missing);

                    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
                    ((_Document)doc).Close(ref saveChanges, ref missing, ref missing);

                    var itemFound = false;
                    foreach (var item in lvFilesPdf.Items)
                    {
                        if (item.ToString() == "ListViewItem: {" + pdfDestinationName + "}")
                        {
                            itemFound = true;
                            break;
                        }
                    }

                    if (pdfDestinationName.Contains(".pdf") && !itemFound)
                    {
                        lvFilesPdf.Items.Add(pdfDestinationName + Environment.NewLine);
                        var count = int.Parse(lblPdfFilesCount.Text);
                        count++;
                        lblPdfFilesCount.Text = count.ToString();
                        //lblPdfFilesCount.Text = lvFilesPdf.Items.Count.ToString();
                    }
                }

                ((_Application)app).Quit(ref missing, ref missing, ref missing);
                return(true);
            }
            catch (Exception err)
            {
                // word application MUST be closed if error is thrown!!!
                ((_Application)app).Quit(ref missing, ref missing, ref missing);
                lblStatus.Text = err.Message;
                return(false);
            }
        }
        public static byte[] GenerateFinalCIPDoc(byte[] docTemplate, byte[] bodyTemplate, Tuple<Dictionary<string, string>, Dictionary<string, string[,]>> documentValues,
            byte[] schedule, int docType, string path, string format, bool draft, int scheduleType)
        {
            Document boaDocumentTemplate = GetBOADocumentTemplate();

            MemoryStream newStream = null;
            if (bodyTemplate != null)
            {
                newStream = new MemoryStream(bodyTemplate);
            }

            // Read the document from the stream.
            Document doc = new Document(newStream);

            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_PREMIUMS, doc, docType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_SCHEDULE, doc, scheduleType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_PARTICULARS, doc, docType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.FSRA_NOTICE1, doc, docType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_HEADER, doc, docType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_PAYMENT, doc, docType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_DUTYOFDISCLOSURE, doc, 0);

            // Save Document after adding BookMark and call
            MemoryStream middleStream = new MemoryStream();
            doc.Save(middleStream, SaveFormat.Doc);

            docTemplate = GenerateBodyDoc(middleStream.GetBuffer(), null,null,null,null, documentValues, false, SaveFormat.Doc);
            newStream = new MemoryStream(docTemplate);
            doc = new Document(newStream);

            if (bodyTemplate != null)
            {
                MemoryStream rtfStream = new MemoryStream(bodyTemplate);
                Document rtfDoc = new Document(rtfStream);
                InsertDocumentAtBookmark(Bookmarks.BPLUS_BODY, doc, rtfDoc);
            }
            else
            {
                if (doc.Range.Bookmarks[Bookmarks.BPLUS_BODY] != null)
                {
                    doc.Range.Bookmarks[Bookmarks.BPLUS_BODY].Text = "";
                }
            }

            if (schedule  != null)
            {
                MemoryStream rtfStream = new MemoryStream(schedule);
                Document rtfDoc = new Document(rtfStream);
                InsertDocumentAtBookmark(Bookmarks.POL_PARTICULARS, doc, rtfDoc);
            }

            if (draft)
            {
                InsertWatermarkText(doc,Bookmarks.DRAFT);
            }

            MemoryStream stream = new MemoryStream();
            doc.BuiltInDocumentProperties.LastSavedTime = DateTime.UtcNow;
            doc.UpdateFields();
            doc.AcceptAllRevisions();
            try
            {
                // Save the document to the memory stream.
                switch (format)
                {
                    case "pdf":
                        doc.Save(stream, SaveFormat.Pdf);
                        break;
                    default:
                        doc.Save(stream, SaveFormat.Doc);
                        break;
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return stream.GetBuffer();
        }
Exemple #17
0
        private string _Convert(string srcPath, string destFileExtension, Boolean srcIsZip, int pageIndex = -1, int imgQuality = 0, string htmlEncoding = "gb2312", int fontZoomPercent = 100, Boolean combineImages = false)
        {
            //判断许可
            //if (!CheckLicense())
            //{
            //    return new InternalBufferOverflowException().ToString();
            //}


            //清理旧文件
            if (this.AutoDelOldFile)
            {
                Utils.ClearupDir(this._tempPath, SaveDirMaxFileCount);
            }

            //文件名唯一标识
            var fileGUID = Utils.GetMd5Str(srcPath);

            try
            {
                this._combineImages = combineImages;

                string fileExtension = Path.GetExtension(srcPath).ToLower();
                string fileName      = fileGUID + fileExtension;

                string tempFilePath = this._tempPath + fileName;
                //判断目录是否存在(如果存在则说明转换过),如果是则不在下载,而doc每次都更新
                //var dirInfo = new DirectoryInfo(this._tempPath + fileGUID);
                //if (!dirInfo.Exists || dirInfo.GetFiles().Length == 0 || fileExtension == ".doc")
                {
                    //如果是HTTP链接,则通过HTTP下载
                    if (srcPath.Contains("http://"))
                    {
                        var downloadTempFile = tempFilePath + ".tmp";
                        Utils.DownloadToFile(srcPath, downloadTempFile, _cookie);
                        //如果是压缩文件,则解压
                        if (srcIsZip)
                        {
                            Utils.UnZipFile(downloadTempFile, tempFilePath);
                        }
                        else
                        {
                            File.Copy(downloadTempFile, tempFilePath);
                        }
                        FileInfo fi = new FileInfo(downloadTempFile);
                        fi.Delete();
                    }
                    //如果是局域网,则直接获取
                    else if (!string.IsNullOrEmpty(this._fileServer) && srcPath.StartsWith(@"\\"))
                    {
                        using (IdentityScope identity = new IdentityScope(this._serverUser, this._fileServer, this._serverPwd))
                        {
                            //如果是压缩文件,则解压
                            if (srcIsZip)
                            {
                                Utils.UnZipFile(srcPath, tempFilePath);
                            }
                            else
                            {
                                tempFilePath = srcPath;
                            }
                        }
                    }
                    else
                    {
                        //如果是压缩文件,则解压
                        if (srcIsZip)
                        {
                            Utils.UnZipFile(srcPath, tempFilePath);
                        }
                        else
                        {
                            tempFilePath = srcPath;
                        }
                    }



                    ////如果是压缩文件,则解压
                    //if (srcIsZip)
                    //{
                    //    try
                    //    {
                    //        //如果是局域网的,则先登录认证
                    //        if (!string.IsNullOrEmpty(this._fileServer) && srcPath.StartsWith(@"\\"))
                    //        {
                    //            using (IdentityScope identity = new IdentityScope(this._serverUser, this._fileServer, this._serverPwd))
                    //            {
                    //                Utils.UnZipFile(srcPath, tempFilePath);
                    //            }
                    //        }
                    //        else
                    //        {
                    //            Utils.UnZipFile(srcPath, tempFilePath);
                    //        }

                    //    }
                    //    catch (Exception)
                    //    {
                    //        return "文件解压失败,请确认源文件是压缩文件.";
                    //    }
                    //}
                }


                //如果路径为空,则直接返回
                if (string.IsNullOrEmpty(tempFilePath))
                {
                    return("");
                }

                string destFileName = fileGUID + destFileExtension;
                string destDir      = this._tempPath + fileGUID + "\\";
                string destFilePath = destDir + destFileName;
                string resultData   = string.Empty;

                if (fileExtension == ".doc" || fileExtension == ".docx")
                {
                    if (!Directory.Exists(destDir))
                    {
                        Directory.CreateDirectory(destDir);
                    }

                    //转换成HTML
                    if (destFileExtension.Equals(".html"))
                    {
                        Document doc = new Document(tempFilePath);

                        //不显示文本边框
                        doc.SaveOptions.HtmlExportTextInputFormFieldAsText = true;
                        doc.SaveOptions.HtmlExportAllowNegativeLeftIndent  = true;
                        doc.SaveOptions.HtmlExportDocumentProperties       = false;
                        doc.AcceptAllRevisions();


                        FormFieldCollection formFields = doc.Range.FormFields;
                        for (int i = formFields.Count - 1; i >= 0; i--)
                        {
                            var ff = formFields[i];
                            if (ff.Type == FieldType.FieldNone)
                            {
                                ff.Remove();
                            }
                        }

                        doc.Save(destFilePath);


                        StreamReader sr       = new StreamReader(destFilePath);
                        var          htmlData = Utils.ReplaceMatch("<meta name=\"generator\" content=\".*?\" />", RegexOptions.None, sr.ReadToEnd(), "");
                        htmlData = Utils.ReplaceMatch(@"<html>[\s\S]*?<body>", RegexOptions.None, htmlData, "");
                        htmlData = Utils.ReplaceMatch(@"</body>[\s\S]*?</html>", RegexOptions.None, htmlData, "");
                        byte a = 0xc2;
                        byte b = 0xa0;
                        htmlData = htmlData.Replace((char)a, ' ');
                        htmlData = htmlData.Replace((char)b, ' ');
                        htmlData = Utils.ReplaceMatch("<img src=\"(.*?)\"", RegexOptions.IgnoreCase, htmlData, "<img src=\"" + this._relativeTempPath + fileGUID + "/$1\"");
                        string pageData = "<span style=\"font-family:'宋体'; font-size:[1-9]+?pt\">-</span><span[^>].*?>[1-9]+?</span><span style=\"font-family:'宋体'; font-size:[1-9]+?pt\">-</span>";
                        htmlData = Utils.ReplaceMatch(pageData, RegexOptions.IgnoreCase, htmlData, "");
                        var utils = new Utils();
                        htmlData = utils.UpdateTableWidthMatch("<table cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse[^>]*?>", htmlData, "100%");
                        htmlData = htmlData.Replace("442.35pt", "100%");

                        sr.Close();

                        if (htmlEncoding.ToLower().Equals("gb2312"))
                        {
                            //StreamWriter sw = new StreamWriter(destFilePath, false, Encoding.GetEncoding("gb2312"));
                            //sw.Write(htmlData);
                            //sw.Flush();
                            //sw.Close();

                            resultData = Utils.UTF82GB2312(htmlData);
                        }
                        else
                        {
                            //StreamWriter sw = new StreamWriter(destFilePath);
                            //sw.Write(htmlData);
                            //sw.Flush();
                            //sw.Close();

                            resultData = htmlData;
                        }

                        //删除临时文件
                        Utils.SigleFileDel(destFilePath);
                        //如果文件夹为空,则删除文件夹
                        var dir = new DirectoryInfo(destDir);
                        if (dir.Exists && dir.GetFiles().Length == 0)
                        {
                            Utils.RemoteDelDir(destDir);
                        }
                    }
                    //转换成图片的
                    else if (destFileExtension.Equals(".jpg"))
                    {
                        resultData = new DocEngine().Convert(tempFilePath, this._tempPath, fileGUID, combineImages, pageIndex, imgQuality);
                    }
                }
                else if (fileExtension == ".pdf")
                {
                    resultData = new PDFEngine().Convert(tempFilePath, this._tempPath, fileGUID, combineImages, pageIndex, imgQuality);
                }
                else if (fileExtension == ".ceb")
                {
                    if (string.IsNullOrEmpty(CebImageSavePath))
                    {
                        resultData = new CebEngine().Convert(tempFilePath, this._tempPath, fileGUID, this._tempPath, combineImages, imgQuality);
                    }
                    else
                    {
                        resultData = new CebEngine().Convert(tempFilePath, this._tempPath, fileGUID, CebImageSavePath, combineImages, imgQuality);
                    };
                }

                //删除临时文件
                Utils.SigleFileDel(tempFilePath);

                return(resultData);
            }

            catch (Exception)
            {
                return("未能找到文件。");
            }
        }
        /// <summary>
        /// Generate the document 
        /// </summary>
        /// <param name="configData">object of ConfigurationData</param>
        /// <returns>stream object converted to byte array</returns>
        public static byte[] GenerateDoc(ConfigurationData configData)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;

            //Read BOA document template
            Document boaDocumentTemplate = GetBOADocumentTemplate();

            //Declared a pol_particular_bookmark string to identify Is it a task or Invoice doc
            string polParticularBookmark="";
            string fsraNotice1Bookmark = "";
            string fsraNotice2Bookmark = "";
            string fsraNotice3Bookmark = "";
            string fsraAdviceBookmark = "";
            string fsraRecommendationBookmark = "";
            string branchLogoBookmark = "";

            MemoryStream newStream = null;
            if (configData.DocumentTemplate != null)
            {
                newStream = new MemoryStream(configData.DocumentTemplate);
            }

            // Read the document from the stream.
            Document doc = new Document(newStream);
            if (!string.IsNullOrWhiteSpace(configData.Notice1))
            {
                // Use the indexer of the Bookmarks collection to obtain the desired bookmark.
                Bookmark bookmarkNotice1 = doc.Range.Bookmarks[Bookmarks.FSRA_NOTICE1];
                if (bookmarkNotice1 != null)
                {
                    if (bookmarkNotice1.Name != null)
                    {
                        bookmarkNotice1.Name = Bookmarks.FSRA_NOTICE1;
                        bookmarkNotice1.Text = "";
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(configData.Notice2))
            {
                // Use the indexer of the Bookmarks collection to obtain the desired bookmark.
                Bookmark bookmarkNotice2 = doc.Range.Bookmarks[Bookmarks.FSRA_NOTICE2];
                if (bookmarkNotice2 != null)
                {
                    if (bookmarkNotice2.Name != null)
                    {
                        bookmarkNotice2.Name = Bookmarks.FSRA_NOTICE2;
                        bookmarkNotice2.Text = "";
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(configData.Notice3))
            {
                // Use the indexer of the Bookmarks collection to obtain the desired bookmark.
                Bookmark bookmarkNotice3 = doc.Range.Bookmarks[Bookmarks.FSRA_NOTICE3];
                if (bookmarkNotice3 != null)
                {
                    if (bookmarkNotice3.Name != null)
                    {
                        bookmarkNotice3.Name = Bookmarks.FSRA_NOTICE3;
                        bookmarkNotice3.Text = "";
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(configData.Recommendations))
            {
                // Use the indexer of the Bookmarks collection to obtain the desired bookmark.
                Bookmark bookmarkRecommendation = doc.Range.Bookmarks[Bookmarks.FSRA_RECOMMENDATIONS];
                if (bookmarkRecommendation != null)
                {
                    if (bookmarkRecommendation.Name != null)
                    {
                        bookmarkRecommendation.Name = Bookmarks.FSRA_RECOMMENDATIONS;
                        bookmarkRecommendation.Text = "";
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(configData.ScopeOfAdvice))
            {
                // Use the indexer of the Bookmarks collection to obtain the desired bookmark.
                Bookmark bookmarkNatureOfAdvice = doc.Range.Bookmarks[Bookmarks.FSRA_NATURE_OF_ADVICE];
                if (bookmarkNatureOfAdvice != null)
                {
                    if (bookmarkNatureOfAdvice.Name != null)
                    {
                        bookmarkNatureOfAdvice.Name = Bookmarks.FSRA_NATURE_OF_ADVICE;
                        bookmarkNatureOfAdvice.Text = "";
                    }
                }
            }
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_PREMIUMS, doc, configData.DocType);

            //  The following statement produces BPLUS_SCHEDULE_3 and BPLUS_SCHEDULE_4
            // if the transaction type is CANCELLATION or ENDORSEMENT
            if (configData != null)
            {
                bool isCancellationOrEndorsement = configData.TransactionType.Equals("cancellation", StringComparison.OrdinalIgnoreCase)
                || configData.TransactionType.Equals("endorsement", StringComparison.OrdinalIgnoreCase);

                if (isCancellationOrEndorsement)
                {
                    if (configData.DocType == 1)
                    {
                        InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_SCHEDULE, doc, 3);
                    }
                    else if (configData.DocType == 2)
                    {
                        InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_SCHEDULE, doc, 4);
                    }
                }
                else
                {
                    InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_SCHEDULE, doc, configData.DocType);
                }
            }
            else
            {
                InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_SCHEDULE, doc, configData.DocType);
            }

            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_PARTICULARS, doc, configData.DocType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_HEADER, doc, configData.DocType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_PAYMENT, doc, configData.DocType);
            InsertBlockAtBookamrk(boaDocumentTemplate, Bookmarks.BPLUS_DUTYOFDISCLOSURE, doc, configData.DocType);

            if (!configData.IsCIP)
            {
                if (configData.BodyTemplate != null)
                {
                    MemoryStream newStream2 = null;
                    if (configData.BodyTemplate != null)
                    {
                        using (newStream2 = new MemoryStream(configData.BodyTemplate))
                        {
                            Document bodyDoc = new Document(newStream2);
                            InsertDocumentAtBookmark(Bookmarks.BPLUS_BODY, doc, bodyDoc);
                        }
                    }
                }
                else
                {
                    if (doc.Range.Bookmarks[Bookmarks.BPLUS_BODY] != null)
                    {
                        doc.Range.Bookmarks[Bookmarks.BPLUS_BODY].Text = "";
                    }
                }
            }

            for (int index = 0; index < doc.Range.Bookmarks.Count; index++)
            {
                Bookmark bookmark = doc.Range.Bookmarks[index];
                if (bookmark.Name == Bookmarks.POL_PARTICULARS)
                {
                    polParticularBookmark=bookmark.Name;
                }
                if (bookmark.Name == Bookmarks.FSRA_NOTICE1 || bookmark.Name == Bookmarks.AB_FSRA_NOTICE1)
                {
                    fsraNotice1Bookmark = bookmark.Name;
                }
                if (bookmark.Name == Bookmarks.FSRA_NOTICE2 || bookmark.Name == Bookmarks.AB_FSRA_NOTICE2)
                {
                    fsraNotice2Bookmark = bookmark.Name;
                }
                if (bookmark.Name == Bookmarks.FSRA_NOTICE3 || bookmark.Name == Bookmarks.AB_FSRA_NOTICE3)
                {
                    fsraNotice3Bookmark = bookmark.Name;
                }
                if (bookmark.Name == Bookmarks.FSRA_NATURE_OF_ADVICE || bookmark.Name == Bookmarks.AB_FSRA_NATURE_OF_ADVICE)
                {
                    fsraAdviceBookmark = bookmark.Name;
                }
                if (bookmark.Name == Bookmarks.FSRA_RECOMMENDATIONS || bookmark.Name == Bookmarks.AB_FSRA_RECOMMENDATIONS)
                {
                    fsraRecommendationBookmark = bookmark.Name;
                }
                if (bookmark.Name == Bookmarks.LOGO)
                {
                    branchLogoBookmark = bookmark.Name;
                }

                string bookmarkName = bookmark.Name;

                string key = null;

                if (TryGetKeyWithCorrectCase(configData.DocumentValues.Keys, bookmarkName, out key) && bookmarkName != Bookmarks.POL_PARTICULARS && bookmarkName != Bookmarks.FSRA_NATURE_OF_ADVICE && bookmarkName != Bookmarks.FSRA_RECOMMENDATIONS && bookmarkName != Bookmarks.FSRA_NOTICE1 && bookmarkName != Bookmarks.FSRA_NOTICE2 && bookmarkName != Bookmarks.FSRA_NOTICE3)
                {
                    string suffix = "";
                    string tempValue;
                    if (configData.DocumentValues[key] != "" && (bookmark.Text.EndsWith("\r") || bookmark.Text.EndsWith("\r\n")))
                    {
                        suffix = Environment.NewLine;
                    }

                    try
                    {
                        tempValue = configData.DocumentValues[key] ?? "" + suffix;

                        //Checking if the bookmark is a having values in 'docValues[key]' if true than remove any RTF text and insert the clean text in the Document
                        if (!String.IsNullOrWhiteSpace(tempValue))
                        {
                            if (tempValue.StartsWith("{\rtf"))
                            {
                                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                                Byte[] stringBytes = encoding.GetBytes(tempValue);
                                LoadOptions loadOptions = new LoadOptions();
                                loadOptions.LoadFormat = Aspose.Words.LoadFormat.Rtf;
                                using (MemoryStream rtfStream = new MemoryStream(stringBytes))
                                {
                                    Document rtfDoc = new Document(rtfStream, loadOptions);
                                    InsertDocumentAtBookmark(tempValue, doc, rtfDoc);
                                }
                            }
                            else
                            {
                                DateTime dateResult;
                                decimal decResult;

                                // without this check first, DateTime.TryParse values like 16.5 results in true and interpreted as 16 May
                                //So first do decimal.tryparse then datetime.tryparse
                                if (decimal.TryParse(tempValue, out decResult))
                                {
                                    bookmark.Text = tempValue;
                                }
                                else
                                {
                                    if (DateTime.TryParse(tempValue, out dateResult))
                                    {
                                        bookmark.Text = dateResult.ToString("dd/MM/yyyy");
                                    }
                                    else
                                    {
                                        bookmark.Text = tempValue;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        string temp = e.Message;
                        bookmark.Remove();
                    }
                }
            }

            // Get collection of all FieldStart nodes in the document.
            NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);

            // We will use regular expression to get name of DOCVARIABLE.
            Regex regex = new Regex("DOCVARIABLE\\s+(?<name>[^\\s\"]+)|(\"(?<name>[^\"]+)\").*");

            // Look through all the field starts for the DOCVARIABLE field start.
            foreach (FieldStart start in fieldStarts)
            {
                try
                {
                    // Check whether the FieldStart is start of DOCVARIABLE field.
                    if (start.FieldType.Equals(FieldType.FieldDocVariable))
                    {
                        // We should get field code.
                        // Field code is the text between FieldStart and FieldSeparator nodes.
                        string fieldCode = "";
                        Node currentNode = start;
                        try
                        {
                            while (!(currentNode == null || currentNode.NodeType.Equals(NodeType.FieldSeparator)))
                            {
                                if (currentNode.NodeType.Equals(NodeType.Run))
                                {
                                    fieldCode += ((Run)currentNode).Text;
                                }

                                currentNode = currentNode.NextSibling;
                            }
                        }
                        catch (Exception ex3)
                        {
                            throw ex3;
                        }
                        // Get name of the DOCVARIABLE.
                        Match match = regex.Match(fieldCode);

                        // Print name of the DOCVARIABLE.
                        string docVarName = match.Groups["name"].Value;

                        if (docVarName.StartsWith("CI___", true, CultureInfo.CurrentCulture) && !configData.DocumentValues.ContainsKey(docVarName))
                        {
                            docVarName = docVarName.Substring(5);
                            if (configData.DocumentValues.ContainsKey("I___" + docVarName))
                            {
                                docVarName = "I___" + docVarName;
                            }
                        }

                        if (docVarName.StartsWith("UW___", true, CultureInfo.CurrentCulture))
                        {
                            docVarName = docVarName.Substring(5);
                        }
                        try
                        {
                            string keyWithCorrectCase = null;
                            string strValue = "";
                            DateTime dtResult;
                            if (TryGetKeyWithCorrectCase(configData.DocumentValues.Keys, docVarName, out keyWithCorrectCase))
                            {
                                if (DateTime.TryParse(configData.DocumentValues[keyWithCorrectCase], out dtResult) && (!configData.DocumentValues[keyWithCorrectCase].Contains(".")))
                                {
                                    strValue = dtResult.ToString("dd/MM/yyyy");
                                }
                                else
                                {
                                    strValue = configData.DocumentValues[keyWithCorrectCase];
                                }

                                if (docVarName == "pol_policy_number")
                                {
                                    doc.Variables[match.Groups["name"].Value] = strValue + "\t";
                                }
                                else
                                {
                                    doc.Variables[match.Groups["name"].Value] = strValue;
                                }
                            }
                            else
                            {
                                if (TryGetKeyWithCorrectCase(configData.DocumentValues.Keys, "I___" + docVarName, out keyWithCorrectCase))
                                {
                                    if (DateTime.TryParse(configData.DocumentValues[keyWithCorrectCase], out dtResult))
                                    {
                                        strValue = dtResult.ToString("dd/MM/yyyy");
                                    }
                                    else
                                    {
                                        strValue = configData.DocumentValues[keyWithCorrectCase];
                                    }

                                    doc.Variables[match.Groups["name"].Value] = strValue;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            /*
            if (hasMacros)
                ExecuteMacros(doc, path);
             */
            //Bookmarks for SOA (Scope of Advice)Workbook which also removes any rtf text from the bookmark
            #region SOA BookMarks
            if (fsraNotice1Bookmark == Bookmarks.FSRA_NOTICE1 || fsraNotice1Bookmark == Bookmarks.AB_FSRA_NOTICE1)
            {
                if (!string.IsNullOrWhiteSpace(configData.Notice1))
                {
                    try
                    {
                        LoadOptions loadOptions = new LoadOptions();
                        loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

                        using (MemoryStream rtfStream = new MemoryStream(Encoding.UTF8.GetBytes(configData.Notice1)))
                        {
                            Document rtfDoc = new Document(rtfStream, loadOptions);
                            InsertDocumentAtBookmark(fsraNotice1Bookmark, doc, rtfDoc);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }

            if (fsraNotice2Bookmark == Bookmarks.FSRA_NOTICE2 || fsraNotice2Bookmark == Bookmarks.AB_FSRA_NOTICE2)
            {
                if (!string.IsNullOrWhiteSpace(configData.Notice2))
                {
                    try
                    {
                        LoadOptions loadOptions = new LoadOptions();
                        loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

                        using (MemoryStream rtfStream = new MemoryStream(Encoding.UTF8.GetBytes(configData.Notice2)))
                        {
                            Document rtfDoc = new Document(rtfStream, loadOptions);
                            InsertDocumentAtBookmark(fsraNotice2Bookmark, doc, rtfDoc);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }

            if (fsraNotice3Bookmark == Bookmarks.FSRA_NOTICE3 || fsraNotice3Bookmark == Bookmarks.AB_FSRA_NOTICE3)
            {
                if (!string.IsNullOrWhiteSpace(configData.Notice3))
                {
                    try
                    {
                        LoadOptions loadOptions = new LoadOptions();
                        loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

                        using (MemoryStream rtfStream = new MemoryStream(Encoding.UTF8.GetBytes(configData.Notice3)))
                        {
                            Document rtfDoc = new Document(rtfStream, loadOptions);
                            InsertDocumentAtBookmark(fsraNotice3Bookmark, doc, rtfDoc);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }

            if (fsraRecommendationBookmark == Bookmarks.FSRA_RECOMMENDATIONS || fsraRecommendationBookmark == Bookmarks.AB_FSRA_RECOMMENDATIONS)
            {
                if (!string.IsNullOrWhiteSpace(configData.Recommendations))
                {
                    try
                    {
                        LoadOptions loadOptions = new LoadOptions();
                        loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

                        using (MemoryStream rtfStream = new MemoryStream(Encoding.UTF8.GetBytes(configData.Recommendations)))
                        {
                            Document rtfDoc = new Document(rtfStream, loadOptions);
                            InsertDocumentAtBookmark(fsraRecommendationBookmark, doc, rtfDoc);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
            if (fsraAdviceBookmark == Bookmarks.FSRA_NATURE_OF_ADVICE || fsraAdviceBookmark == Bookmarks.AB_FSRA_NATURE_OF_ADVICE)
            {
                if (!string.IsNullOrWhiteSpace(configData.ScopeOfAdvice))
                {
                    try
                    {
                        LoadOptions loadOptions = new LoadOptions();
                        loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

                        using (MemoryStream rtfStream = new MemoryStream(Encoding.UTF8.GetBytes(configData.ScopeOfAdvice)))
                        {
                            Document rtfDoc = new Document(rtfStream, loadOptions);
                            InsertDocumentAtBookmark(fsraAdviceBookmark, doc, rtfDoc);
                        }
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
            #endregion

            if (configData.Schedule != null && configData.Schedule.Length != 0)
            {
                try
                {
                    LoadOptions loadOptions = new LoadOptions();
                    loadOptions.LoadFormat = Aspose.Words.LoadFormat.Rtf;

                    using (MemoryStream rtfStream = new MemoryStream(configData.Schedule))
                    {
                        Document rtfDoc = new Document(rtfStream, loadOptions);
                        //Checking for creating a Task Doc or an Invoice
                        if (polParticularBookmark == Bookmarks.POL_PARTICULARS)
                            InsertDocumentAtBookmark(Bookmarks.POL_PARTICULARS, doc, rtfDoc);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }

            bool useSalesTeamLogo = false;
            switch (configData.DocType)
            {
                case 1:
                    if (configData.DocumentValues.ContainsKey(Bookmarks.SALTEA_USE_BILLING) && configData.DocumentValues[Bookmarks.SALTEA_USE_BILLING] == "True")
                        useSalesTeamLogo = true;
                    break;

                case 2:
                    if (configData.DocumentValues.ContainsKey(Bookmarks.SALTEA_USE_CLOSING) && configData.DocumentValues[Bookmarks.SALTEA_USE_CLOSING] == "True")
                        useSalesTeamLogo = true;
                    break;

                default:
                    if (configData.DocumentValues.ContainsKey(Bookmarks.SALTEA_USE_OTHER) && configData.DocumentValues[Bookmarks.SALTEA_USE_OTHER] == "True")
                        useSalesTeamLogo = true;
                    break;
            }

            // Insert Logo
            if (branchLogoBookmark == Bookmarks.LOGO)
            {
                string value = "";

                if (useSalesTeamLogo && configData.DocumentValues.ContainsKey(Bookmarks.SALTEA_LOGO))
                {
                    value = configData.DocumentValues[Bookmarks.SALTEA_LOGO];
                }

                if (string.IsNullOrEmpty(value))
                {
                    if (configData.DocumentValues.ContainsKey(Bookmarks.SAP_LOGO))
                    {
                        value = configData.DocumentValues[Bookmarks.SAP_LOGO];
                    }
                }

                if (string.IsNullOrEmpty(value))
                {
                    if (configData.DocumentValues.ContainsKey(Bookmarks.BRA_LOGO) && (doc.Variables[Bookmarks.BRA_DESC] == Bookmarks.ELECTRONIC || configData.DocType == 3 || configData.IsGenerateTaskDocument))
                    {
                        value = configData.DocumentValues[Bookmarks.BRA_LOGO];
                    }
                }
                    if (!string.IsNullOrEmpty(value))
                    {
                        string logoPath = path + "\\logos\\" + value;
                        if(File.Exists(logoPath))
                            InsertImage(doc, Bookmarks.LOGO, logoPath);
                    }
            }

            if (configData.ShowWaterMark)
            {
                InsertWatermarkText(doc, Bookmarks.DRAFT);
            }

            try
            {
                doc.UpdateFields();
                doc.Range.UpdateFields();
            }
            catch (Exception)
            {
                // Error sometimes occurrs in Aspose when calling UpdateFields.
            }

            NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);

            foreach (Paragraph para in paragraphs)
            {
                if (para.IsListItem)
                {
                    foreach (Node node in para.ChildNodes)
                    {
                        Run run = node as Run;

                        if (run != null)
                        {
                            bool runBeginsWithATab = run.Range.Text.Count() > 0 && run.Range.Text[0] == '\t';

                            if (runBeginsWithATab)
                            {
                                run.Text = run.Range.Text.Remove(0, 1);
                            }
                        }
                    }
                }
            }

            MemoryStream stream = new MemoryStream();
            doc.BuiltInDocumentProperties.LastSavedTime = DateTime.UtcNow;
            try
            {
                doc.UpdateFields();
            }
            catch (Exception)
            {
                // Error sometimes occurrs in Aspose when calling UpdateFields.
            }
            doc.AcceptAllRevisions();

            if (configData.IsCIP)
            {
                if (configData.BodyTemplate != null)
                {
                    MemoryStream newStream2 = null;
                    if (configData.BodyTemplate != null)
                    {
                        using (newStream2 = new MemoryStream(configData.BodyTemplate))
                        {
                            Document bodyDoc = new Document(newStream2);
                            InsertDocumentAtBookmark(Bookmarks.BPLUS_BODY, doc, bodyDoc);
                        }
                    }
                }
                else
                {
                    if (doc.Range.Bookmarks[Bookmarks.BPLUS_BODY] != null)
                    {
                        doc.Range.Bookmarks[Bookmarks.BPLUS_BODY].Text = "";
                    }
                }

            }

            try
            {
                if (configData.LockDocument)
                {
                    doc.Protect(ProtectionType.ReadOnly);
                }

                if (configData.IsGenerateTaskDocument && doc.ProtectionType == ProtectionType.AllowOnlyFormFields)
                {
                    doc.Unprotect();
                    doc.Protect(ProtectionType.AllowOnlyFormFields, "BOA1234");
                }

                // Save the document to the memory stream.
                switch (configData.Format)
                {
                    case "pdf":
                        doc.Save(stream, SaveFormat.Pdf);
                        break;
                    default:
                        doc.Save(stream, SaveFormat.Doc);
                        break;
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return stream.ToArray();
        }