/// <summary>
        /// Reads the building blocks for a category and creates a <see cref="LayoutInformation"/> object from them.
        /// </summary>
        /// <param name="document">The document to be used to temporarily insert the building blocks so they can be scanned for content control tags.</param>
        /// <param name="category">The category to read from.</param>
        /// <returns>The layout.</returns>
        private LayoutInformation GetLayoutForCategory(IWordDocument document, string category)
        {
            IEnumerable <BuildingBlock>     blocks     = this.wordTemplate.EnumerateBuildingBlocksForCategory(category);
            IEnumerable <BuildingBlockInfo> blocksInfo = blocks.Select(block => document.ReadBuildingBlockInfo(block));

            return(this.CreateLayout(category, blocks, blocksInfo));
        }
Beispiel #2
0
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            var shapeDescNotBelow = document
                                    .Shapes
                                    .Where(f => f.Description.Position != Position.Below)
                                    .ToList();

            if (shapeDescNotBelow.Any())
            {
                var str = string.Join(
                    ", ",
                    shapeDescNotBelow.Select(
                        f =>
                {
                    var plainDesc = f.Description.PlainDescription;

                    if (string.IsNullOrEmpty(plainDesc))
                    {
                        plainDesc = NoDescription;
                    }

                    return(plainDesc);
                }));

                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, str)));
            }

            return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
        }
Beispiel #3
0
        protected void EmployeesGrid_ServerWordExporting(object sender, Syncfusion.JavaScript.Web.GridEventArgs e)
        {
            WordExport    exp      = new WordExport();
            IWordDocument document = exp.Export(EmployeesGrid.Model, (IEnumerable)EmployeesGrid.DataSource, "Export.docx", true, true, "flat-lime", true);

            exp.Export(OrdersGrid.Model, (IEnumerable)OrdersGrid.DataSource, "Export.docx", true, true, "flat-lime", false, document, "Second Grid");
        }
Beispiel #4
0
        public IReadOnlyCollection <IMatch> MatchWords(IWordDocument document, string elementPrefix)
        {
            var linkRegex = new nat.Regex($@"(\[({elementPrefix})(?<{NumberGroupName}>[0-9]+)\])");

            var matches = document
                          .Words
                          .Select(f => linkRegex.Match(f.Characters.Text))
                          .Where(f => f.Success)
                          .ToList();

            var result = new List <IMatch>();

            foreach (var match in matches)
            {
                var grps = match
                           .Groups
                           .Cast <nat.Group>()
                           .Select(f => new MatchGroup(f.Name, f.Value))
                           .ToList();

                result.Add(new Match(match.Value, grps));
            }

            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// Get the captions of all the open word documents
        /// </summary>
        /// <returns></returns>
        public static List <string> GetWordDocuments()
        {
            List <string> documents = new List <string>();

            try {
                using (IWordApplication wordApplication = COMWrapper.GetInstance <IWordApplication>()) {
                    if (wordApplication != null)
                    {
                        if (version == null)
                        {
                            version = wordApplication.Version;
                        }
                        for (int i = 1; i <= wordApplication.Documents.Count; i++)
                        {
                            IWordDocument document = wordApplication.Documents.item(i);
                            if (document.ReadOnly)
                            {
                                continue;
                            }
                            if (isAfter2003())
                            {
                                if (document.Final)
                                {
                                    continue;
                                }
                            }
                            documents.Add(document.ActiveWindow.Caption);
                        }
                    }
                }
            } catch (Exception ex) {
                LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
            }
            return(documents);
        }
        /// <summary>
        /// Makes a handle for a document.
        /// </summary>
        /// <param name="document">The document to make the handle for.</param>
        /// <returns>The <see cref="DocumentHandle"/> for the <paramref name="document"/>.</returns>
        private DocumentHandle MakeDocumentHandle(IWordDocument document)
        {
            DocumentHandle handle = document.Handle.HasValue ? new DocumentHandle(document.Handle.Value) : new DocumentHandle(document.Name);

            this.logger.Log(TraceEventType.Verbose, "Handle for document {0} is {1}", document.Name, handle);
            return(handle);
        }
Beispiel #7
0
        public async Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            using var webClient = new HeadWebClient();

            var invalidUris = new List <Uri>();

            foreach (var link in document.ExternalHyperLinks)
            {
                try
                {
                    await webClient.DownloadDataTaskAsync(link.Uri);
                }
                catch (WebException)
                {
                    invalidUris.Add(link.Uri);
                }
            }

            if (!invalidUris.Any())
            {
                return(RuleCheckResult.CreatePassed(RuleName));
            }

            var missingUrls = string.Join(", ", invalidUris.Select(f => f.AbsoluteUri));

            return(RuleCheckResult.CreateFailure(RuleName, missingUrls));
        }
