using Syncfusion.DocIO.DLS; using Syncfusion.DocIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.Calculate; using Helper; using System.Data; using Model; using System.Linq.Expressions; using NLog; using Syncfusion.XlsIO.Implementation.XmlSerialization; using System.Security.Authentication.ExtendedProtection; using System.Drawing; using Syncfusion.XPS; using System.Xml.Linq; using System.Text.RegularExpressions; using SkiaSharp; using Syncfusion.DocToPDFConverter; using Syncfusion.Pdf; using System.Management.Instrumentation; using Syncfusion.XlsIO.FormatParser.FormatTokens; using System.Security.Policy; using System.Buffers.Text; using Syncfusion.XlsIO.Implementation.TemplateMarkers; using System.Drawing.Printing; using Syncfusion.XlsIO; namespace DOCGEN.Klassen { public class SynFWord { public bool create_nativ(string property, string value, string base64, string originalfile, string destfile) { FileStream ms = new FileStream(originalfile, FileMode.Open, FileAccess.Read); WordDocument document = new WordDocument(); document.Open(ms, FormatType.Automatic); try { document.CustomDocumentProperties.Add(property, value); } catch { document.CustomDocumentProperties.Remove(property); document.CustomDocumentProperties.Add(property, value); } document.Save(destfile); ms.Close(); document.Dispose(); return true; } public string Generate_Word(string base64, clsDocData docdata) { string formattype = ""; MemoryStream ms = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(base64)); WordDocument document = new WordDocument(ms, FormatType.Doc); formattype = document.ActualFormatType.ToString(); var formattype_original = document.ActualFormatType; foreach (clsDocValue dv in docdata.DocValues) { if (dv.TMBeginn.ToString() != "" && dv.TMEnd.ToString() == "") { try { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); if ((dv.TMBeginn.ToString() == "TGEDKVornameNameLinksB99" || dv.TMBeginn.ToString() == "TGEDKVornameNameRechtsB99") && docdata.As_Faksimile == "True") { bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); IWParagraph paragraph = new WParagraph(document); paragraph.AppendBreak(BreakType.LineBreak); System.Drawing.Image image = System.Drawing.Image.FromFile(@"x:\docdemo\unterschriften\kube1.png"); paragraph.AppendPicture(image); paragraph.AppendBreak(BreakType.LineBreak); paragraph.AppendText(dv.Value.ToString()); bookmarkNavigator.InsertParagraph(paragraph); } else { bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); bookmarkNavigator.InsertText(dv.Value.ToString()); } } catch { } } if (dv.TMBeginn.ToString() != "" && dv.TMEnd.ToString() != "") { try { ReplaceBookmarkContent(ref document, dv.TMBeginn.ToString(), dv.TMEnd.ToString(), dv.Value.ToString()); } catch { } } if (dv.FieldName.ToString() != "") { try { foreach (WSection section in document.Sections) //Iterates through section child elements foreach (WTextBody textBody in section.ChildEntities) { //Iterates through form fields foreach (WFormField formField in textBody.FormFields) { if (formField.Name == dv.FieldName.ToString()) { formField.Text = dv.Value.ToString(); break; } } } } catch { } } } if (docdata.As_Faksimile == "True") { TextSelection[] textSelections = document.FindAll("Thurgauer Kantonalbank", false, true); foreach (TextSelection selection in textSelections) { WTextRange textRange = selection.GetAsOneRange(); WTextBody ownerTextBody = textRange.OwnerParagraph.OwnerTextBody; //Get the index of the paragraph with specified text int ownerParaIndex = ownerTextBody.ChildEntities.IndexOf(textRange.OwnerParagraph); //Check whether the previous and next paragraphs are empty and remove them if (ownerParaIndex > 0 && ownerTextBody.ChildEntities[ownerParaIndex - 1] is WParagraph && (ownerTextBody.ChildEntities[ownerParaIndex - 1] as WParagraph).Items.Count == 0) { ownerTextBody.ChildEntities.RemoveAt(ownerParaIndex - 1); } if (ownerParaIndex + 1 < ownerTextBody.ChildEntities.Count && ownerTextBody.ChildEntities[ownerParaIndex + 1] is WParagraph && (ownerTextBody.ChildEntities[ownerParaIndex + 1] as WParagraph).Items.Count == 0) { for (int i = 0; i < 4; i++) { try { ownerTextBody.ChildEntities.RemoveAt(ownerParaIndex + 1); } catch { } } } } } foreach (clsDocMacro dm in docdata.DocMacros) { switch (dm.Name.ToUpper()) { case "DOKUMENTSCHUETZEN": document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); break; default: break; } if (dm.BookMark != "") { if (document.ProtectionType == ProtectionType.NoProtection) { WParagraph paragraph = document.Sections[0].Paragraphs[0] as WParagraph; BookmarkStart bookmarkStart = new BookmarkStart(document, dm.BookMark); paragraph.Items.Insert(0, bookmarkStart); } else { document.Protect(ProtectionType.NoProtection, "Australia"); WParagraph paragraph = document.Sections[0].Paragraphs[0] as WParagraph; BookmarkStart bookmarkStart = new BookmarkStart(document, dm.BookMark); BookmarkEnd bookmarkEnd = new BookmarkEnd(document, dm.BookMark); paragraph.Items.Insert(0, bookmarkStart); paragraph.Items.Insert(2, bookmarkEnd); document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); } } } if (docdata.Barcode == true) { Insert_Barcode(document, docdata); } //document.UpdateDocumentFields(); //document.UpdateAlternateChunks(); MemoryStream destms = new MemoryStream(); if (formattype_original.ToString().ToUpper() == "DOTMXXX") { document.Save(destms, FormatType.Docm); } else { document.Save(destms, formattype_original); } document.Close(); document.Dispose(); byte[] imageArray = destms.ToArray(); if (docdata.Result_as_PDF == "True") { DocGet getdoc = new DocGet(""); string destdoc = ""; destdoc = getdoc.Convert_Word_To_PDF(Convert.ToBase64String(imageArray)); return destdoc; } return Convert.ToBase64String(imageArray); } public static void ReplaceBookmarkText(ref WordDocument document, string bookmarkName, string textToFind, string textToReplace) { //Check whether the bookmark name is valid. if (string.IsNullOrEmpty(bookmarkName) || document.Bookmarks.FindByName(bookmarkName) == null) return; //Move to the virtual cursor before the bookmark end location of the bookmark. BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); bookmarksNavigator.MoveToBookmark(bookmarkName); //Replace the bookmark content with new text. TextBodyPart textBodyPart = bookmarksNavigator.GetBookmarkContent(); //Get paragraph from the textBody part. foreach (TextBodyItem item in textBodyPart.BodyItems) { IterateTextBody(item, textToFind, textToReplace); } //Replace the bookmark content with text body part. bookmarksNavigator.ReplaceBookmarkContent(textBodyPart); } public static void IterateTextBody(TextBodyItem item, string textToFind, string textToReplace) { switch (item.EntityType) { case EntityType.Paragraph: WParagraph paragraph = (WParagraph)item; //Replace a text in the bookmark content. paragraph.Replace(new System.Text.RegularExpressions.Regex(textToFind), textToReplace); break; case EntityType.Table: WTable table = (WTable)item; foreach (WTableRow row in table.Rows) { foreach (WTableCell cell in row.Cells) { foreach (TextBodyItem bodyItem in cell.ChildEntities) { IterateTextBody(bodyItem, textToFind, textToReplace); } } } break; case EntityType.BlockContentControl: WTextBody body = (item as IBlockContentControl).TextBody; foreach (TextBodyItem bodyitem in body.ChildEntities) IterateTextBody(bodyitem, textToFind, textToReplace); break; } } public void ReplaceBookmarkContent(ref WordDocument document, String bookmark1, String bookmark2, String replacementContent) { //Temp Bookmark. String tempBookmarkName = "tempBookmark"; #region Insert bookmark start after bookmark1. //Get the bookmark instance by using FindByName method of BookmarkCollection with bookmark name. Bookmark firstBookmark = document.Bookmarks.FindByName(bookmark1); //Access the bookmark end’s owner paragraph by using bookmark. WParagraph firstBookmarkOwnerPara = firstBookmark.BookmarkEnd.OwnerParagraph; //Get the index of bookmark end of bookmark1. int index = firstBookmarkOwnerPara.Items.IndexOf(firstBookmark.BookmarkEnd); //Create and add new bookmark start after bookmark1. BookmarkStart newBookmarkStart = new BookmarkStart(document, tempBookmarkName); firstBookmarkOwnerPara.ChildEntities.Insert(index + 1, newBookmarkStart); #endregion #region Insert bookmark end before bookmark2. //Get the bookmark instance by using FindByName method of BookmarkCollection with bookmark name. Bookmark secondBookmark = document.Bookmarks.FindByName(bookmark2); //Access the bookmark start’s owner paragraph by using bookmark. WParagraph secondBookmarkOwnerPara = secondBookmark.BookmarkStart.OwnerParagraph; //Get the index of bookmark start of bookmark2. index = secondBookmarkOwnerPara.Items.IndexOf(secondBookmark.BookmarkStart); //Create and add new bookmark end before bookmark2. BookmarkEnd newBookmarkEnd = new BookmarkEnd(document, tempBookmarkName); secondBookmarkOwnerPara.ChildEntities.Insert(index, newBookmarkEnd); #endregion #region Select bookmark content and replace. //Create the bookmark navigator instance to access the newly created bookmark. BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); //Move the virtual cursor to the location of the temp bookmark. bookmarkNavigator.MoveToBookmark(tempBookmarkName); //Replace the bookmark content. bookmarkNavigator.ReplaceBookmarkContent(replacementContent, true); #endregion #region Remove that temporary bookmark. //Get the bookmark instance by using FindByName method of BookmarkCollection with bookmark name. Bookmark bookmark = document.Bookmarks.FindByName(tempBookmarkName); //Remove the temp bookmark named from Word document. document.Bookmarks.Remove(bookmark); #endregion } private void RemoveEmptyParagraph(IWSection curSection) { int j = 0; int paraCount = 0; while (j < curSection.Body.ChildEntities.Count) { //Read the section text body WTextBody textBody = curSection.Body; //Read all the body items collection BodyItemCollection textbodycollection = textBody.ChildEntities as BodyItemCollection; if (textbodycollection[j].EntityType == EntityType.Paragraph) { IWParagraph paragraph = textbodycollection[j] as IWParagraph; if (paragraph.Items.Count == 0) { //Remove the empty paragraph to the Section curSection.Paragraphs.RemoveAt(paraCount); } else { paraCount++; j++; } } else { j++; } } } private static Entity GetOwnerEntity(BookmarkStart bookmarkStart) { Entity baseEntity = bookmarkStart.Owner; while (!(baseEntity is WSection)) { if (baseEntity is null) return baseEntity; baseEntity = baseEntity.Owner; } return baseEntity; } public Image resizeImage(Image imgToResize, Size size) { return (Image)(new Bitmap(imgToResize, size)); } private static void FindAndReplaceInTable(WTable table, TextSelection textSelection) { //Iterate through the rows of table. foreach (WTableRow row in table.Rows) { //Iterate through the cells of rows. foreach (WTableCell cell in row.Cells) { //Iterates through the items in cell. foreach (Entity entity in cell.ChildEntities) { if (entity.EntityType == EntityType.Paragraph) { WParagraph paragraph = entity as WParagraph; //Replace the specified regular expression with a TextSelection in the paragraph. paragraph.Replace(new Regex("<<(.*)>>"), textSelection); } else if (entity.EntityType == EntityType.Table) { FindAndReplaceInTable(entity as WTable, textSelection); } } } } } public void Insert_Barcode(WordDocument document, clsDocData docData) { BarcodeLib.Barcode Barcode = new BarcodeLib.Barcode(); System.Drawing.Image barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5C, docData.Dokumentid.Substring(9, 13), docData.Dokumentid.Substring(9, 13), "Below", "Arial", 8, 0); //EDOKA_Barcode.EDOKABC bc = new EDOKA_Barcode.EDOKABC(); //System.Drawing.Image barcodeimage = bc.getimg("Interleaved 2 of 5 Mod 10", docData.Dokumentid.Substring(9,13), 190, 120); // OFFEDK0002024002441185 //BarcodeSettings bs = new BarcodeSettings(); //bs.Type = BarCodeType.Interleaved25; //bs.ShowBottomText = true; //bs.ShowTopText = false; //bs.BottomText = Documentid.Substring(9, 13); ; //bs.Data = Documentid.Substring(9, 13); ////bs.ImageWidth = 200; ////bs.ImageHeight = 40; //BarCodeGenerator bg = new BarCodeGenerator(bs); //bg.GenerateImage().Save(@"h:\edoka_work\bc.jpg"); // FileStream imageStream = new FileStream(@"h:\edoka_work\bc.jpg", FileMode.Open, FileAccess.Read); foreach (WSection section in document.Sections) { int bchor = 400; int bcver = 700; WPicture picture = new WPicture(document); picture.LoadImage(barcodeimage); picture.Height = 40; picture.Width = 140; picture.VerticalPosition = bcver; picture.HorizontalPosition = bchor; picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Margin; picture.TextWrappingStyle = TextWrappingStyle.Square; WPicture picture2 = new WPicture(document); picture2.LoadImage(barcodeimage); picture2.Height = 40; picture2.Width = 140; picture2.VerticalPosition = bcver; picture2.HorizontalPosition = bchor; picture2.HorizontalOrigin = HorizontalOrigin.Page; picture2.VerticalOrigin = VerticalOrigin.Margin; picture2.TextWrappingStyle = TextWrappingStyle.Square; //Insert image in Header and Footer of section section.HeadersFooters.Footer.AddParagraph().ChildEntities.Add(picture); section.HeadersFooters.FirstPageFooter.AddParagraph().ChildEntities.Add(picture2); } } /// Word to PDF-Konverter /// Das sind die Remarks /// Base64-Dokument public string DocToPDF(string dokument) { MemoryStream ms = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(dokument)); WordDocument document = new WordDocument(ms, FormatType.Automatic); int i = 0; //Iterate each section from Word document foreach (WSection section in document.Sections) { //Create new Word document WordDocument newDocument = new WordDocument(); //Add cloned section into new Word document newDocument.Sections.Add(section.Clone()); //Saves the Word document to MemoryStream FileStream outputStream = new FileStream(@"x:\T1.dotm", FileMode.OpenOrCreate, FileAccess.ReadWrite); newDocument.Save(outputStream, FormatType.Dotm); document.Sections.RemoveAt(i); FileStream outputStream1 = new FileStream(@"x:\T2.dotm", FileMode.OpenOrCreate, FileAccess.ReadWrite); document.Save(outputStream1, FormatType.Dotm); newDocument.Close(); document.Close(); outputStream.Close(); outputStream1.Close(); i++; } return ""; //int cnt = document.Sections.Count; //TextSelection textSelection = document.Find("Exemplar für", false, true); //return dokument; } public int GetPageNumber(string text, WordDocument wd) { //DocToPDFConverter converter = new DocToPDFConverter(); //PdfDocument pdfDocument = converter.ConvertToPDF(wd); //MemoryStream stream = new MemoryStream(); //pdfDocument.Save(stream); //pdfDocument.Close(true); //wd.Close(); //converter.Dispose(); //stream.Position = 0; //FileStream fileStream = new FileStream("Output.pdf", FileMode.Create); //stream.CopyTo(fileStream); //fileStream.Close(); //PdfViewerControl documentViewer = new PdfViewerControl(); ////Load the PDF document //documentViewer.Load(stream); ////Get the occurrences of the target text and location. //Dictionary> textSearch = new Dictionary>(); //bool IsMatchFound = documentViewer.FindText("Revision History", out textSearch); //List pageNumbers = null; //if (IsMatchFound) //{ // pageNumbers = GetPageNumebers(textSearch); //} //documentViewer.Dispose(); return 0; } public void Print_Word(string dokument) { MemoryStream ms = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(dokument)); WordDocument document = new WordDocument(ms, FormatType.Automatic); document.UpdateDocumentFields(); int i = 0; //Iterate each section from Word document foreach (WSection section in document.Sections) { //Create new Word document WordDocument newDocument = new WordDocument(); //Add cloned section into new Word document newDocument.Sections.Add(section.Clone()); //Saves the Word document to MemoryStream FileStream outputStream = new FileStream(@"x:\T1.dotm", FileMode.OpenOrCreate, FileAccess.ReadWrite); newDocument.Save(outputStream, FormatType.Dotm); document.Sections.RemoveAt(i); FileStream outputStream1 = new FileStream(@"x:\T2.dotm", FileMode.OpenOrCreate, FileAccess.ReadWrite); document.Save(outputStream1, FormatType.Dotm); newDocument.Close(); document.Close(); outputStream.Close(); outputStream1.Close(); i++; } } public void SplitDocument(ref WordDocument wordDocument, ref WordDocument target, int SectionNumber) { target.Sections.Add(wordDocument.Sections[SectionNumber].Clone()); } public void SplitDocument_Part2(ref WordDocument wordDocument, ref WordDocument target, int SectionNumber) { int i = 0; foreach (WSection section in wordDocument.Sections) { if (i != SectionNumber) { target.Sections.Add(wordDocument.Sections[i].Clone()); } i = i + 1; } return; WTextBody textBody = null; for (int i1 = target.Sections.Count - 1; i >= 0; i--) { //Accesses the Body of section where all the contents in document are apart textBody = target.Sections[i].Body; //Removes the last empty page in the Word document RemoveEmptyItems(textBody); //Removes the empty sections in the document if (textBody.ChildEntities.Count == 0) { int SectionIndex = target.ChildEntities.IndexOf(target.Sections[i]); target.ChildEntities.RemoveAt(SectionIndex); } } } private void RemoveEmptyItems(WTextBody textBody) { //A flag to determine any renderable item found in the Word document. bool IsRenderableItem = false; //Iterates into textbody items. for (int itemIndex = textBody.ChildEntities.Count - 1; itemIndex >= 0 && !IsRenderableItem; itemIndex--) { #region Removes last empty paragraph //Checks item is empty paragraph and removes it. if (textBody.ChildEntities[itemIndex] is WParagraph) { WParagraph paragraph = textBody.ChildEntities[itemIndex] as WParagraph; //Iterates into paragraph for (int pIndex = paragraph.Items.Count - 1; pIndex >= 0; pIndex--) { ParagraphItem paragraphItem = paragraph.Items[pIndex]; //Removes page breaks if ((paragraphItem is Syncfusion.DocIO.DLS.Break && (paragraphItem as Syncfusion.DocIO.DLS.Break).BreakType == BreakType.PageBreak)) paragraph.Items.RemoveAt(pIndex); //Check paragraph contains any renderable items. else if (!(paragraphItem is BookmarkStart || paragraphItem is BookmarkEnd)) { //Found renderable item and break the iteration. IsRenderableItem = true; break; } } //Remove empty paragraph and the paragraph with bookmarks only if (paragraph.Items.Count == 0 || !IsRenderableItem) textBody.ChildEntities.RemoveAt(itemIndex); } #endregion } } public void Replace_Text(ref WordDocument wordDocument, string TextToReplace, string NewText) { wordDocument.Replace(TextToReplace, NewText, true, true); } public void Replace_Fieldtext(ref WordDocument wordDocument, string fieldname, string newvalue) { try { foreach (WSection section in wordDocument.Sections) //Iterates through section child elements foreach (WTextBody textBody in section.ChildEntities) { //Iterates through form fields foreach (WFormField formField in textBody.FormFields) { if (formField.Name == fieldname) { formField.Text = newvalue; break; } } } } catch { } } } }