You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1223 lines
56 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
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", "");
}
}
}
public string Generate_Word(string base64, clsDocData docdata, string img_UL = "", string img_UR = "", string img_faktura = "", bool serienbrief=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)
{
Insert_Barcode(document, docdata);
}
if (docdata.PrintLogo == true)
{
insert_Logo(document, docdata);
}
if (docdata.Kopfzeile_generieren == true)
{
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;
p = section.HeadersFooters.FirstPageHeader.AddParagraph();
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);
//}
if (docdata.Form_ohne_Unterschrift == "True" || docdata.As_Faksimile == "True")
{
//DB db = new DB();
}
foreach (clsDocValue dv in docdata.DocValues)
{
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")
{
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" && serienbrief==true)
{
string funktionlinks = "";
string funktionrechts = "";
foreach (clsDocValue dv2 in docdata.DocValues)
{
//if (dv2.TMBeginn.ToString() == "TGEDKFunktionLinksB99") { funktionlinks = dv2.Value.ToString(); }
//if (dv2.TMBeginn.ToString() == "TGEDKFunktionRechtsB99") { funktionrechts = dv2.Value.ToString(); }
if (dv2.TMBeginn.ToString().Contains("FunktionLinks")) { funktionlinks = dv2.Value.ToString(); }
if (dv2.TMBeginn.ToString().Contains("FunktionRecht")) { funktionrechts = dv2.Value.ToString(); }
}
bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString());
IWParagraph paragraph = new WParagraph(document);
paragraph.AppendBreak(BreakType.LineBreak);
// if (dv.TMBeginn.ToString() == "TGEDKVornameNameLinksB99")
if (dv.TMBeginn.ToString().Contains("VornameNameLinks"))
{
string unterschrift = "";
if (img_UL != "") { unterschrift = img_UL.ToString(); }
else
{
unterschrift = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(get_unterschrift(docdata.Unterschrift_Links));
}
if (unterschrift != "")
{
MemoryStream mssign = new MemoryStream(Convert.FromBase64String(unterschrift));
System.Drawing.Image img = System.Drawing.Image.FromStream(mssign);
paragraph.AppendPicture(img);
mssign.Dispose();
img.Dispose();
}
}
else
{
string unterschrift = "";
if (img_UR != "") { unterschrift = img_UR; }
else
{
unterschrift = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(get_unterschrift(docdata.Unterschrift_Rechts));
}
if (unterschrift != "")
{
MemoryStream mssign = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(unterschrift));
System.Drawing.Image img = System.Drawing.Image.FromStream(mssign);
mssign.Dispose();
paragraph.AppendPicture(img);
img.Dispose();
}
}
// 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());
//if (dv.TMBeginn.ToString() == "TGEDKVornameNameLinksB99")
if (dv.TMBeginn.ToString().Contains("VornameNameLinks"))
{
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendText(funktionlinks);
}
else
{
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendText(funktionrechts);
}
//paragraph.rep
bookmarkNavigator.InsertParagraph(paragraph);
}
else
{
//if (docdata.As_Faksimile=="True" && (dv.TMBeginn.ToString() == "TGEDKFunktionLinksB99" || dv.TMBeginn.ToString() == "TGEDKFunktionRechtsB99"))
if (docdata.As_Faksimile == "True" && (dv.TMBeginn.ToString().Contains("FunktionLinks") || dv.TMBeginn.ToString().Contains("FunktionRechts")) && serienbrief == true)
{
}
else
{
//if (dv.TMBeginn.ToString() == "TGEDKAdresseZustellungB99")
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());
}
}
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 { }
}
}
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 { }
}
}
}
}
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");
}
}
}
//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 ends 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 starts 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 void Insert_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; }
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();
//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", 33, 300, 50, " U", "Futur Book", 8,270);
}
else
{
barcodeimage = barbarcode.GetBarI25(Color.Black, Color.White, docData.Dokumentid.Substring(6, 16), "Bar 25i c HR", 33, 300, 50, " U", "Futur Book", 8, 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 = 0;
picture.Height = docData.barcode_width;
picture.Width = docData.barcode_height;
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)
{
IWSection section = document.Sections[0];
IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph();
System.Drawing.Image image = System.Drawing.Image.FromFile(@"E:\Software-Projekte\OnDoc\Images\tkb_logo_4c_u.jpg");
paragraph.AppendPicture(image);
////Get the Word document section.
//IWSection section = document.Sections[0];
////Add a paragraph to the header.
//IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph();
//// Get the image stream.
//FileStream imageStream = new FileStream(@"../../../Data/Logo.jpg", FileMode.Open, FileAccess.Read);
////Append the picture to the created paragraph.
//IWPicture picture = paragraph.AppendPicture(imageStream);
////Set the picture properties.
//picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText;
//picture.VerticalOrigin = VerticalOrigin.Margin;
//picture.VerticalPosition = -45;
//picture.HorizontalOrigin = HorizontalOrigin.Column;
//picture.HorizontalPosition = 263.5f;
//picture.WidthScale = 20;
//picture.HeightScale = 15;
}
/// <summary>Word to PDF-Konverter</summary>
/// <remarks>Das sind die Remarks</remarks>
/// <param name="dokument">Base64-Dokument</param>
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<int, List<RectangleF>> textSearch = new Dictionary<int, List<RectangleF>>();
//bool IsMatchFound = documentViewer.FindText("Revision History", out textSearch);
//List<int> 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;
}
}
}