Beispiel #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentResult"/> class.
 /// </summary>
 /// <param name="document">The Word Document</param>
 /// <param name="filename">The Filename</param>
 /// <param name="formattype">The FormatType</param>
 /// <param name="response">The Resposne</param>
 /// <param name="contentDisposition">The Type of ContentDisposition</param>
 public DocumentResult(IWordDocument document, string filename, FormatType formattype, HttpResponse response, HttpContentDisposition contentDisposition)
 {
     FileName                = filename;
     m_document              = document;
     this.formatType         = formattype;
     m_response              = response;
     this.ContentDisposition = contentDisposition;
 }
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            if (!CheckMatching(document, document.Tables.Count) || !CheckMatching(document, document.ListOfTables.Entries.Count))
            {
                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, "List of tables not matching")));
            }

            return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
        }
        public static string GetText(this IWordDocument source)
        {
            if (source == null)
            {
                return(null);
            }

            return(source.GetTextAsync(CancellationToken.None).WaitForResult());
        }
        public static Stream HighlightText(this IWordDocument source, params string[] terms)
        {
            if (source == null)
            {
                return(null);
            }

            return(source.HighlightTextAsync(CancellationToken.None, terms).WaitForResult());
        }
        public void Convert(IWordDocument doc)
        {
            using (var stream = new MemoryStream(4096))
            using (var document = doc.GetWordprocessingDocument())
            using (var package = Package.Open(stream, FileMode.CreateNew, FileAccess.ReadWrite))
            {
                //document.GetPartsOfType<>()

            }
        }
Beispiel #13
0
		/// <summary>
		/// Internal method for the insert
		/// </summary>
		/// <param name="wordApplication"></param>
		/// <param name="wordDocument"></param>
		/// <param name="tmpFile"></param>
		/// <param name="adress">link for the image</param>
		/// <param name="tooltip">tooltip of the image</param>
		/// <returns></returns>
		internal static bool InsertIntoExistingDocument(IWordApplication wordApplication, IWordDocument wordDocument, string tmpFile, string address, string tooltip) {
			// Bug #1517: image will be inserted into that document, where the focus was last. It will not inserted into the chosen one.
			// Solution: Make sure the selected document is active, otherwise the insert will be made in a different document!
			try {
				wordDocument.Activate();
			} catch {
			}
			using (ISelection selection = wordApplication.Selection) {
				if (selection == null) {
					LOG.InfoFormat("No selection to insert {0} into found.", tmpFile);
					return false;
				}
				// Add Picture
				using (IInlineShape shape = AddPictureToSelection(selection, tmpFile)) {
					if (!string.IsNullOrEmpty(address)) {
						object screentip = Type.Missing;
						if (!string.IsNullOrEmpty(tooltip)) {
							screentip = tooltip;
						}
						try {
							using (IHyperlinks hyperlinks = wordDocument.Hyperlinks) {
								hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
							}
						} catch (Exception e) {
							LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
						}
					}
				}
				try {
					using (IWordWindow activeWindow = wordDocument.ActiveWindow) {
						activeWindow.Activate();
						using (IPane activePane = activeWindow.ActivePane) {
							using (IWordView view = activePane.View) {
								view.Zoom.Percentage = 100;
							}
						}
					}
				} catch (Exception e) {
					if (e.InnerException != null) {
						LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException.Message);
					} else {
						LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.Message);
					}
				}
				try {
					wordApplication.Activate();
				} catch {
				}
				try {
					wordDocument.Activate();
				} catch {
				}
				return true;
			}
		}
        private async Task When_the_WordDocument_is_loaded()
        {
            var basePath = typeof(LoadWordDocumentFeature).Assembly.GetBasePath();

            var wordPath = Path.Combine(basePath, "TestingInfrastructure", "WordDocuments");

            var wordFilePath = Path.Combine(wordPath, _wordDocumentName);

            wordFilePath = Path.ChangeExtension(wordFilePath, ".docx");

            _wordDocument = await _wordDocumentRepo.LoadAsync(wordFilePath);
        }
