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.

1177 lines
55 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 Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office;
using System.Threading;
using System.Drawing;
using Font = System.Drawing.Font;
using System.Xml.Linq;
using BarcodeLib;
using System.Drawing.Drawing2D;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
using Microsoft.VisualBasic;
using System.Net.NetworkInformation;
namespace OnDocOffice
{
public class clsExcelEdit
{
public string connectstring { get; set; }
public string filename { get; set; }
public string dokumentid { get; set; }
public
Microsoft.Office.Interop.Excel.Application excel;
Workbook workBook = null;
public clsExcelEdit(string connectstring, string filename, string dokumentid)
{
this.connectstring = connectstring;
this.filename = filename;
this.dokumentid = dokumentid;
}
public bool Start_Application()
{
try
{
excel = new Microsoft.Office.Interop.Excel.Application();
return true;
}
catch
{
return false;
}
}
public void Edit_Document()
{
Start_Application();
workBook = excel.Workbooks.Open(filename);
excel.Visible = true;
//clsProcessWatch.AddToList(dokumentid, filename, "Word");
bool isClosed = IsDocumentClosed(excel, workBook);
workBook = null;
excel = null;
}
public void Control_Word(string dokumentid, string filename, string application)
{
//clsProcessWatch.AddToList(dokumentid, filename, application);
}
static bool IsDocumentClosed(Microsoft.Office.Interop.Excel.Application excelApp, Workbook workBook)
{
// Check if the document is still listed in the Documents collection
foreach (Workbook openDoc in excelApp.Workbooks)
{
if (openDoc.FullName == workBook.FullName)
{
return false; // Document is still open
}
}
return true; // Document is closed
}
public void run_macros()
{
}
public bool IsNumeric(string value)
{
return value.All(char.IsNumber);
}
public string Bar25I(string BarTextIn)
{
string Bar25IRet = default;
string BarTextOut = "";
string TempString = "";
long CharValue = 0;
string barcodeout = "";
// Initialize input and output strings
BarTextOut = "";
BarTextIn = BarTextIn.Trim();
// Throw away non-numeric data
TempString = "";
for (int II = 1, loopTo = BarTextIn.Length; II <= loopTo; II++)
{
if (IsNumeric(BarTextIn.Substring(II - 1, 1)))
{
TempString = TempString + BarTextIn.Substring(II - 1, 1);
}
}
// If not an even number of digits, add a leading 0
if (TempString.Length % 2 == 1)
{
TempString = "0" + TempString;
}
// Break digit pairs up and convert to characters- build output string
for (int II = 1, loopTo1 = TempString.Length; II <= loopTo1; II += 2)
{
// Break string into pairs of digits and get value
CharValue = Convert.ToInt32(TempString.Substring(II - 1, 2));
// translate value to ASCII and save in BarTextOut
if (CharValue < 90)
{
BarTextOut = BarTextOut + (char)(CharValue + 33);
}
else
{
BarTextOut = BarTextOut + (char)(CharValue + 71);
}
}
// Build ouput string, trailing space for Windows rasterization bug
barcodeout = "{" + BarTextOut + "} ";
// Return the string
Bar25IRet = barcodeout;
return Bar25IRet;
}
public string convert_excel(string x)
{
string s;
string s1;
int i;
s = x;
i = Microsoft.VisualBasic.Strings.InStr(s, Strings.Chr(13).ToString());
while (i > 0)
{
s = Strings.Left(s, i - 1) + "#" + Strings.Right(s, Strings.Len(s) - (i));
if (Strings.Mid(s, i + 1, 1) == Strings.Chr(10).ToString())
s = Strings.Left(s, i) + Strings.Right(s, Strings.Len(s) - (i + 1));
i = Microsoft.VisualBasic.Strings.InStr(s, Strings.Chr(13).ToString());
}
i = Microsoft.VisualBasic.Strings.InStr(s, "#");
while (i > 0)
{
s = Strings.Left(s, i - 1) + Strings.Chr(10) + Strings.Right(s, Strings.Len(s) - (i));
i = Microsoft.VisualBasic.Strings.InStr(s, "#");
}
return s;
}
public string Generate_Excel_in_Office(ref clsDocData docdata, ref clsdok dok, string vorlage, string connectionstring, string tempdir, string dokumentid, string apptype, string extension, int OfficeSleep, int bookmarks_docio)
{
this.dokumentid = docdata.Dokumentid;
string filename = tempdir + dokumentid + "." + extension;
bool cursor = false;
int sheetcursor = 0;
int i = 0;
Helper.clsFileHelper fh = new Helper.clsFileHelper();
fh.SaveBase64ToFile(vorlage, filename);
Start_Application();
workBook = excel.Workbooks.Open(filename);
foreach (Worksheet ws in workBook.Sheets)
{
ws.Activate();
foreach (clsDocValue dv in docdata.DocValues)
{
try
{
if (dv.TMBeginn == "TGEDKCursor" || dv.TMBeginn == "TGEDKCursorB" || dv.FieldName == "TGEDKCursor" || dv.FieldName == "TGEDKCursorB")
{
try
{
excel.Range[workBook.Names.Item(dv.FieldName).NameLocal].Select();
cursor = true;
sheetcursor = i;
}
catch
{
}
}
else
{
excel.Range[workBook.Names.Item(dv.FieldName).NameLocal].Select();
excel.ActiveCell.FormulaR1C1 = convert_excel(dv.Value);
}
}
catch { }
}
i = i + 1;
}
if (docdata.Barcode == true)
{
string barcode = Bar25I(dokumentid.Substring(6, 16));
foreach (Worksheet ws in workBook.Sheets)
{
ws.Activate();
int i1 = 0;
int i2 = 0;
for (i1 = 1; i1 < workBook.Names.Count; i1++)
{
string na = workBook.Names.Item(i1).NameLocal;
if (na.Substring(0, 7) == "TGEDKBC")
{
excel.Range[excel.Names.Item(na).NameLocal].Select();
excel.ActiveCell.FormulaR1C1 = barcode;
try
{
excel.Selection.Characters.Font.Name = docdata.barcode_font;
}
catch { }
}
if (na.Substring(0, 7) == "TGEDKAR")
{
excel.Range[excel.Names.Item(na).NameLocal].Select();
excel.ActiveCell.FormulaR1C1 = convert_excel(docdata.barcode_zusatz);
}
}
}
}
workBook.Save();
workBook.Close();
workBook = null;
string b64 = fh.Base64FromFile(filename);
excel.Workbooks.Open(filename);
excel.Visible= true;
excel = null;
Logging.Logging.Debug("Generierung abgeschlossen", "clsOffice", dokumentid);
return b64;
//return fh.Base64FromFile(filename);
}
}
public class clsWordEdit
{
public string connectstring { get; set; }
public string filename { get; set; }
public string dokumentid { get; set; }
public bool is_protected { get; set; } = false;
public
Microsoft.Office.Interop.Word.Application word;
Microsoft.Office.Interop.Word.Document worddoc;
Document doc = null;
public clsWordEdit(string connectstring, string filename, string dokumentid)
{
this.connectstring = connectstring;
this.filename = filename;
this.dokumentid = dokumentid;
}
public bool Start_Application()
{
try
{
//Type WordType = Type.GetTypeFromProgID("Word.Application");
//word = Activator.CreateInstance(WordType);
////ExcelInst.Visible = true;
word = (Microsoft.Office.Interop.Word.Application)Interaction.CreateObject("Word.Application");
//word = new Microsoft.Office.Interop.Word.Application();
word.Run("Autoexec");
word.NormalTemplate.Saved = true;
return true;
}
catch
{
return false;
}
}
public void Edit_Document(bool runmacros)
{
Start_Application();
doc = word.Documents.Open(filename);
word.Visible = true;
if (runmacros == true)
{
Database.DB db = new Database.DB(connectstring);
db.Get_Tabledata("Select * from ondoc_macros where dokumentid='" + dokumentid + "' order by reihenfolge", false, true);
foreach (DataRow dr in db.dsdaten.Tables[0].Rows)
{
try
{
word.Run(dr[0].ToString());
}
catch (Exception e) { string a = e.Message; }
}
}
//clsProcessWatch.AddToList(dokumentid, filename, "Word");
bool isClosed = IsDocumentClosed(word, doc);
doc = null;
word = null;
}
public void Control_Word(string dokumentid, string filename, string application)
{
//clsProcessWatch.AddToList(dokumentid, filename, application);
}
static bool IsDocumentClosed(Microsoft.Office.Interop.Word.Application wordApp, Document doc)
{
// Check if the document is still listed in the Documents collection
foreach (Document openDoc in wordApp.Documents)
{
if (openDoc.FullName == doc.FullName)
{
return false; // Document is still open
}
}
return true; // Document is closed
}
public void run_macros(ref clsDocData docdata, string connectionstring)
{
Database.DB db = new Database.DB(connectionstring);
db.Get_Tabledata("select * from view_idv_makros where office_vorlagenr=" + docdata.VorlageNr.ToString() + " order by reihenfolge asc", false, true);
if (db.dsdaten.Tables[0].Rows.Count > 0) { word.Visible = true; word.Activate(); }
foreach (DataRow dr in db.dsdaten.Tables[0].Rows)
{
if (dr[0].ToString() == "DokumentSchuetzen")
{
worddoc.Range(0, 0).Select();
worddoc.Protect(Type: Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyFormFields, NoReset: true, Password: "Australia");
}
try
{
word.Run(dr[0].ToString());
}
catch (Exception e) { string a = e.Message; }
}
}
public void Word_Compatibility_Mode (ref WordDocument wd)
{
CompatibilityMode compatibilityMode = wd.Settings.CompatibilityMode;
var formattype_original = wd.ActualFormatType;
switch (compatibilityMode)
{
case CompatibilityMode.Word2010:
wd.Settings.CompatibilityMode = CompatibilityMode.Word2010;
break;
case CompatibilityMode.Word2013:
wd.Settings.CompatibilityMode = CompatibilityMode.Word2013;
break;
default:
// wd.Settings.CompatibilityMode = CompatibilityMode.Word2003;
break;
}
}
private string set_cmode(string file)
{
string formattype = "";
MemoryStream ms = new MemoryStream(Helper.EncodeExtensions.DecodeBase642ByteArray(file));
WordDocument document = new WordDocument(ms, FormatType.Automatic);
CompatibilityMode compatibilityMode = document.Settings.CompatibilityMode;
formattype = document.ActualFormatType.ToString();
var formattype_original = document.ActualFormatType;
Word_Compatibility_Mode(ref document);
//switch (compatibilityMode)
//{
// case CompatibilityMode.Word2010:
// document.Settings.CompatibilityMode = CompatibilityMode.Word2010;
// break;
// case CompatibilityMode.Word2013:
// document.Settings.CompatibilityMode = CompatibilityMode.Word2010;
// break;
// default:
// document.Settings.CompatibilityMode = CompatibilityMode.Word2003;
// break;
//}
MemoryStream destms = new MemoryStream();
document.Save(destms,formattype_original);
document.Close();
document.Dispose();
byte[] imageArray = destms.ToArray();
return Convert.ToBase64String(imageArray);
}
public string Generate_Word_in_Office(ref clsDocData docdata, ref clsdok dok, string vorlage, string connectionstring, string tempdir, string dokumentid, string apptype, string extension, int OfficeSleep, int bookmarks_docio)
{
this.dokumentid = docdata.Dokumentid;
string filename = tempdir + dokumentid + "." + extension;
int pos = 0;
int pos2 = 0;
VBFileManagement.VBFileManagement vb = new VBFileManagement.VBFileManagement();
vb.Get_From_DB(Convert.ToInt32(docdata.VorlageNr), filename, connectionstring, false);
Helper.clsFileHelper fh = new Helper.clsFileHelper();
vorlage = fh.Base64FromFile(filename);
vorlage = set_cmode(vorlage);
fh.SaveBase64ToFile(vorlage, filename);
Logging.Logging.Debug("Generate_Word_in_Office", "clsOffice", dokumentid);
Start_Application();
// Thread.Sleep(OfficeSleep);
worddoc = word.Documents.Open(filename);
Thread.Sleep(OfficeSleep);
string ext = System.IO.Path.GetExtension(filename).ToUpper();
Logging.Logging.Debug(word.ActiveDocument.CompatibilityMode.ToString(), ext, dokumentid);
//switch (word.ActiveDocument.CompatibilityMode)
//{
// case 14:
// switch (ext)
// {
// case ".DOCX":
// word.ActiveDocument.SaveAs2(filename, CompatibilityMode:14, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument);
// break;
// case ".DOCM":
// word.ActiveDocument.SaveAs2(filename, CompatibilityMode:14, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocumentMacroEnabled);
// break;
// case ".DOTX":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplate, CompatibilityMode: 14);
// break;
// case "DOTM":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplateMacroEnabled, CompatibilityMode: 14);
// break;
// }
// break;
// case 15:
// case 16:
// case 17:
// case 18:
// switch (ext)
// {
// case ".DOCX":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument);
// break;
// case ".DOCM":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocumentMacroEnabled);
// break;
// case ".DOTX":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplate);
// break;
// case "DOTM":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplateMacroEnabled);
// break;
// }
// break;
// default:
// switch (ext)
// {
// case ".DOCX":
// word.ActiveDocument.SaveAs2(filename, CompatibilityMode: 11, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument);
// break;
// case ".DOCM":
// word.ActiveDocument.SaveAs2(filename, CompatibilityMode: 11, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocumentMacroEnabled);
// break;
// case ".DOTX":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplate, CompatibilityMode: 11);
// break;
// case "DOTM":
// word.ActiveDocument.SaveAs2(filename, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplateMacroEnabled, CompatibilityMode: 11);
// break;
// }
// break;
//}
word.NormalTemplate.Saved = true;
//word.ActiveDocument.Close(false);
Thread.Sleep(OfficeSleep);
//worddoc = word.Documents.Open(filename);
Logging.Logging.Debug("Word Open", "clsOffice", dokumentid);
Logging.Logging.Debug("Word befüllen", "clsOffice", dokumentid);
Thread.Sleep(OfficeSleep);
if (worddoc.ProtectionType != Microsoft.Office.Interop.Word.WdProtectionType.wdNoProtection)
{
worddoc.Unprotect(Password: "Australia");
is_protected = true;
}
bool cursorpositionieren = false;
if (docdata.Kopfzeile_generieren == true)
{
Kopfzeile_generieren();
}
//word.Visible = false;
word.ScreenUpdating = false;
if (bookmarks_docio == 1)
{
worddoc.Save();
worddoc.Close();
Fill_Bookmarks_from_Word(filename, docdata, "", "");
worddoc = word.Documents.Open(filename);
}
else
{
foreach (clsDocValue dv in docdata.DocValues)
{
try
{
if (dv.TMBeginn.ToString() == "TGEDKCursor" || dv.TMBeginn.ToString() == "TGEDKCursorB" ||
dv.FieldName.ToString() == "TGEDKCursor" || dv.FieldName.ToString() == "TGEDKCursorB") { cursorpositionieren = true; }
}
catch { }
Logging.Logging.Debug(dv.TMBeginn.ToString() + " / " + dv.TMEnd.ToString(), dv.Value.ToString(), dokumentid);
if (dv.TMBeginn.ToString() != "" && dv.TMEnd.ToString() == "")
{
try
{
//Logging.Logging.Debug(dv.TMBeginn.ToString() ,"Select" , dokumentid);
worddoc.Bookmarks[dv.TMBeginn.ToString()].Select();
//Logging.Logging.Debug(dv.TMBeginn.ToString(), "Select-End", dokumentid);
word.Selection.Text = dv.Value.ToString();
//Logging.Logging.Debug(dv.TMBeginn.ToString(), "Text-End", dokumentid);
//pos = worddoc.Bookmarks[dv.TMBeginn.ToString()].Start;
//pos2 = word.Selection.End;
Logging.Logging.Debug(dv.TMBeginn.ToString(), "Selection-End", dokumentid);
//------------------------------
if (dv.TMBeginn.ToString().Substring(0, 19) == "XTGEDKDirektTelefonB" ||
dv.TMBeginn.ToString().Substring(0, 23) == "XTGEDKVornameNameBetreue" ||
dv.TMBeginn.ToString().Substring(0, 19) == "XTGEDKDirektTelefonZ")
{
pos = worddoc.Bookmarks[dv.TMBeginn.ToString()].Start;
pos2 = word.Selection.End;
word.Selection.MoveLeft(Unit: Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count: 1);
word.Selection.TypeText(Text: "");
word.Selection.SetRange(Start: pos + 1, End: pos2 + 1);
var withBlock = worddoc.Bookmarks;
withBlock.Add(Range: word.Selection.Range, Name: dv.TMBeginn.ToString());
withBlock.DefaultSorting = Microsoft.Office.Interop.Word.WdBookmarkSortBy.wdSortByName;
withBlock.ShowHidden = false;
}
else
{
if (dv.TMBeginn.ToString().Substring(0, 22) == "XTGEDKDirektTelefonDokZ" ||
dv.TMBeginn.ToString().Substring(0, 20) == "XTGEDKVornameNameDokZ")
{
pos = worddoc.Bookmarks[dv.TMBeginn.ToString()].Start;
pos2 = word.Selection.End;
word.Selection.Text = dv.Value.ToString();
word.Selection.MoveLeft(Unit: Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count: 1);
word.Selection.TypeText(Text: "");
word.Selection.SetRange(Start: pos + 1, End: pos2 + 1);
var withBlock = worddoc.Bookmarks;
withBlock.Add(Range: word.Selection.Range, Name: dv.TMBeginn.ToString());
withBlock.DefaultSorting = Microsoft.Office.Interop.Word.WdBookmarkSortBy.wdSortByName;
withBlock.ShowHidden = false;
}
else
{
//objWord.Visible = True
// objWord.Selection.SetRange(Start:= pos, End:= pos2)
// With docWord.Bookmarks
// .Add(Range:= objWord.Selection.Range, Name:= Dokumentdaten.Rows(i).Item("beginntextmarke"))
// .DefaultSorting = Microsoft.Office.Interop.Word.WdBookmarkSortBy.wdSortByName
// .ShowHidden = False
// End With
}
}
//-------------------------------
//objWord.Selection.MoveLeft(Unit:= Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count:= 1)
// objWord.Selection.MoveLeft(Unit:= Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count:= 2, Extend:= Microsoft.Office.Interop.Word.WdMovementType.wdExtend)
// If objWord.Selection.Text = " " Then
// objWord.Selection.MoveRight(Unit:= Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count:= 1)
// objWord.Selection.MoveLeft(Unit:= Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count:= 1, Extend:= Microsoft.Office.Interop.Word.WdMovementType.wdExtend)
// objWord.Selection.Delete(Unit:= Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count:= 1)
// End If
}
catch { }
}
if (dv.TMBeginn.ToString() != "" && dv.TMEnd.ToString() != "")
{
try
{
worddoc.Bookmarks[dv.TMBeginn.ToString()].Select();
pos = worddoc.Bookmarks[dv.TMBeginn.ToString()].Start;
worddoc.Bookmarks[dv.TMEnd.ToString()].Select();
pos2 = worddoc.Bookmarks[dv.TMEnd.ToString()].Start;
word.Selection.SetRange(pos, pos2);
word.Selection.TypeText(Text: dv.Value.ToString());
}
catch { }
}
if (dv.FieldName.ToString() != "")
{
try
{
worddoc.FormFields[dv.FieldName.ToString()].Result = dv.Value;
}
catch { }
}
}
}
word.ScreenUpdating = true;
Logging.Logging.Debug("Word Befüllen Ende", "clsOffice", dokumentid);
if (docdata.Barcode == true) { Generate_Barcodes(ref docdata); }
Logging.Logging.Debug("Barcodes", "clsOffice", dokumentid);
if (is_protected)
{
try
{
worddoc.Protect(Type: Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyFormFields, NoReset: true, Password: "Australia");
}
catch { }
}
//word.Visible = true;
Logging.Logging.Debug("Start Macros", "clsOffice", dokumentid);
run_macros(ref docdata, connectionstring);
worddoc.Save();
Logging.Logging.Debug("Word Saved", "clsOffice", dokumentid);
worddoc.Close();
Logging.Logging.Debug("Word geschlossen", "clsOffice", dokumentid);
Thread.Sleep(OfficeSleep);
string b64 = fh.Base64FromFile(filename);
word.Documents.Open(filename);
Logging.Logging.Debug("Word geöffnet", "clsOffice", dokumentid);
worddoc = null;
word = null;
Logging.Logging.Debug("Generierung abgeschlossen", "clsOffice", dokumentid);
return b64;
//return fh.Base64FromFile(filename);
}
private void Kopfzeile_generieren()
{
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdStory);
if (word.ActiveWindow.View.SplitSpecial != Microsoft.Office.Interop.Word.WdSpecialPane.wdPaneNone)
{
word.ActiveWindow.Panes[2].Close();
}
if (word.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || word.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView)
{
word.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
}
word.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
set_headerbookmark();
word.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
}
private void set_headerbookmark()
{
try
{
worddoc.Bookmarks["TGEDKCompanyBBEB99"].Select();
}
catch
{
word.Selection.MoveDown(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine, Count: 1);
{
var withBlock = word.ActiveDocument.Bookmarks;
withBlock.Add(Range: word.Selection.Range, Name: "TGEDKCompanyBBEB99");
withBlock.DefaultSorting = Microsoft.Office.Interop.Word.WdBookmarkSortBy.wdSortByName;
withBlock.ShowHidden = false;
}
}
}
private void HeaderFooterAnzeigen()
{
if (word.ActiveWindow.View.SplitSpecial != Microsoft.Office.Interop.Word.WdSpecialPane.wdPaneNone)
{
word.ActiveWindow.Panes[2].Close();
}
if (word.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || word.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView)
{
word.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
}
word.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
if (word.Selection.HeaderFooter.IsHeader == true)
{
word.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
}
else
{
word.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
}
}
public void Insert_Datamatrix(string filename)
{
object Form;
string strsel;
object strresult;
string s;
int dmposition;
// Selection.ShapeRange.Select
try
{
//object missing = System.Reflection.Missing.Value;
//object start1 = 0;
//object end1 = 0;
//Document adoc = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
//Microsoft.Office.Interop.Word.Range rng = adoc.Range(ref start1, ref missing);
string Zeichen;
Zeichen = " U";
int BarcodeFormatn = 0;
switch (BarcodeFormatn)
{
case 0:
{
word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine, Extend: Microsoft.Office.Interop.Word.WdMovementType.wdExtend);
word.Selection.Delete(Unit: Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count: 1);
word.Selection.InlineShapes.AddPicture(filename, LinkToFile: false, SaveWithDocument: true);
break;
}
case 1:
{
word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine, Extend: Microsoft.Office.Interop.Word.WdMovementType.wdExtend);
word.Selection.Delete(Unit: Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count: 1);
word.Selection.InlineShapes.AddPicture(filename, LinkToFile: false, SaveWithDocument: true);
break;
}
case 2:
{
word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine, Extend: Microsoft.Office.Interop.Word.WdMovementType.wdExtend);
word.Selection.Delete(Unit: Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count: 1);
word.Selection.InlineShapes.AddPicture(filename, LinkToFile: false, SaveWithDocument: true);
break;
}
case 3:
{
word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine, Extend: Microsoft.Office.Interop.Word.WdMovementType.wdExtend);
word.Selection.Delete(Unit: Microsoft.Office.Interop.Word.WdUnits.wdCharacter, Count: 1);
word.Selection.InlineShapes.AddPicture(filename, LinkToFile: false, SaveWithDocument: true);
break;
}
}
Form = null;
return;
}
catch (Exception ex)
{
}
}
private 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;
}
private void Generate_Barcodes(ref clsDocData docdata)
{
float left = 360;
float top = 793;
float width = 200;
float height = 33;
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdStory);
Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
int pages = worddoc.ComputeStatistics(stat, null);
for (int i = 1; i <= pages; i++)
{
string xname = i.ToString().Trim();
try
{
word.Selection.GoTo(What: Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage, xname);
}
catch { }
HeaderFooterAnzeigen();
if (docdata.barcode_type == "1")
{
System.Drawing.Image barcodeimage;
BarcodeLib.Barcode Barcode = new BarcodeLib.Barcode();
barcodeimage = Barcode.Get_Datamatrix(DataMatrix.net.DmtxScheme.DmtxSchemeAscii, docdata.barcode_content, 6, 6, 0, "Right", docdata.barcode_text, docdata.Zusatz_Font, docdata.Zusatz_FontSize);
barcodeimage = ResizeImage(barcodeimage, new Size(200, 80));
barcodeimage.Save(word.ActiveDocument.FullName + ".png");
Insert_Datamatrix(word.ActiveDocument.FullName + ".png");
System.IO.File.Delete(word.ActiveDocument.FullName + ".png");
return;
}
else
{
//System.Drawing.Image barcodeimage;
//BarcodeLib.Barcode Barcode = new BarcodeLib.Barcode();
//barcodeimage = Barcode.Get_LinerBarcode(Barcoded.Symbology.I2of5, dokumentid.Substring(6, 16), dokumentid.Substring(6, 16) + docdata.barcode_zusatz, docdata.barcode_textposition, docdata.Zusatz_Font, Convert.ToInt32(docdata.Zusatz_FontSize), 0);
//barcodeimage.Save(word.ActiveDocument.FullName + ".png");
//Insert_Datamatrix(word.ActiveDocument.FullName + ".png");
//System.IO.File.Delete(word.ActiveDocument.FullName + ".png");
//return;
}
word.Selection.HeaderFooter.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, docdata.barcode_left, docdata.barcode_top, docdata.barcode_width, docdata.barcode_height).Select();
word.Selection.ShapeRange.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
word.Selection.ShapeRange.TextFrame.MarginLeft = 0;
word.Selection.ShapeRange.TextFrame.MarginTop = 0;
word.Selection.ShapeRange.TextFrame.MarginRight = 0;
word.Selection.ShapeRange.TextFrame.MarginBottom = 0;
word.ActiveDocument.Tables.Add(Range: word.Selection.Range, NumRows: 1, NumColumns: 1);
if (docdata.barcode_horizontal == 0)
{
word.Selection.Tables[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
word.Selection.Tables[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
word.Selection.Tables[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
word.Selection.Tables[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
word.Selection.Tables[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
word.Selection.Tables[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalUp].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
word.Selection.Orientation = Microsoft.Office.Interop.Word.WdTextOrientation.wdTextOrientationUpward;
word.Selection.Tables[1].Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;
word.Selection.Tables[1].Rows.Height = 150;
}
word.Selection.TypeText(Bar25I(dokumentid.Substring(6, 16)));
word.Selection.HomeKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine, Extend: Microsoft.Office.Interop.Word.WdMovementType.wdExtend);
word.Selection.Font.Name = docdata.barcode_font;
word.Selection.Font.Size = docdata.barcode_fontsize;
word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
word.Selection.EndKey(Unit: Microsoft.Office.Interop.Word.WdUnits.wdLine);
word.Selection.Font.Name = docdata.Zusatz_Font;
word.Selection.Font.Size = docdata.Zusatz_FontSize;
word.Selection.TypeText(docdata.barcode_zusatz);
}
}
public bool IsNumeric(string value)
{
return value.All(char.IsNumber);
}
public string Bar25I(string BarTextIn)
{
string Bar25IRet = default;
string BarTextOut = "";
string TempString = "";
long CharValue = 0;
string barcodeout = "";
// Initialize input and output strings
BarTextOut = "";
BarTextIn = BarTextIn.Trim();
// Throw away non-numeric data
TempString = "";
for (int II = 1, loopTo = BarTextIn.Length; II <= loopTo; II++)
{
if (IsNumeric(BarTextIn.Substring(II - 1, 1)))
{
TempString = TempString + BarTextIn.Substring(II - 1, 1);
}
}
// If not an even number of digits, add a leading 0
if (TempString.Length % 2 == 1)
{
TempString = "0" + TempString;
}
// Break digit pairs up and convert to characters- build output string
for (int II = 1, loopTo1 = TempString.Length; II <= loopTo1; II += 2)
{
// Break string into pairs of digits and get value
CharValue = Convert.ToInt32(TempString.Substring(II - 1, 2));
// translate value to ASCII and save in BarTextOut
if (CharValue < 90)
{
BarTextOut = BarTextOut + (char)(CharValue + 33);
}
else
{
BarTextOut = BarTextOut + (char)(CharValue + 71);
}
}
// Build ouput string, trailing space for Windows rasterization bug
barcodeout = "{" + BarTextOut + "} ";
// Return the string
Bar25IRet = barcodeout;
return Bar25IRet;
}
public string get_unterschrift(string input)
{
return "";
}
public void Replace_Text(ref WordDocument wordDocument, string TextToReplace, string NewText)
{
wordDocument.Replace(TextToReplace, NewText, true, true);
}
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.
Syncfusion.DocIO.DLS.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.
Syncfusion.DocIO.DLS.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.
Syncfusion.DocIO.DLS.Bookmark bookmark = document.Bookmarks.FindByName(tempBookmarkName);
//Remove the temp bookmark named from Word document.
document.Bookmarks.Remove(bookmark);
#endregion
}
public void Fill_Bookmarks_from_Word(string filename, clsDocData docdata, string img_UL = "", string img_UR = "")
{
using (FileStream inputFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) ;
WordDocument document = new WordDocument();
document.Open(filename, FormatType.Automatic);
Word_Compatibility_Mode(ref document);
//CompatibilityMode compatibilityMode = document.Settings.CompatibilityMode;
//var formattype_original = document.ActualFormatType;
//switch (compatibilityMode)
//{
// case CompatibilityMode.Word2010:
// document.Settings.CompatibilityMode = CompatibilityMode.Word2010;
// break;
// case CompatibilityMode.Word2013:
// document.Settings.CompatibilityMode = CompatibilityMode.Word2010;
// break;
// default:
// document.Settings.CompatibilityMode = CompatibilityMode.Word2003;
// break;
//}
foreach (clsDocValue dv in docdata.DocValues)
{
if (docdata.Form_ohne_Unterschrift == "True")
{
foreach (clsDocValue dv2 in docdata.DocValues)
{
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() != "" && dv.TMEnd.ToString() == "")
{
try
{
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
if ((dv.TMBeginn.ToString() == "TGEDKVornameNameLinksB99" || dv.TMBeginn.ToString() == "TGEDKVornameNameRechtsB99") && docdata.As_Faksimile == "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(); }
}
bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString());
IWParagraph paragraph = new WParagraph(document);
paragraph.AppendBreak(BreakType.LineBreak);
if (dv.TMBeginn.ToString() == "TGEDKVornameNameLinksB99")
{
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")
{
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"))
{
}
else
{
Syncfusion.DocIO.DLS.Bookmark bookmark;
bookmark = document.Bookmarks.FindByName(dv.TMBeginn.ToString());
if (bookmark != null)
{
bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString(),true,false);
bookmarkNavigator.MoveToBookmark(dv.TMBeginn.ToString());
bookmarkNavigator.InsertText(dv.Value.ToString());
bookmarkNavigator.ReplaceBookmarkContent(dv.Value.ToString(),true);
//TextBodyPart bookmarkContent = bookmarkNavigator.GetBookmarkContent();
//string bookmarkText = ((Syncfusion.DocIO.DLS.WParagraph)bookmarkContent.BodyItems.FirstItem).Text;
}
}
}
}
catch { }
}
if (dv.TMBeginn.ToString() != "" && dv.TMEnd.ToString() != "")
{
try
{
ReplaceBookmarkContent(ref document, dv.TMBeginn.ToString(), dv.TMEnd.ToString(), dv.Value.ToString());
}
catch { }
}
if (dv.FieldName.ToString() != "")
{
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())
{
formField.Text = dv.Value.ToString();
break;
}
}
}
}
catch { }
}
}
document.Save(filename);
document.Dispose();
document = null;
return;
}
}
}