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 System.Drawing.Drawing2D; 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; using System.Security.Permissions; using System.Net; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using static System.Net.Mime.MediaTypeNames; using System.Diagnostics; using Database; using System.Drawing.Drawing2D; using Syncfusion.Drawing; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Syncfusion.Windows.Forms.Chart; using Microsoft.SqlServer.Server; using Syncfusion.Windows.Forms.Chart.SvgBase; using System.Drawing.Imaging; using BarcodeLib; using Logging; namespace DOCGEN.Klassen { public class SyncFWord { public string resturi = ""; public string apikey = ""; public SyncFWord(string resturi, string apikey) { this.resturi = resturi; this.apikey = apikey; } 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(@originalfile, FormatType.Automatic); //document.Open(ms, FormatType.Automatic); try { document.CustomDocumentProperties.Add(property, value); } catch { document.CustomDocumentProperties.Remove(property); document.CustomDocumentProperties.Add(property, value); } TextSelection[] textSelections = document.FindAll("{" + property + "}", false, true); try { foreach (TextSelection textSelection in textSelections) { //Gets the found text as single text range and sets highlight color WTextRange textRange = textSelection.GetAsOneRange(); textRange.Text = value; } } catch { } Logging.Logging.Debug("Create Native: " + destfile, "Ondoc", ""); document.UpdateDocumentFields(); document.Save(destfile); //ms.Close(); document.Dispose(); return true; } private string get_image(int imageid, int width, int height) { string URL = resturi + "API/GetImageAsBase64?imageid=" + imageid.ToString() + "&ImageWidth=" + width.ToString() + "&ImageHeight=" + height.ToString(); HttpWebRequest webRequest = HttpWebRequest.Create(URL) as HttpWebRequest; webRequest.Method = WebRequestMethods.Http.Get; webRequest.Headers["Authorization"] = "Bearer " + apikey; try { using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseContent = reader.ReadToEnd(); return responseContent; } else { Logging.Logging.Error(URL + ": " + response.StatusCode.ToString() + " / " + response.StatusDescription, "Client - GetImage", ""); return ""; } } } catch (Exception ex) { return ""; } } private string get_unterschrift(string MaNr) { string URL = resturi + "API/GetUnterschriftAsBase64ByMitarbeiternr?MaNr=" + MaNr; HttpWebRequest webRequest = HttpWebRequest.Create(URL) as HttpWebRequest; webRequest.Method = WebRequestMethods.Http.Get; webRequest.Headers["Authorization"] = "Bearer " + apikey; try { using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseContent = reader.ReadToEnd(); return responseContent; } else { Logging.Logging.Error(URL + ": " + response.StatusCode.ToString() + " / " + response.StatusDescription, "Clinet - DokList GetDocument", ""); return ""; } } } catch (Exception ex) { return ""; } } private System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size) { return (System.Drawing.Image)new Bitmap(imgToResize, size); } public void set_compatibilitymode(ref WordDocument document, string force) { CompatibilityMode compatibilityMode = document.Settings.CompatibilityMode; Logging.Logging.Debug(compatibilityMode.ToString(), "ondoc sf", force); switch (compatibilityMode) { case CompatibilityMode.Word2003: document.Settings.CompatibilityMode = CompatibilityMode.Word2010; break; case CompatibilityMode.Word2010: document.Settings.CompatibilityMode = CompatibilityMode.Word2010; break; case CompatibilityMode.Word2013: document.Settings.CompatibilityMode = CompatibilityMode.Word2013; break; default: //document.Settings.CompatibilityMode = CompatibilityMode.Word2003; break; } if (force != "" && force != "Standard") { if (force == "Word 2013") { document.Settings.CompatibilityMode = CompatibilityMode.Word2013; Logging.Logging.Debug("Übersteuerung CompatibilityMode: neu" + force, "ondoc", ""); } if (force == "Word 2010") { document.Settings.CompatibilityMode = CompatibilityMode.Word2010; Logging.Logging.Debug("Übersteuerung CompatibilityMode: neu" + force, "ondoc", ""); } } } private void Insert_CLMValue(CLMDocItem item, ref WordDocument document) { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); try { switch (item.type.ToString()) { case "4": case "7": case "8": case "9": case "10": case "13": case "14": case "15": case "16": case "18": try { ReplaceBookmarkContent(ref document, item.itemname, "", item.itemvalue, false); } catch { Insert_CLMField(item, ref document); } break; //bookmarkNavigator.MoveToBookmark(bookmark); //bookmarkNavigator.ReplaceBookmarkContent(item.itemvalue.ToString(), true); //break; case "3": // Neu Checkbox foreach (WSection section in document.Sections) foreach (WTextBody textBody in section.ChildEntities) { foreach (WFormField formField in textBody.FormFields) { if (formField.Name == item.field.ToString()) { string type = formField.FieldType.ToString(); if (type == "FieldFormCheckBox") { WCheckBox cb = (WCheckBox)formField; if (item.itemvalue.ToString().ToUpper() != "") { cb.Checked = true; } } break; } } } break; case "5": Insert_CLMImage(item, ref document); break; case "6": Insert_CLMImages(item, ref document, true); break; case "11": Insert_CLMLogo(item,ref document); break; case "12": Insert_CLMTable(item, ref document); break; case "17": //Datamatrix Insert_CLMDataMatrix(item,ref document); break; } } catch { } finally { bookmarkNavigator = null; } } private void Insert_CLMLogo(CLMDocItem item, ref WordDocument document) { // IWSection section = document.Sections[0]; // IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph(); // string b64 = Newtonsoft.Json.JsonConvert.DeserializeObject(get_image(4, -1, 0)); byte[] imageBytes = Convert.FromBase64String(item.itemvalue); using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { System.Drawing.Image image = System.Drawing.Image.FromStream(ms); //paragraph.AppendPicture(image); WPicture picture = new WPicture(document); WPicture picture2 = new WPicture(document); picture.LoadImage(image); picture2.LoadImage(image); picture.VerticalPosition = Convert.ToInt32(item.left); picture.HorizontalPosition = Convert.ToInt32(item.top); picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Page; picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Largest; picture2.VerticalPosition = picture.VerticalPosition; picture2.HorizontalPosition = picture.HorizontalPosition; picture2.HorizontalOrigin = HorizontalOrigin.Page; picture2.VerticalOrigin = VerticalOrigin.Page; picture2.TextWrappingStyle = TextWrappingStyle.Square; picture2.TextWrappingType = TextWrappingType.Largest; picture.Rotation = 0; picture.Height = Convert.ToInt32(item.height); picture.Width = Convert.ToInt32(item.width); picture.VerticalPosition = Convert.ToInt32(item.top); picture.HorizontalPosition = Convert.ToInt32(item.left); picture2.Rotation = 0; picture2.Height = picture.Height; picture2.Width = picture.Width; picture2.VerticalPosition = picture.VerticalPosition; picture2.HorizontalPosition = picture.HorizontalPosition; //foreach (IWSection section in document.Sections) //{ IWSection section = document.Sections[0]; if (section.PageSetup.DifferentFirstPage == true) { WParagraph FirstfooterPar = new WParagraph(document); FirstfooterPar.ChildEntities.Add(picture); if (section.HeadersFooters.FirstPageHeader.Paragraphs.Count > 0) { section.HeadersFooters.FirstPageHeader.Paragraphs.RemoveAt(section.HeadersFooters.FirstPageHeader.Paragraphs.Count - 1); } section.HeadersFooters.FirstPageHeader.Paragraphs.Add(FirstfooterPar); } WParagraph footerPar = new WParagraph(document); footerPar.ChildEntities.Add(picture2); if (section.HeadersFooters.Header.Count > 0) { section.HeadersFooters.Header.Paragraphs.RemoveAt(section.HeadersFooters.Header.Paragraphs.Count - 1); } section.HeadersFooters.Header.Paragraphs.Add(footerPar); } } private void Insert_CLMDataMatrix(CLMDocItem item, ref WordDocument document) { BarcodeLib.Barcode Barcode = new BarcodeLib.Barcode(); System.Drawing.Image barcodeimage = Barcode.Get_Datamatrix(DataMatrix.net.DmtxScheme.DmtxSchemeAscii, item.itemvalue.ToString(), 6, 6, 0, "Right", item.itemvalue.ToString().Substring(5,16),"", 12); System.Drawing.Image barcodeimage2; barcodeimage2 = barcodeimage; WPicture picture = new WPicture(document); WPicture picture2 = new WPicture(document); picture.LoadImage(barcodeimage); picture2.LoadImage(barcodeimage); picture.VerticalPosition = Convert.ToInt32(item.left); picture.HorizontalPosition = Convert.ToInt32(item.top); picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Page; picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Largest; picture2.VerticalPosition = picture.VerticalPosition; picture2.HorizontalPosition = picture.HorizontalPosition; picture2.HorizontalOrigin = HorizontalOrigin.Page; picture2.VerticalOrigin = VerticalOrigin.Page; picture2.TextWrappingStyle = TextWrappingStyle.Square; picture2.TextWrappingType = TextWrappingType.Largest; picture.Rotation = 0; picture.Height = Convert.ToInt32(item.height); picture.Width = Convert.ToInt32(item.width); picture.VerticalPosition = Convert.ToInt32(item.top); picture.HorizontalPosition = Convert.ToInt32(item.left); picture2.Rotation = 0; picture2.Height = picture.Height; picture2.Width = picture.Width; picture2.VerticalPosition = picture.VerticalPosition; picture2.HorizontalPosition = picture.HorizontalPosition; //foreach (IWSection section in document.Sections) //{ IWSection section = document.Sections[0]; if (section.PageSetup.DifferentFirstPage == true) { WParagraph FirstfooterPar = new WParagraph(document); FirstfooterPar.ChildEntities.Add(picture); if (section.HeadersFooters.FirstPageFooter.Paragraphs.Count > 0) { section.HeadersFooters.FirstPageFooter.Paragraphs.RemoveAt(section.HeadersFooters.FirstPageFooter.Paragraphs.Count - 1); } section.HeadersFooters.FirstPageFooter.Paragraphs.Add(FirstfooterPar); } WParagraph footerPar = new WParagraph(document); footerPar.ChildEntities.Add(picture2); if (section.HeadersFooters.Footer.Count > 0) { section.HeadersFooters.Footer.Paragraphs.RemoveAt(section.HeadersFooters.Footer.Paragraphs.Count - 1); } section.HeadersFooters.Footer.Paragraphs.Add(footerPar); } private void Insert_CLMField(CLMDocItem item, ref WordDocument document) { 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.ToString().ToUpper() == item.field.ToString().ToUpper() || formField.Name.ToString().ToUpper() == item.bmstart.ToString().ToUpper()) { formField.Text = item.itemvalue; break; } } } } private void Insert_CLMTable(CLMDocItem item, ref WordDocument document) { string tablestyle = ""; List cellwidth = null; List cellpadding = null; List headers = null; List stringList = null; string s = ""; DataTable dt = (DataTable)JsonConvert.DeserializeObject(item.itemvalue, (typeof(DataTable))); try { dynamic myObject = JValue.Parse(item.format); foreach (dynamic formats in myObject) { if (formats.Tag == "TableStyle") { tablestyle = formats.Value; } if (formats.Tag == "CellWidth") { s = formats.Value.ToString(); cellwidth = s.Split(';').ToList(); } if (formats.Tag == "CellPadding") { s = formats.Value.ToString(); cellpadding = s.Split(';').ToList(); } if (formats.Tag == "Headers") { s = formats.Value.ToString(); headers = s.Split(';').ToList(); } //Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString()); } } catch { } if (cellpadding.Count == 0) { cellpadding.Add("0"); cellpadding.Add("0"); cellpadding.Add("0"); cellpadding.Add("0"); } if (cellwidth.Count == 0) { for (int i1 = 0; i1 < dt.Columns.Count; i1++) { cellwidth.Add("0"); } } int maxwith = 0; foreach (string w in cellwidth) { maxwith = maxwith + Convert.ToInt32(w); } string bm = item.field.ToString(); if (bm == "") { bm = item.bmstart.ToString(); } BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.MoveToBookmark(bm); //Bookmark bookmark = document.Bookmarks.FindByName(bm); //WSection section = GetOwnerEntity(bookmark.BookmarkStart) as WSection; IWTable table = new WTable(document); //IWTable table = section.AddTable(); if (headers.Count > 0 && headers.Count == dt.Columns.Count) { DataRow dr = dt.NewRow(); for (int i = 0; i < headers.Count; i++) { dr[i] = headers[i]; } dt.Rows.InsertAt(dr, 0); dt.AcceptChanges(); } table.ResetCells(dt.Rows.Count, dt.Columns.Count); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table[i, j].AddParagraph().AppendText(dt.Rows[i][dt.Columns[j]].ToString()); WTableCell cell = table.Rows[i].Cells[j]; try { if (cellpadding.Count > 0) { cell.CellFormat.SamePaddingsAsTable = false; cell.CellFormat.Paddings.Left = Convert.ToInt32(cellpadding[0]); //in terms of points cell.CellFormat.Paddings.Right = Convert.ToInt32(cellpadding[1]); //in terms of points cell.CellFormat.Paddings.Top = Convert.ToInt32(cellpadding[2]); //in terms of points cell.CellFormat.Paddings.Bottom = Convert.ToInt32(cellpadding[3]); //in terms of points } } catch { } try { int wi = Convert.ToInt32(cellwidth[j]); if (wi > 0) { cell.Width = wi; } else { { cell.Width = table.Width - maxwith; } } } catch { } //This line Defines whether to use same paddings as table has. //cell.CellFormat.SamePaddingsAsTable = false; //cell.CellFormat.Paddings.Left =0; //in terms of points //cell.CellFormat.Paddings.Right = 0;//in terms of points //cell.CellFormat.Paddings.Top = 0;//in terms of points //cell.CellFormat.Paddings.Bottom = 15f;//in terms of points // if (j==0) { cell.Width = 150; } else { cell.Width = table.Width - 150; } } } try { if (tablestyle == "None" || tablestyle == "") { table.ApplyStyle(BuiltinTableStyle.LightShading); //Enables special formatting for banded columns of the table. table.ApplyStyleForBandedColumns = false; //Enables special formatting for banded rows of the table. table.ApplyStyleForBandedRows = false; //Disables special formatting for first column of the table. table.ApplyStyleForFirstColumn = false; //Enables special formatting for header row of the table. table.ApplyStyleForHeaderRow = false; //Enables special formatting for last column of the table. table.ApplyStyleForLastColumn = false; //Disables special formatting for last row of the table. table.ApplyStyleForLastRow = false; table.TableFormat.Borders.BorderType = BorderStyle.None; } if (tablestyle == "default") { } //tablestyle = "LightShadingAccent1"; if (Enum.IsDefined(typeof(BuiltinTableStyle), tablestyle)) { ApplyBuiltInTableStyleFromIStyle(ref table, tablestyle); } } catch { } bookmarkNavigator.InsertTable(table); //bookmark = null; //section = null; table = null; cellwidth = null; cellpadding = null; headers = null; stringList = null; } private void ApplyBuiltInTableStyleFromIStyle(ref IWTable table, string style) { if (style == null || string.IsNullOrEmpty(style)) return; switch (style) { case "None": //table.ApplyStyle(BuiltinTableStyle.None); break; case "TableNormal": table.ApplyStyle(BuiltinTableStyle.TableNormal); break; case "TableGrid": table.ApplyStyle(BuiltinTableStyle.TableGrid); break; // Light Shading case "LightShading": table.ApplyStyle(BuiltinTableStyle.LightShading); break; case "LightShadingAccent1": table.ApplyStyle(BuiltinTableStyle.LightShadingAccent1); break; case "LightShadingAccent2": table.ApplyStyle(BuiltinTableStyle.LightShadingAccent2); break; case "LightShadingAccent3": table.ApplyStyle(BuiltinTableStyle.LightShadingAccent3); break; case "LightShadingAccent4": table.ApplyStyle(BuiltinTableStyle.LightShadingAccent4); break; case "LightShadingAccent5": table.ApplyStyle(BuiltinTableStyle.LightShadingAccent5); break; case "LightShadingAccent6": table.ApplyStyle(BuiltinTableStyle.LightShadingAccent6); break; // Light Grid case "LightGrid": table.ApplyStyle(BuiltinTableStyle.LightGrid); break; case "LightGridAccent1": table.ApplyStyle(BuiltinTableStyle.LightGridAccent1); break; case "LightGridAccent2": table.ApplyStyle(BuiltinTableStyle.LightGridAccent2); break; case "LightGridAccent3": table.ApplyStyle(BuiltinTableStyle.LightGridAccent3); break; case "LightGridAccent4": table.ApplyStyle(BuiltinTableStyle.LightGridAccent4); break; case "LightGridAccent5": table.ApplyStyle(BuiltinTableStyle.LightGridAccent5); break; case "LightGridAccent6": table.ApplyStyle(BuiltinTableStyle.LightGridAccent6); break; // Medium Shading case "MediumShading1": table.ApplyStyle(BuiltinTableStyle.MediumShading1); break; case "MediumShading1Accent1": table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent1); break; case "MediumShading1Accent2": table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent2); break; case "MediumShading1Accent3": table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent3); break; case "MediumShading1Accent4": table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent4); break; case "MediumShading1Accent5": table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5); break; case "MediumShading1Accent6": table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent6); break; // Medium Grid case "MediumGrid1": table.ApplyStyle(BuiltinTableStyle.MediumGrid1); break; case "MediumGrid1Accent1": table.ApplyStyle(BuiltinTableStyle.MediumGrid1Accent1); break; case "MediumGrid1Accent2": table.ApplyStyle(BuiltinTableStyle.MediumGrid1Accent2); break; case "MediumGrid1Accent3": table.ApplyStyle(BuiltinTableStyle.MediumGrid1Accent3); break; case "MediumGrid1Accent4": table.ApplyStyle(BuiltinTableStyle.MediumGrid1Accent4); break; case "MediumGrid1Accent5": table.ApplyStyle(BuiltinTableStyle.MediumGrid1Accent5); break; case "MediumGrid1Accent6": table.ApplyStyle(BuiltinTableStyle.MediumGrid1Accent6); break; // Medium List case "MediumList1": table.ApplyStyle(BuiltinTableStyle.MediumList1); break; case "MediumList1Accent1": table.ApplyStyle(BuiltinTableStyle.MediumList1Accent1); break; case "MediumList1Accent2": table.ApplyStyle(BuiltinTableStyle.MediumList1Accent2); break; case "MediumList1Accent3": table.ApplyStyle(BuiltinTableStyle.MediumList1Accent3); break; case "MediumList1Accent4": table.ApplyStyle(BuiltinTableStyle.MediumList1Accent4); break; case "MediumList1Accent5": table.ApplyStyle(BuiltinTableStyle.MediumList1Accent5); break; case "MediumList1Accent6": table.ApplyStyle(BuiltinTableStyle.MediumList1Accent6); break; // Dark List case "DarkList": table.ApplyStyle(BuiltinTableStyle.DarkList); break; case "DarkListAccent1": table.ApplyStyle(BuiltinTableStyle.DarkListAccent1); break; case "DarkListAccent2": table.ApplyStyle(BuiltinTableStyle.DarkListAccent2); break; case "DarkListAccent3": table.ApplyStyle(BuiltinTableStyle.DarkListAccent3); break; case "DarkListAccent4": table.ApplyStyle(BuiltinTableStyle.DarkListAccent4); break; case "DarkListAccent5": table.ApplyStyle(BuiltinTableStyle.DarkListAccent5); break; case "DarkListAccent6": table.ApplyStyle(BuiltinTableStyle.DarkListAccent6); break; // Colorful Grid case "ColorfulGrid": table.ApplyStyle(BuiltinTableStyle.ColorfulGrid); break; case "ColorfulGridAccent1": table.ApplyStyle(BuiltinTableStyle.ColorfulGridAccent1); break; case "ColorfulGridAccent2": table.ApplyStyle(BuiltinTableStyle.ColorfulGridAccent2); break; case "ColorfulGridAccent3": table.ApplyStyle(BuiltinTableStyle.ColorfulGridAccent3); break; case "ColorfulGridAccent4": table.ApplyStyle(BuiltinTableStyle.ColorfulGridAccent4); break; case "ColorfulGridAccent5": table.ApplyStyle(BuiltinTableStyle.ColorfulGridAccent5); break; case "ColorfulGridAccent6": table.ApplyStyle(BuiltinTableStyle.ColorfulGridAccent6); break; default: // Custom table style fallback //table.ApplyStyle(style.Name); break; } } public Bitmap Resize(System.Drawing.Image image, int width, int height, bool keepAspectRatio, bool enlargeSmallerImages) { if (!enlargeSmallerImages && image.Width <= width && image.Height <= height) { return new Bitmap(image); } if (!keepAspectRatio) { return new Bitmap(image, width, height); } int originalWidth = image.Width; int originalHeight = image.Height; int newWidth = 0; int newHeight = 0; double aspectRatio = (double)originalWidth / originalHeight; if (width > 0) { newWidth = width; newHeight = (int)Math.Round(width / aspectRatio); } else { newHeight = height; newWidth = (int)Math.Round(height * aspectRatio); } return new Bitmap(image, newWidth, newHeight); } public System.Drawing.Image Resize1(System.Drawing.Image src, string outputPath, int maxWidth, int maxHeight) { double ratio = 0; int width = 0; int height = 0; if (maxHeight == 0) { ratio = (double)maxWidth / src.Width; width = maxWidth; height = (int)(src.Height * ratio); } else { ratio = (double)maxHeight / src.Height; height = maxHeight; width = (int)(src.Width * ratio); } var dest = new Bitmap(width, height); dest.SetResolution( src.HorizontalResolution, src.VerticalResolution); using (var g = Graphics.FromImage(dest)) { g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrap = new ImageAttributes()) { wrap.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); g.DrawImage( src, new Rectangle(0, 0, width, height), 0, 0, src.Width, src.Height, GraphicsUnit.Pixel, wrap); } return dest;// bmp.Save(outputPath, jpgEncoder, encParams); } } private void Insert_CLMImages(CLMDocItem item, ref WordDocument document, Boolean inline = false) { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); try { bookmarkNavigator.MoveToBookmark(item.bmstart); } catch { bookmarkNavigator.MoveToBookmark(item.field); } bookmarkNavigator.DeleteBookmarkContent(true); IWParagraph paragraph = new WParagraph(document); DataTable dt = new DataTable(); try { dt = (DataTable)JsonConvert.DeserializeObject(item.itemvalue, (typeof(DataTable))); foreach (DataRow dr in dt.Rows) { MemoryStream mssign = new MemoryStream(Convert.FromBase64String(dr[0].ToString())); System.Drawing.Image img = System.Drawing.Image.FromStream(mssign); if (Convert.ToInt32(item.width) != 0 || Convert.ToInt32(item.height) != 0) { // img = Resize(img, Convert.ToInt32(item.width), Convert.ToInt32(item.width)), true, true); img = Resize1(img, "", Convert.ToInt32(item.width), Convert.ToInt32(item.height)); } paragraph.AppendPicture(img); mssign = null; img = null; } bookmarkNavigator.InsertParagraph(paragraph); paragraph = null; bookmarkNavigator = null; dt = null; } catch (Exception ex) { string s= ex.Message; } } private void Insert_CLMImage(CLMDocItem item, ref WordDocument document, Boolean inline = false, Boolean multiimages = false) { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); Syncfusion.DocIO.DLS.Bookmark bm = document.Bookmarks[item.bmstart]; if (bm is null) { bm = document.Bookmarks[item.field]; } MemoryStream mssign = new MemoryStream(Convert.FromBase64String(item.itemvalue)); System.Drawing.Image img = System.Drawing.Image.FromStream(mssign); System.Drawing.Image img1 = Resize(img, Convert.ToInt32(item.width), Convert.ToInt32(item.height), true, true); int itop = Convert.ToInt32(item.top) * -1; int top = Convert.ToInt32(Convert.ToInt32(itop) + Convert.ToInt32(img1.Height)); top = Convert.ToInt32(Convert.ToInt32(itop)); int height = Convert.ToInt32(Convert.ToInt32(img1.Height)); int left = Convert.ToInt32(Convert.ToInt32(item.left)); int width = Convert.ToInt32(Convert.ToInt32(img1.Width)); Shape signature = bm.BookmarkStart.OwnerParagraph.AppendShape(Syncfusion.DocIO.DLS.AutoShapeType.Rectangle, Convert.ToInt32(img1.Width), Convert.ToInt32(img1.Height)); signature.TextFrame.InternalMargin.Top = 0; signature.TextFrame.InternalMargin.Left = 0; signature.TextFrame.InternalMargin.Bottom = 0; signature.TextFrame.InternalMargin.Right = 0; //IWParagraph p = bm.BookmarkStart.OwnerParagraph; //IWPicture u = p.AppendPicture(img); IWParagraph sigparagraph = signature.TextBody.AddParagraph(); signature.WrapFormat.TextWrappingStyle = TextWrappingStyle.Behind; signature.LineFormat.DashStyle = LineDashing.Solid; signature.LineFormat.Color = Color.White; signature.WrapFormat.AllowOverlap = true; signature.WrapFormat.TextWrappingStyle = TextWrappingStyle.Behind; signature.HorizontalPosition = signature.HorizontalPosition + left; signature.VerticalPosition = signature.VerticalPosition - top; IWPicture p = sigparagraph.AppendPicture(img); p.Width = Convert.ToInt32(img1.Width); p.Height = Convert.ToInt32(img1.Height); ; //signature.Name = "Unterschrift_" + bookmark; img = null; img1 = null; bm = null; mssign = null; signature = null; } private void insert_signature(string bookmark, string unterschrift, ref WordDocument document) { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); Syncfusion.DocIO.DLS.Bookmark bm = document.Bookmarks[bookmark]; MemoryStream mssign = new MemoryStream(Convert.FromBase64String(unterschrift)); System.Drawing.Image img = System.Drawing.Image.FromStream(mssign); Shape signature = bm.BookmarkStart.OwnerParagraph.AppendShape(Syncfusion.DocIO.DLS.AutoShapeType.Rectangle, 124, 52); signature.TextFrame.InternalMargin.Top = 0; signature.TextFrame.InternalMargin.Left = 0; signature.TextFrame.InternalMargin.Bottom = 0; signature.TextFrame.InternalMargin.Right = 0; //IWParagraph p = bm.BookmarkStart.OwnerParagraph; //IWPicture u = p.AppendPicture(img); IWParagraph sigparagraph = signature.TextBody.AddParagraph(); signature.WrapFormat.TextWrappingStyle = TextWrappingStyle.Behind; signature.LineFormat.DashStyle = LineDashing.Solid; signature.LineFormat.Color = Color.White; signature.WrapFormat.AllowOverlap = true; signature.VerticalPosition = signature.VerticalPosition - 51; signature.WrapFormat.TextWrappingStyle = TextWrappingStyle.Behind; //signature.HorizontalPosition = signature.HorizontalPosition + 200; IWPicture p = sigparagraph.AppendPicture(img); p.Width = 120; p.Height = 50; signature.Name = "Unterschrift_" + bookmark; // signature.OwnerParagraph.AppendPicture(img); mssign = null; } void InsertBookmark(WordDocument document, WParagraph paragraph, string name) { BookmarkStart bookmarkStart = new BookmarkStart(document, name); BookmarkEnd bookmarkEnd = new BookmarkEnd(document, name); paragraph.ChildEntities.Insert(0, bookmarkStart); paragraph.ChildEntities.Add(bookmarkEnd); } void AddBookmarkToHeaderFooter(WordDocument document, HeaderFooter headerFooter, string bookmarkName) { int bookmarkIndex = 1; // Counter to ensure unique bookmark names if (headerFooter.ChildEntities.Count > 0) { foreach (Entity childEntity in headerFooter.ChildEntities) { if (childEntity is WParagraph paragraph && paragraph.ChildEntities.Count > 0) { InsertBookmark(document, paragraph, bookmarkName + bookmarkIndex); bookmarkIndex++; } else if (childEntity is WTable table) { foreach (WTableRow row in table.Rows) { foreach (WTableCell cell in row.Cells) { foreach (Entity cellEntity in cell.ChildEntities) { if (cellEntity is WParagraph cellParagraph && cellParagraph.ChildEntities.Count > 0) { InsertBookmark(document, cellParagraph, bookmarkName + bookmarkIndex); bookmarkIndex++; } } } } } } } } public string Generate_Word(string base64, clsDocData docdata, string img_UL = "", string img_UR = "", string img_faktura = "", bool serienbrief = false, bool editdoc = false) { string formattype = ""; MemoryStream ms = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(base64)); WordDocument document = new WordDocument(ms, FormatType.Automatic); CompatibilityMode compatibilityMode = document.Settings.CompatibilityMode; set_compatibilitymode(ref document, docdata.CompatibilityMode); Logging.Logging.Debug(compatibilityMode.ToString(), "ondoc sf", docdata.Dokumentid); //switch (compatibilityMode) //{ // case CompatibilityMode.Word2003: // document.Settings.CompatibilityMode = CompatibilityMode.Word2010; // break; // case CompatibilityMode.Word2010: // document.Settings.CompatibilityMode = CompatibilityMode.Word2010; // break; // case CompatibilityMode.Word2013: // document.Settings.CompatibilityMode = CompatibilityMode.Word2013; // break; // default: // //document.Settings.CompatibilityMode = CompatibilityMode.Word2003; // break; //} //if (docdata.CompatibilityMode !="" && docdata.CompatibilityMode != "Standard") //{ // if (docdata.CompatibilityMode=="Word 2013") // { // document.Settings.CompatibilityMode = CompatibilityMode.Word2013; // Logging.Logging.Debug("Übersteuerung CompatibilityMode: neu" + docdata.CompatibilityMode, "ondoc", ""); // } // if (docdata.CompatibilityMode == "Word 2010") // { // document.Settings.CompatibilityMode = CompatibilityMode.Word2010; // Logging.Logging.Debug("Übersteuerung CompatibilityMode: neu" + docdata.CompatibilityMode, "ondoc", ""); // } //} //if (compatibilityMode == CompatibilityMode.Word2010) { document.Settings.CompatibilityMode = CompatibilityMode.Word2010; } //if (compatibilityMode > CompatibilityMode.Word2010) { document.Settings.CompatibilityMode = CompatibilityMode.Word2013; } formattype = document.ActualFormatType.ToString(); var formattype_original = document.ActualFormatType; string ppimg = ""; string ppimg64 = ""; if (docdata.Barcode == true) { //20250531 - Barcode nicht beim Serienbrief if (!serienbrief) Insert_Barcode(document, docdata); } if (docdata.PrintLogo == true) { insert_Logo(document, docdata); } if (docdata.Kopfzeile_generieren)// == true && editdoc==false) { try { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.MoveToBookmark("TGEDKCompanyBBEB99"); IWParagraph paragraph = new WParagraph(document); paragraph.AppendBreak(BreakType.LineBreak); } catch { foreach (WSection section in document.Sections) { IWParagraph p; try { p = section.HeadersFooters.FirstPageHeader.Paragraphs[section.HeadersFooters.FirstPageHeader.Paragraphs.Count - 1]; } catch { p = section.HeadersFooters.FirstPageHeader.AddParagraph(); } BookmarkStart bookmarkStart = new BookmarkStart(document, "TGEDKCompanyBBEB99"); BookmarkEnd bookmarkEnd = new BookmarkEnd(document, "TGEDKCompanyBBEB99"); //p.ChildEntities.Insert(2, bookmarkStart); p.ChildEntities.Add(bookmarkStart); p.ChildEntities.Add(bookmarkEnd); //foreach (clsDocValue dv in docdata.DocValues) //{ // if (dv.TMBeginn.ToString() == "TGEDKCompanyBBEB99") // { // p.AppendText(dv.Value); // } //} //p.AppendBookmarkStart("TGEDKCompanyBBEB99"); //p.AppendBreak(BreakType.LineBreak); } } } //if (img_faktura != "") //{ // insert_ppfaktura(document, img_faktura); //} //List shapes = document.FindAllItemsByProperty(EntityType.Shape, null, null); //for (int i = 0; i < shapes.Count; i++) //{ // Shape sh = shapes[i] as Shape; // if (sh.Name.Contains("Unterschrift_")){ // int i1 = sh.OwnerParagraph.ChildEntities.Count; // } //} foreach (clsDocValue dv in docdata.DocValues) { //break; if (dv.TMBeginn.ToString().Contains("VornameName")) { int a = 1; } //if (dv.TMBeginn.ToString().Contains("TGEDKCursor")) { //break; } //if (dv.FieldName.ToString().Contains("TGEDKCursor")) { //break; } if (docdata.Form_ohne_Unterschrift == "True") { foreach (clsDocValue dv2 in docdata.DocValues) { if (dv2.TMBeginn.ToString().Contains("VornameNameLinks")) { dv2.Value = ""; } if (dv2.TMBeginn.ToString().Contains("VornameNameRechts")) { dv2.Value = ""; } if (dv2.TMBeginn.ToString().Contains("TGEDKFunktionLinks")) { dv2.Value = ""; } if (dv2.TMBeginn.ToString().Contains("FunktionRechts")) { dv2.Value = ""; } //if (dv2.TMBeginn.ToString() == "TGEDKVornameNameLinksB99") { dv2.Value = ""; } //if (dv2.TMBeginn.ToString() == "TGEDKVornameNameRechtsB99") { dv2.Value = ""; } //if (dv2.TMBeginn.ToString() == "TGEDKFunktionLinksB99") { dv2.Value = ""; } //if (dv2.TMBeginn.ToString() == "TGEDKFunktionRechtsB99") { dv2.Value = ""; } } } if (dv.TMBeginn.ToString() == "TGEDKTagesdatumB99" || dv.TMBeginn.ToString().Contains("Inhaber")) { int a = 1; } 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") if ((dv.TMBeginn.ToString().Contains("VornameNameLinks") || dv.TMBeginn.ToString().Contains("VornameNameRechts")) && docdata.As_Faksimile == "True" && (docdata.sign == true || serienbrief == true)) { if (dv.TMBeginn.ToString().Contains("VornameNameLinks")) { string unterschrift = ""; if (img_UL != "") { unterschrift = img_UL.ToString(); } else { if (docdata.APICall == true) { if (docdata.img_unterschrift_links != "") { unterschrift = docdata.img_unterschrift_links; } } else { unterschrift = Newtonsoft.Json.JsonConvert.DeserializeObject(get_unterschrift(docdata.Unterschrift_Links)); } } bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); bookmarkNavigator.ReplaceBookmarkContent(dv.Value.ToString(), true); if (docdata.Unterschrift_Links != "-1") { insert_signature(dv.TMBeginn.ToLower(), unterschrift, ref document); } } if (dv.TMBeginn.ToString().Contains("VornameNameRechts")) { string unterschrift = ""; if (img_UR != "") { unterschrift = img_UR.ToString(); } else { if (docdata.APICall == true) { if (docdata.img_unterschrift_rechts != "") { unterschrift = docdata.img_unterschrift_rechts; } } else { unterschrift = Newtonsoft.Json.JsonConvert.DeserializeObject(get_unterschrift(docdata.Unterschrift_Rechts)); } } bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); bookmarkNavigator.ReplaceBookmarkContent(dv.Value.ToString(), true); if (docdata.Unterschrift_Rechts != "-1") { insert_signature(dv.TMBeginn.ToLower(), unterschrift, ref document); } } } else { if (dv.TMBeginn.ToString() == "TGEDKZustellungB99") { if (img_faktura != "") { insert_ppfaktura(document, img_faktura); bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); bookmarkNavigator.InsertText(dv.Value.ToString()); //bookmarkNavigator.ReplaceBookmarkContent(dv.Value.ToString(), true); } else { if (!dv.TMBeginn.ToString().Contains("TGEDKCursor")) { if (dv.TMBeginn.ToString().Contains("VornameName")) { int a = 1; } bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); //bookmarkNavigator.InsertText(dv.Value.ToString()); bookmarkNavigator.ReplaceBookmarkContent(dv.Value.ToString(), true); } } } else { if (!dv.TMBeginn.ToString().Contains("TGEDKCursor")) { if (dv.TMBeginn.ToString().Contains("VornameName")) { int a = 1; } bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString()); //bookmarkNavigator.InsertText(dv.Value.ToString()); bookmarkNavigator.ReplaceBookmarkContent(dv.Value.ToString(), true); } } //} } } catch { } } if (dv.TMBeginn.ToString() != "" && dv.TMEnd.ToString() != "") { try { if (!dv.TMBeginn.ToString().Contains("TGEDKCursor")) { ReplaceBookmarkContent(ref document, dv.TMBeginn.ToString(), dv.TMEnd.ToString(), dv.Value.ToString(), serienbrief); } } catch { } } if (dv.FieldName.ToString() != "") { if (dv.FieldName.ToString().Substring(0, 2) == "$$") { Replace_Text(ref document, dv.FieldName.ToString(), dv.Value.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() && !dv.FieldName.ToString().Contains("TGEDKCursor")) { formField.Text = dv.Value.ToString(); break; } } } } catch { } } } try { foreach (attribute apivalue in docdata.APIValues) { try { if (apivalue.Type == "Checkbox") { CheckboxCount = 0; CheckboxNr = Convert.ToInt32(apivalue.Value); foreach (WSection section in document.Sections) { //Accesses the Body of section where all the contents in document are apart WTextBody sectionBody = section.Body; IterateTextBody(sectionBody); } } if (apivalue.Type == "Absatz") { if (apivalue.Value != "Ja") { apivalue.Value = ""; BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.MoveToBookmark(apivalue.Tag); bookmarkNavigator.ReplaceBookmarkContent(apivalue.Value, true); Bookmark bookmark = document.Bookmarks.FindByName(apivalue.Tag + "Inhalt"); document.Bookmarks.Remove(bookmark); } } else { if (apivalue.Value.Contains("")) { string leftpart = apivalue.Value.Substring(0, apivalue.Value.IndexOf("")); string rightparr = apivalue.Value.Substring(apivalue.Value.IndexOf(""), apivalue.Value.Length - apivalue.Value.IndexOf("") - 4); string middle = apivalue.Value.Substring(apivalue.Value.IndexOf("") + 3, apivalue.Value.IndexOf("") - apivalue.Value.IndexOf("") - 3); BookmarksNavigator bn = new BookmarksNavigator(document); bn.MoveToBookmark(apivalue.Tag); apivalue.Value = apivalue.Value.Replace("", ""); apivalue.Value = apivalue.Value.Replace("", ""); bn.ReplaceBookmarkContent(apivalue.Value, true); TextSelection textSelection = document.Find(middle, false, true); WTextRange text = textSelection.GetAsOneRange(); text.CharacterFormat.Italic = true; } else { // WTextRange text = textSelection.GetAsOneRange(); //apivalue.Value = apivalue.Value & char(11) & "Hallo"; BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.MoveToBookmark(apivalue.Tag); bookmarkNavigator.ReplaceBookmarkContent(apivalue.Value, true); } } } catch { } } } catch { } try { foreach (CLMDocItem item in docdata.CLMDocItems) { if (item.itemvalue.ToString() != "" && item.type != null) { Insert_CLMValue(item, ref document); //BookmarkCollection bookmarks = document.Bookmarks; //foreach (Bookmark bm in bookmarks) //{ // if (bm.Name.ToUpper() == item.field.ToString().ToUpper() || bm.Name.ToUpper() == item.bmstart.ToString().ToUpper()) // { // Insert_CLMValue(item, bm.Name, ref document); // } //} } } } catch { } //gaga //if (docdata.As_Faksimile == "True" && serienbrief==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 { } // } // } // } //} try { if (docdata.TextToReplace.Count() > 0) { bool locked = false; if (document.ProtectionType != ProtectionType.NoProtection) { document.Protect(ProtectionType.NoProtection, "Australia"); locked = true; } foreach (textreplace tr in docdata.TextToReplace) { Replace_Text(ref document, tr.TextToFind, tr.TextToReplace); } if (locked) { document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); } } } catch { } foreach (clsDocMacro dm in docdata.DocMacros) { switch (dm.Name.ToUpper()) { case "DOKUMENTSCHUETZEN": document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); //document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); break; case "FORMULARAKTUALISIEREN": if (document.ProtectionType != ProtectionType.NoProtection) { document.Protect(ProtectionType.NoProtection, "Australia"); try { document.UpdateDocumentFields(); } catch { } try { document.UpdateFields = true; } catch { } document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); } else { try { document.UpdateDocumentFields(); } catch { } try { document.UpdateFields = true; } catch { } } break; default: break; } if (dm.BookMark != "") { string variable = ""; string inhalt = ""; if (dm.BookMark.Contains(":")) { string phrase = dm.BookMark; string[] parts = phrase.Split(':'); variable = parts[0]; inhalt = parts[1]; } else { } if (document.ProtectionType == ProtectionType.NoProtection) { if (variable != "") { try { document.Variables.Add(variable, inhalt); } catch { } } if (variable == "") { 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(1, bookmarkEnd); } } else { document.Protect(ProtectionType.NoProtection, "Australia"); if (variable != "") { try { document.Variables.Add(variable, inhalt); } catch { } } if (variable == "") { 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(1, bookmarkEnd); } document.Protect(ProtectionType.AllowOnlyFormFields, "Australia"); } } } try { set_font_bold(ref document); } catch { } //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") { DB dB = new DB(); DocGet getdoc = new DocGet(""); string destdoc = ""; destdoc = getdoc.Convert_Word_To_PDF(Convert.ToBase64String(imageArray)); return destdoc; } return Convert.ToBase64String(imageArray); } private static int CheckboxNr = 0; private static int CheckboxCount = 0; private static void IterateTextBody(WTextBody textBody) { //Iterates through each of the child items of WTextBody for (int i = 0; i < textBody.ChildEntities.Count; i++) { //IEntity is the basic unit in DocIO DOM. //Accesses the body items (should be either paragraph, table or block content control) as IEntity IEntity bodyItemEntity = textBody.ChildEntities[i]; //A Text body has 3 types of elements - Paragraph, Table and Block Content Control //Decides the element type by using EntityType switch (bodyItemEntity.EntityType) { case EntityType.Paragraph: WParagraph paragraph = bodyItemEntity as WParagraph; //Processes the paragraph contents //Iterates through the paragraph's DOM IterateParagraph(paragraph.Items); break; case EntityType.Table: //Table is a collection of rows and cells //Iterates through table's DOM IterateTable(bodyItemEntity as WTable); break; case EntityType.BlockContentControl: BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl; //Iterates to the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody); break; } } } private static void IterateTable(WTable table) { //Iterates the row collection in a table foreach (WTableRow row in table.Rows) { //Iterates the cell collection in a table row foreach (WTableCell cell in row.Cells) { //Table cell is derived from (also a) TextBody //Reusing the code meant for iterating TextBody IterateTextBody(cell); } } } private static void IterateParagraph(ParagraphItemCollection paraItems) { for (int i = 0; i < paraItems.Count; i++) { Entity entity = paraItems[i]; //A paragraph can have child elements such as text, image, hyperlink, symbols, etc., //Decides the element type by using EntityType if (entity is WCheckBox) { WCheckBox checkbox = entity as WCheckBox; //Modifies check box properties CheckboxCount = CheckboxCount + 1; if (CheckboxCount == CheckboxNr) { checkbox.Checked = true; //checkbox.SizeType = CheckBoxSizeType.Exactly; } //if (!checkbox.Checked) // checkbox.Checked = true; //checkbox.SizeType = CheckBoxSizeType.Exactly; } } } public static void set_list(ref WordDocument document) { Regex regex = new Regex("
    (.*?)
"); } public static void set_font_bold(ref WordDocument document) { Regex regex = new Regex("(.*?)"); // Find all matches of the regex pattern in the document. TextSelection[] matches = document.FindAll(regex); // Iterate through each match found in the document. foreach (TextSelection match in matches) { // Get the entire text range of the matched content. WTextRange textRange = match.GetAsOneRange(); // Extract the full text of the match. string fullText = textRange.Text; // Define the length of the opening tag . int startTagLength = "".Length; // Find the index of the closing tag . int endTagIndex = fullText.LastIndexOf(""); // Extract the opening tag, bold text, and closing tag as separate strings. string startTag = fullText.Substring(0, startTagLength); string boldText = fullText.Substring(startTagLength, endTagIndex - startTagLength); string endTag = fullText.Substring(endTagIndex); // Create new text ranges for each part (opening tag, bold text, and closing tag). WTextRange startTextRange = CreateTextRange(textRange, startTag); WTextRange boldTextRange = CreateTextRange(textRange, boldText); WTextRange endTextRange = CreateTextRange(textRange, endTag); // Apply bold formatting to the text range containing the bold text. boldTextRange.CharacterFormat.Bold = true; // Replace the original text range with the newly created text ranges in the paragraph. WParagraph paragraph = textRange.OwnerParagraph; // Get the index of the original text range within the paragraph. int index = paragraph.ChildEntities.IndexOf(textRange); // Remove the original text range from the paragraph. paragraph.ChildEntities.RemoveAt(index); // Insert the new text ranges (in order: closing tag, bold text, opening tag) into the paragraph. // paragraph.ChildEntities.Insert(index, endTextRange); paragraph.ChildEntities.Insert(index, boldTextRange); //paragraph.ChildEntities.Insert(index, startTextRange); } } static WTextRange CreateTextRange(WTextRange original, string text) { // Clone the original text range to preserve its formatting. WTextRange newTextRange = original.Clone() as WTextRange; // Set the text for the new text range. newTextRange.Text = text; return newTextRange; } 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, bool serienbrief) { if (serienbrief) { BookmarksNavigator bmn = new BookmarksNavigator(document); bmn.MoveToBookmark(bookmark1); bmn.InsertText(replacementContent + " "); return; } //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. //BookmarksNavigator bmn = new BookmarksNavigator(document); //bmn.MoveToBookmark(bookmark1); //TextBodyPart tbp = bmn.GetBookmarkContent(); ////SHU //string bookmarkText = ((Syncfusion.DocIO.DLS.WParagraph)tbp.BodyItems.FirstItem).Text; //if (bookmarkText.Trim() == "" || bookmarkText.Trim()!=replacementContent.Trim()) { bmn.InsertText(replacementContent); return; } 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_ppfaktura(WordDocument document, string ppfakturaimage) { BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); //bookmarkNavigator.MoveToBookmark("TGEDKAdresseZustellungB99"); bookmarkNavigator.MoveToBookmark("TGEDKZustellungB99"); string img = ppfakturaimage; byte[] b = Convert.FromBase64String(ppfakturaimage); MemoryStream mssign = new MemoryStream(b); System.Drawing.Image image = System.Drawing.Image.FromStream(mssign); IWParagraph paragraph = new WParagraph(document); paragraph.AppendPicture(image); //paragraph.AppendText(zustellungvalue); bookmarkNavigator.InsertParagraph(paragraph); } private static System.Drawing.Image ResizeImage(System.Drawing.Image imgToResize, Size size) { // Get the image current width int sourceWidth = imgToResize.Width; // Get the image current height int sourceHeight = imgToResize.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; // Calculate width and height with new desired size nPercentW = ((float)size.Width / (float)sourceWidth); nPercentH = ((float)size.Height / (float)sourceHeight); nPercent = Math.Min(nPercentW, nPercentH); // New Width and Height int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((System.Drawing.Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; // Draw image with new width and height g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return (System.Drawing.Image)b; } public System.Drawing.Image AutoSizeImage(System.Drawing.Image oBitmap, int maxWidth, int maxHeight, bool bStretch = false) { // Größenverhältnis der max. Dimension float maxRatio = (float)(maxWidth / (double)maxHeight); // Bildgröße und aktuelles Größenverhältnis int imgWidth = oBitmap.Width; int imgHeight = oBitmap.Height; float imgRatio = (float)(imgWidth / (double)imgHeight); // Bild anpassen? if (imgWidth > maxWidth | imgHeight > maxHeight | bStretch) { if (imgRatio <= maxRatio) { // Größenverhältnis des Bildes ist kleiner als die // maximale Größe, in der das Bild angezeigt werden kann. // In diesem Fall muss die Bildbreite angepasst werden. imgWidth = (int)Math.Round(imgWidth / (imgHeight / (double)maxHeight)); imgHeight = maxHeight; } else { // Größenverhältnis des Bildes ist größer als die // maximale Größe, in der das Bild angezeigt werden kann. // In diesem Fall muss die Bildhöhe angepasst werden. imgHeight = (int)Math.Round(imgHeight / (imgWidth / (double)maxWidth)); imgWidth = maxWidth; } // Bitmap-Objekt in der neuen Größe erstellen var oImage = new Bitmap(imgWidth, imgHeight); // Bild interpolieren, damit die Qualität erhalten bleibt using (Graphics g = Graphics.FromImage(oImage)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(oBitmap, new System.Drawing.Rectangle(0, 0, imgWidth, imgHeight)); } // neues Bitmap zurückgeben return oImage; } else { // unverändertes Originalbild zurückgeben return oBitmap; } } public System.Drawing.Image Get_Barcodeimage(clsDocData docData) { System.Drawing.Image barcodeimage; BarcodeLib.Barcode Barcode = new BarcodeLib.Barcode(); switch (docData.barcode_type) { case "0": barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5, docData.Dokumentid.Substring(6, 16), docData.Dokumentid.Substring(6, 16) + docData.barcode_zusatz, docData.barcode_textposition, docData.Zusatz_Font, Convert.ToInt32(docData.Zusatz_FontSize), 0); BarcodeLib.clsBarI25 barbarcode = new BarcodeLib.clsBarI25(); if (docData.barcode_horizontal == 0) { barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 66, 600, 100, docData.barcode_zusatz, "Futur Book", 16, 270); } else { barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 66, 600, 100, docData.barcode_zusatz, "Futur Book", 16, 0); } //barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5C, docData.Dokumentid.Substring(9, 13), docData.Dokumentid.Substring(6, 16) + docData.barcode_zusatz, docData.barcode_textposition, docData.barcode_font, Convert.ToInt32(docData.barcode_fontsize), 0); return barcodeimage; break; case "1": if (docData.barcode_left > 200) { barcodeimage = Barcode.Get_Datamatrix(DataMatrix.net.DmtxScheme.DmtxSchemeAscii, docData.barcode_content, 6, 6, 0, "Left", docData.barcode_text + docData.barcode_zusatz, docData.Zusatz_Font, docData.Zusatz_FontSize); } else { barcodeimage = Barcode.Get_Datamatrix(DataMatrix.net.DmtxScheme.DmtxSchemeAscii, docData.barcode_content, 6, 6, 0, "Right", docData.barcode_text + docData.barcode_zusatz, docData.Zusatz_Font, docData.Zusatz_FontSize); } //barcodeimage = AutoSizeImage(barcodeimage, docData.barcode_width, docData.barcode_height, false); return barcodeimage; break; default: barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5C, docData.Dokumentid.Substring(9, 13), docData.Dokumentid.Substring(6, 16) + docData.barcode_zusatz, docData.barcode_textposition, docData.barcode_font, Convert.ToInt32(docData.barcode_fontsize), 0); return barcodeimage; break; } // System.Drawing.Image barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5C, docData.Dokumentid.Substring(9, 13), docData.Dokumentid.Substring(9, 13), docData.barcode_textposition "Below", "Arial", 6, 0); } public void Insert_Barcode(WordDocument document, clsDocData docData) { System.Drawing.Image barcodeimage; barcodeimage = Get_Barcodeimage(docData); System.Drawing.Image barcodeimage2; barcodeimage2 = barcodeimage; WPicture picture = new WPicture(document); WPicture picture2 = new WPicture(document); picture.LoadImage(barcodeimage); picture2.LoadImage(barcodeimage); picture.VerticalPosition = docData.barcode_left; picture.HorizontalPosition = docData.barcode_top; picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Page; picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Largest; picture2.VerticalPosition = docData.barcode_left; picture2.HorizontalPosition = docData.barcode_top; picture2.HorizontalOrigin = HorizontalOrigin.Page; picture2.VerticalOrigin = VerticalOrigin.Page; picture2.TextWrappingStyle = TextWrappingStyle.Square; picture2.TextWrappingType = TextWrappingType.Largest; if (docData.barcode_horizontal == 0) { picture.Rotation = 0; picture.Height = docData.barcode_height; ; picture.Width = docData.barcode_width; picture.VerticalPosition = docData.barcode_top; ; picture.HorizontalPosition = docData.barcode_left; picture2.Rotation = 0; picture2.Height = docData.barcode_height; ; picture2.Width = docData.barcode_width; picture2.VerticalPosition = docData.barcode_top; ; picture2.HorizontalPosition = docData.barcode_left; } else { picture.Rotation = 0; picture.Height = docData.barcode_height; picture.Width = docData.barcode_width; picture.VerticalPosition = docData.barcode_top; ; picture.HorizontalPosition = docData.barcode_left; picture2.Rotation = 0; picture2.Height = docData.barcode_height; picture2.Width = docData.barcode_width; picture2.VerticalPosition = docData.barcode_top; ; picture2.HorizontalPosition = docData.barcode_left; } if (docData.barcode_type == "0") { } //foreach (IWSection section in document.Sections) //{ IWSection section = document.Sections[0]; if (section.PageSetup.DifferentFirstPage == true) { WParagraph FirstfooterPar = new WParagraph(document); FirstfooterPar.ChildEntities.Add(picture); if (section.HeadersFooters.FirstPageFooter.Paragraphs.Count > 0) { section.HeadersFooters.FirstPageFooter.Paragraphs.RemoveAt(section.HeadersFooters.FirstPageFooter.Paragraphs.Count - 1); } section.HeadersFooters.FirstPageFooter.Paragraphs.Add(FirstfooterPar); } WParagraph footerPar = new WParagraph(document); footerPar.ChildEntities.Add(picture2); if (section.HeadersFooters.Footer.Count > 0) { section.HeadersFooters.Footer.Paragraphs.RemoveAt(section.HeadersFooters.Footer.Paragraphs.Count - 1); } section.HeadersFooters.Footer.Paragraphs.Add(footerPar); //} //for (int i = 0; i < document.Sections.Count; i++) //{ // IWSection section1 = document.Sections[i]; // if (section1.PageSetup.DifferentFirstPage == true) // { // WParagraph FirstfooterPar1 = new WParagraph(document); // FirstfooterPar1.ChildEntities.Add(picture); // if (section1.HeadersFooters.FirstPageFooter.Paragraphs.Count > 0 && editdoc) // { // section1.HeadersFooters.FirstPageFooter.Paragraphs.RemoveAt(section1.HeadersFooters.FirstPageFooter.Paragraphs.Count - 1); // } // section1.HeadersFooters.FirstPageFooter.Paragraphs.Add(FirstfooterPar1); // } // WParagraph footerPar1 = new WParagraph(document); // footerPar1.ChildEntities.Add(picture2); // if (section1.HeadersFooters.Footer.Count > 0 && editdoc) { section1.HeadersFooters.Footer.Paragraphs.RemoveAt(section1.HeadersFooters.Footer.Paragraphs.Count - 1); } // section1.HeadersFooters.Footer.Paragraphs.Add(footerPar1); //} } public void xInsert_Barcode(WordDocument document, clsDocData docData) { System.Drawing.Image barcodeimage; BarcodeLib.Barcode Barcode = new BarcodeLib.Barcode(); switch (docData.barcode_type) { case "0": //int rotation = 0; //if (docData.barcode_horizontal == 0) { rotation = 270; } BarcodeLib.clsBarI25 barbarcode = new BarcodeLib.clsBarI25(); //barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 36, 350, 50, " "+docData.barcode_zusatz, docData.Zusatz_Font, Convert.ToInt32(docData.Zusatz_FontSize), 0); //barcodeimage = AutoSizeImage(barcodeimage, docData.barcode_width, docData.barcode_height, false); //barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), docData.barcode_font, docData.barcode_fontsize, docData.barcode_width*2, docData.barcode_height+10, " " + docData.barcode_zusatz, docData.Zusatz_Font, docData.Zusatz_FontSize, 0); //barcodeimage = AutoSizeImage(barcodeimage, docData.barcode_width*3, docData.barcode_height*3,false); if (docData.barcode_horizontal == 0) { barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 66, 600, 100, docData.barcode_zusatz, "Futur Book", 16, 0); //barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 33, 429, 52, docData.barcode_zusatz, "Futur Book", 8, 270); } else { barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 66, 600, 100, docData.barcode_zusatz, "Futur Book", 16, 0); //barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 33, 429, 52, docData.barcode_zusatz, "Futur Book", 8, 0); } //barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5, docData.Dokumentid.Substring(6, 16), docData.Dokumentid.Substring(6, 16) + docData.barcode_zusatz, docData.barcode_textposition, docData.Zusatz_Font, Convert.ToInt32(docData.Zusatz_FontSize), 0); //barcodeimage = ScaleImage(barcodeimage, docData.barcode_width, docData.barcode_height); //barcodeimage = resizeImage(barcodeimage, new Size(docData.barcode_width,docData.barcode_height)); break; case "1": //BarcodeLibVBDatamatrix.MW6Datamatrix dm = new BarcodeLibVBDatamatrix.MW6Datamatrix(); //dm.Generage_BarcodeImage(ref docData, @"h:\tssettings\edoka\"); //barcodeimage = System.Drawing.Image.FromFile(@"h:\tssettings\edoka\a_" + docData.Dokumentid + ".png"); //System.IO.File.Delete(@"h:\tssettings\edoka\a_" + docData.Dokumentid + ".png"); //barcodeimage = Barcode.Get_Datamatrix(DataMatrix.net.DmtxScheme.DmtxSchemeAutoBest, docData.barcode_content, 4, 0, 0, "Left", docData.barcode_content, docData.barcode_font, docData.barcode_fontsize); barcodeimage = Barcode.Get_Datamatrix(DataMatrix.net.DmtxScheme.DmtxSchemeAscii, docData.barcode_content, 6, 6, 0, "Right", docData.barcode_text + docData.barcode_zusatz, docData.Zusatz_Font, docData.Zusatz_FontSize); barcodeimage = AutoSizeImage(barcodeimage, docData.barcode_width, docData.barcode_height, false); //barcodeimage= resizeImage(barcodeimage, new Size(docData.barcode_width, docData.barcode_height)); //barcodeimage = ScaleImage(barcodeimage, docData.barcode_width,docData.barcode_height); //barcodeimage.Save(@"x:\bctest.png"); break; default: barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5C, docData.Dokumentid.Substring(9, 13), docData.Dokumentid.Substring(6, 16) + docData.barcode_zusatz, docData.barcode_textposition, docData.barcode_font, Convert.ToInt32(docData.barcode_fontsize), 0); break; } // System.Drawing.Image barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5C, docData.Dokumentid.Substring(9, 13), docData.Dokumentid.Substring(9, 13), docData.barcode_textposition "Below", "Arial", 6, 0); foreach (WSection section in document.Sections) { WPicture picture = new WPicture(document); picture.LoadImage(barcodeimage); //picture.Height = docData.barcode_height; //picture.Width = docData.barcode_width; picture.VerticalPosition = docData.barcode_left; picture.HorizontalPosition = docData.barcode_top; picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Page; picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Largest; //picture.Width = barcodeimage.Width; //picture.Height = barcodeimage.Height; if (docData.barcode_horizontal == 0) { picture.Rotation = 270; picture.Height = docData.barcode_height; ; picture.Width = docData.barcode_width; picture.VerticalPosition = docData.barcode_top; ; picture.HorizontalPosition = docData.barcode_left; } else { picture.Rotation = 0; picture.Height = docData.barcode_height; picture.Width = docData.barcode_width; picture.VerticalPosition = docData.barcode_top; ; picture.HorizontalPosition = docData.barcode_left; // picture.Width = barcodeimage.Width; // picture.Height = barcodeimage.Height; } if (docData.barcode_type == "0") { // picture.Width = docData.barcode_width; // picture.Height = docData.barcode_height; } WPicture picture2 = new WPicture(document); picture2 = picture; section.HeadersFooters.Footer.AddParagraph().ChildEntities.Add(picture); section.HeadersFooters.FirstPageFooter.AddParagraph().ChildEntities.Add(picture2); //if (section.HeadersFooters.FirstPageFooter.Paragraphs.Count < 1) //{ section.HeadersFooters.FirstPageFooter.AddParagraph(); section.HeadersFooters.FirstPageFooter.Paragraphs[0].ChildEntities.Add(picture); //} Syncfusion.DocIO.DLS.IWParagraph paragraph = section.Body.LastParagraph; if (paragraph != null) paragraph.ChildEntities.Add(picture); } } public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight) { var ratioX = (double)maxWidth / image.Width; var ratioY = (double)maxHeight / image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(newImage)) graphics.DrawImage(image, 0, 0, newWidth, newHeight); return newImage; } public void insert_Logo(WordDocument document, clsDocData docData) { CLMDocItem di = new CLMDocItem(); di.itemvalue = docData.img_logo; di.top = "20"; di.left = "40"; di.width = "160"; di.height = "40"; Insert_CLMLogo(di, ref document); di = null; return; string b64 = ""; if (docData.img_logo != "") { b64 = docData.img_logo; } else { b64 = Newtonsoft.Json.JsonConvert.DeserializeObject(get_image(4, -1, 0)); } //byte[] imageBytes = Convert.FromBase64String(b64); //using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) //{ // System.Drawing.Image image = System.Drawing.Image.FromStream(ms); // paragraph.AppendPicture(image); //} byte[] imageBytes = Convert.FromBase64String(docData.img_logo); using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { System.Drawing.Image image = System.Drawing.Image.FromStream(ms); //paragraph.AppendPicture(image); WPicture picture = new WPicture(document); WPicture picture2 = new WPicture(document); picture.LoadImage(image); picture2.LoadImage(image); picture.VerticalPosition = Convert.ToInt32(25); picture.HorizontalPosition = Convert.ToInt32(20); picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Page; picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Largest; picture2.VerticalPosition = picture.VerticalPosition; picture2.HorizontalPosition = picture.HorizontalPosition; picture2.HorizontalOrigin = HorizontalOrigin.Page; picture2.VerticalOrigin = VerticalOrigin.Page; picture2.TextWrappingStyle = TextWrappingStyle.Square; picture2.TextWrappingType = TextWrappingType.Largest; picture.Rotation = 0; picture.Height = Convert.ToInt32(40); picture.Width = Convert.ToInt32(160); picture.VerticalPosition = Convert.ToInt32(20); picture.HorizontalPosition = Convert.ToInt32(25); picture2.Rotation = 0; picture2.Height = picture.Height; picture2.Width = picture.Width; picture2.VerticalPosition = picture.VerticalPosition; picture2.HorizontalPosition = picture.HorizontalPosition; IWSection section = document.Sections[0]; //foreach (IWSection section in document.Sections) //{ if (section.PageSetup.DifferentFirstPage == true) { WParagraph FirstfooterPar = new WParagraph(document); FirstfooterPar.ChildEntities.Add(picture); if (section.HeadersFooters.FirstPageHeader.Paragraphs.Count > 0) { section.HeadersFooters.FirstPageHeader.Paragraphs.RemoveAt(section.HeadersFooters.FirstPageHeader.Paragraphs.Count - 1); } section.HeadersFooters.FirstPageHeader.Paragraphs.Add(FirstfooterPar); } WParagraph footerPar = new WParagraph(document); footerPar.ChildEntities.Add(picture2); if (section.HeadersFooters.Header.Count > 0) { section.HeadersFooters.Header.Paragraphs.RemoveAt(section.HeadersFooters.Header.Paragraphs.Count - 1); } section.HeadersFooters.Header.Paragraphs.Add(footerPar); } } /// 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 { } } public bool FindText(string base64, string searchstring) { MemoryStream ms = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(base64)); WordDocument document = new WordDocument(ms, FormatType.Automatic); TextSelection textSelection = document.Find(searchstring, false, true); document = null; ms = null; if (textSelection != null) { return true; } else return false; } } }