Beispiel #15
0
        public override IWordParagraphObj <ChartType> Copy(IWordDocument Target, Index?Pos = null)
        {
            var Doc      = Target.To <WordDocumentMicrosoft>();
            var Index    = Doc.ToUnderlying(Doc.ToIndexActual(Pos), false);
            var PackDoc  = Doc.PackDocument;
            var NewChart = PackDoc.InlineShapes.AddChart2(Range: PackDoc.Range(Index));

            PackShape.Copy();
            NewChart.Chart.Paste();
            NewChart.Chart.ChartType = PackShape.Chart.ChartType.To <Microsoft.Office.Core.XlChartType>();
            return((IWordParagraphObj <ChartType>)NewChart.ToChart(Doc));
        }
Beispiel #16
0
 /// <summary>
 /// Handles the <see cref="Application.DocumentBeforeClose"/> event.
 /// </summary>
 /// <param name="doc">The document that is being closed.</param>
 /// <param name="cancel">The cancel flag that is to be set to cancel the operation.</param>
 private void HandleDocumentBeforeClose(Document doc, ref bool cancel)
 {
     this.logger.Log(TraceEventType.Information, "Word document closing: {0}", doc.Name);
     if (this.DocumentBeforeClose != null)
     {
         using (IWordDocument wordDoc = this.CreateWordDocument(doc))
         {
             CancellableDocumentOperationEventArgs e = new CancellableDocumentOperationEventArgs(wordDoc);
             this.DocumentBeforeClose(this, e);
             cancel = e.Cancel;
         }
     }
 }
 private void InitDocument(string _docFilePath)
 {
     if (string.IsNullOrEmpty(_docFilePath))
     {
         throw new Exception("Word文件路径不能为空!");
     }
     if (!File.Exists(_docFilePath))
     {
         throw new Exception("指定路径的Word文件不存在!");
     }
     using (Stream fileStream = new FileStream(_docFilePath, FileMode.Open, FileAccess.Read))
     {
         this._wordDocument = WordDocuemntFactory.Create(fileStream);
     }
 }
Beispiel #18
0
 public static void InsertIntoNewDocument(string tmpFile, string address, string tooltip)
 {
     using (IWordApplication wordApplication = GetOrCreateWordApplication()) {
         if (wordApplication == null)
         {
             return;
         }
         wordApplication.Visible = true;
         wordApplication.Activate();
         // Create new Document
         object template        = string.Empty;
         object newTemplate     = false;
         object documentType    = 0;
         object documentVisible = true;
         using (IDocuments documents = wordApplication.Documents) {
             using (IWordDocument wordDocument = documents.Add(ref template, ref newTemplate, ref documentType, ref documentVisible)) {
                 using (ISelection selection = wordApplication.Selection) {
                     // Add Picture
                     using (IInlineShape shape = AddPictureToSelection(selection, tmpFile)) {
                         if (!string.IsNullOrEmpty(address))
                         {
                             object screentip = Type.Missing;
                             if (!string.IsNullOrEmpty(tooltip))
                             {
                                 screentip = tooltip;
                             }
                             try {
                                 using (IHyperlinks hyperlinks = wordDocument.Hyperlinks) {
                                     hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
                                 }
                             } catch (Exception e) {
                                 LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
                             }
                         }
                     }
                 }
                 try {
                     wordDocument.Activate();
                 } catch {
                 }
                 try {
                     wordDocument.ActiveWindow.Activate();
                 } catch {
                 }
             }
         }
     }
 }
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            var tableDescsNotAbove = document
                                     .Tables
                                     .Where(f => f.Description.Position != Position.Above)
                                     .ToList();

            if (tableDescsNotAbove.Any())
            {
                var str = string.Join(", ", tableDescsNotAbove.Select(f => f.Description.PlainDescription));

                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, str)));
            }

            return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
        }
 /// <summary>
 /// Insert the bitmap stored under the tempfile path into the word document with the supplied caption
 /// </summary>
 /// <param name="wordCaption"></param>
 /// <param name="tmpFile"></param>
 /// <returns></returns>
 public static bool InsertIntoExistingDocument(string wordCaption, string tmpFile)
 {
     using (IWordApplication wordApplication = COMWrapper.GetInstance <IWordApplication>()) {
         if (wordApplication != null)
         {
             for (int i = 1; i <= wordApplication.Documents.Count; i++)
             {
                 IWordDocument wordDocument = wordApplication.Documents.item(i);
                 if (wordDocument.ActiveWindow.Caption.StartsWith(wordCaption))
                 {
                     return(InsertIntoExistingDocument(wordDocument, tmpFile));
                 }
             }
         }
     }
     return(false);
 }
        /// <summary>
        /// Loads the template.
        /// </summary>
        public void Load()
        {
            this.logger.Log(TraceEventType.Verbose, "Loading template.");
            this.buildingBlockCache.Clear();
            IWordDocument tempDocument = this.GetDocument();

            tempDocument.StartUpdate();
            try
            {
                this.layouts = this.wordTemplate.EnumerateBuildingBlockCategories()
                               .Where(category => this.CategoryIsLayout(category))
                               .Select(category => this.GetLayoutForCategory(tempDocument, category)).ToList();
            }
            finally
            {
                tempDocument.EndUpdate();
            }
        }
Beispiel #22
0
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            var words  = _wordMatcher.MatchWords(document, WordPrefix);
            var tables = document.Tables.Where(f => f.Description.PlainDescription.EndsWith(TableDescriptionSuffix))
                         .ToList();

            if (!tables.Any())
            {
                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, $"Table {WordPrefix} not found")));
            }

            if (tables.Count > 1)
            {
                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, $"More than one Table {WordPrefix} found")));
            }

            var table = tables.Single();

            var tableEntries = table
                               .Cells
                               .Where(f => f.ColumnIndex == 1)
                               .Skip(1)
                               .Select(f => f.Words.Single())
                               .Select(f => f.Characters.Text)
                               .ToList();

            if (words.Count != tableEntries.Count())
            {
                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, $"Found {words.Count} words, but {tableEntries.Count} table entries")));
            }

            for (var i = 0; i < words.Count; i++)
            {
                var word       = words.ElementAt(i).Value;
                var tableValue = $"[{tableEntries.ElementAt(i)}]";

                if (word != tableValue)
                {
                    return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, $"Found {word} word, but {tableValue} in table")));
                }
            }

            return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
        }
Beispiel #23
0
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            var differentFonts = document
                                 .Words
                                 .SelectMany(f => f.Characters.Entries)
                                 .Select(f => f.Font)
                                 .Select(f => f.Name)
                                 .Where(f => !_nonFonts.Contains(f))
                                 .Distinct()
                                 .ToList();

            if (differentFonts.Count() == 1)
            {
                return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
            }

            var differents = string.Join(", ", differentFonts);

            return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, $"Found the following different Fonts: {differents}")));
        }
        private static bool CheckMatching(IWordDocument document, int itemsCount)
        {
            for (var i = 0; i < itemsCount; i++)
            {
                var table         = document.Tables.ElementAtOrDefault(i);
                var tableFromList = document.ListOfTables.Entries.ElementAtOrDefault(i);

                if (table == null || tableFromList == null)
                {
                    return(false);
                }

                if (!tableFromList.Text.StartsWith(table.Description.PlainDescription))
                {
                    return(false);
                }
            }

            return(true);
        }
 public static void InsertIntoNewDocument(string tmpFile)
 {
     using (IWordApplication wordApplication = COMWrapper.GetOrCreateInstance <IWordApplication>()) {
         if (wordApplication != null)
         {
             wordApplication.Visible = true;
             wordApplication.Activate();
             // Create new Document
             object        template        = string.Empty;
             object        newTemplate     = false;
             object        documentType    = 0;
             object        documentVisible = true;
             IWordDocument wordDocument    = wordApplication.Documents.Add(ref template, ref newTemplate, ref documentType, ref documentVisible);
             // Add Picture
             AddPictureToSelection(wordApplication.Selection, tmpFile);
             wordDocument.Activate();
             wordDocument.ActiveWindow.Activate();
         }
     }
 }
        private static bool CheckMatching(IWordDocument document, int itemsCount)
        {
            for (var i = 0; i < itemsCount; i++)
            {
                var shape        = document.Shapes.ElementAtOrDefault(i);
                var figuresShape = document.ListOfShapes.Entries.ElementAtOrDefault(i);

                if (shape == null || figuresShape == null)
                {
                    return(false);
                }

                if (!figuresShape.Text.StartsWith(shape.Description.PlainDescription))
                {
                    return(false);
                }
            }

            return(true);
        }
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            var glossaryTables = document
                                 .Tables
                                 .Where(f => f.Description.PlainDescription.EndsWith("Glossar"))
                                 .ToList();

            if (!glossaryTables.Any())
            {
                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, "GlossaryTable not found")));
            }

            if (glossaryTables.Count > 1)
            {
                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, "More than one GlossaryTable found")));
            }

            var missingWords  = new List <string>();
            var glossaryTable = glossaryTables.Single();

            var glossaryCells = glossaryTable.Cells.Where(f => f.RowIndex > 1 && f.ColumnIndex == 1);

            foreach (var cell in glossaryCells)
            {
                var cellWord = string.Join(string.Empty, cell.Words.Select(f => f.Characters.Text));

                if (document.Words.Count(f => f.Characters.Text == cellWord) == 1)
                {
                    missingWords.Add(cellWord);
                }
            }

            if (missingWords.Any())
            {
                var str = string.Join(", ", missingWords);

                return(Task.FromResult(RuleCheckResult.CreateFailure(RuleName, str)));
            }

            return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
        }
        public Task <RuleCheckResult> CheckRuleAsync(IWordDocument document)
        {
            if (!document.Sections.Entries.Any())
            {
                return(Failure(FailureNoSections));
            }

            var firstSection = document.Sections.Entries.First();

            if (!firstSection.PageNumberDefinitions.Any())
            {
                return(Failure(FailureNoPageNumbers));
            }

            if (firstSection.PageNumberDefinitions.First().ShowFirstPageNumber)
            {
                return(Failure(FailurePageNumber));
            }

            return(Task.FromResult(RuleCheckResult.CreatePassed(RuleName)));
        }
Beispiel #29
0
 public static bool InsertIntoExistingDocument(IWordDocument wordDocument, string tmpFile)
 {
     if (wordDocument.Application.Selection != null)
     {
         AddPictureToSelection(wordDocument.Application.Selection, tmpFile);
         try {
             wordDocument.ActiveWindow.ActivePane.View.Zoom.Percentage = 100;
         } catch (Exception e) {
             if (e.InnerException != null)
             {
                 LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException.Message);
             }
             else
             {
                 LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.Message);
             }
         }
         return(true);
     }
     return(false);
 }
Beispiel #30
0
        /// <summary>
        /// genearate document
        /// </summary>
        /// <param name="fileByte"></param>
        /// <param name="documentContent"></param>
        /// <returns></returns>
        public byte[] GenerateDocument(byte[] fileByte, List <DocContent> documentContent, string outputFileType)
        {
            #region logging
            //System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Date : " + DateTime.Now.ToString());
            //System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Input FileBytes : " +  fileByte.Length.ToString());
            //System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Memory created : " + fileMemoryStream.Length.ToString());
            //System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Add parameters and value" + documentTemplate.Sections.Count.ToString());
            //System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Saving docio : " + documentTemplate.Document.Count.ToString());
            ///System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Save success memory stream length : " + docIoMemoryStream.Length.ToString());
            //System.IO.File.AppendAllText(@"C:\ErrorLog.txt", "\r\n Save success pdf memory stream length : " + docIoPdfMemoryStream.Length.ToString());
            #endregion

            byte[] docIoFileByte = null;
            if (fileByte != null)
            {
                MemoryStream fileMemoryStream = new MemoryStream();
                fileMemoryStream.Write(fileByte, 0, fileByte.Length);
                _documentTemplate = new WordDocument(fileMemoryStream);

                //read the text parameters values and placeholders to be replacedin document
                foreach (DocContent itemDocContent in documentContent)
                {
                    _documentTemplate.Replace(itemDocContent.ContentKey, itemDocContent.ContentText, true, true);
                }
                MemoryStream docIoMemoryStream = null;
                if (outputFileType.ToUpper() == PdfExtension.ToUpper())
                {
                    docIoMemoryStream = GetPDFStream();
                }
                else if (outputFileType.ToUpper() == DocExtension.ToUpper())
                {
                    docIoMemoryStream = GetWordStream();
                }
                docIoMemoryStream.Seek(0, SeekOrigin.Begin);
                docIoFileByte = docIoMemoryStream.ToArray();
                docIoMemoryStream.Close();
            }
            return(docIoFileByte);
        }
Beispiel #31
0
        /// <summary>
        /// Get the captions of all the open word documents
        /// </summary>
        /// <returns></returns>
        public static List <string> GetWordDocuments()
        {
            List <string> openDocuments = new List <string>();

            try {
                using (IWordApplication wordApplication = GetWordApplication()) {
                    if (wordApplication == null)
                    {
                        return(openDocuments);
                    }
                    using (IDocuments documents = wordApplication.Documents) {
                        for (int i = 1; i <= documents.Count; i++)
                        {
                            using (IWordDocument document = documents.item(i)) {
                                if (document.ReadOnly)
                                {
                                    continue;
                                }
                                if (isAfter2003())
                                {
                                    if (document.Final)
                                    {
                                        continue;
                                    }
                                }
                                using (IWordWindow activeWindow = document.ActiveWindow) {
                                    openDocuments.Add(activeWindow.Caption);
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
            }
            openDocuments.Sort();
            return(openDocuments);
        }
Beispiel #32
0
 /// <summary>
 /// Insert the bitmap stored under the tempfile path into the word document with the supplied caption
 /// </summary>
 /// <param name="wordCaption"></param>
 /// <param name="tmpFile"></param>
 /// <returns></returns>
 public static bool InsertIntoExistingDocument(string wordCaption, string tmpFile)
 {
     using (IWordApplication wordApplication = GetWordApplication()) {
         if (wordApplication == null)
         {
             return(false);
         }
         using (IDocuments documents = wordApplication.Documents) {
             for (int i = 1; i <= documents.Count; i++)
             {
                 using (IWordDocument wordDocument = documents.item(i)) {
                     using (IWordWindow activeWindow = wordDocument.ActiveWindow) {
                         if (activeWindow.Caption.StartsWith(wordCaption))
                         {
                             return(InsertIntoExistingDocument(wordApplication, wordDocument, tmpFile, null, null));
                         }
                     }
                 }
             }
         }
     }
     return(false);
 }
 internal static bool InsertIntoExistingDocument(IWordDocument wordDocument, string tmpFile)
 {
     if (wordDocument.Application.Selection != null) {
         AddPictureToSelection(wordDocument.Application.Selection, tmpFile);
         try {
             wordDocument.ActiveWindow.ActivePane.View.Zoom.Percentage = 100;
         } catch (Exception e) {
             if (e.InnerException != null) {
                 LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException.Message);
             } else {
                 LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.Message);
             }
         }
         wordDocument.Application.Activate();
         wordDocument.Activate();
         wordDocument.ActiveWindow.Activate();
         return true;
     }
     return false;
 }
Beispiel #34
0
 public FontStyleBase(IWordDocument document)
 {
     Names = document.AddParagraphStyle("Names");
     Names.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;
     Names.CharacterFormat.FontSize = 22;
 }