public static string MergeWorkorder(Workorder workorder) { using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) { tx.Create(); // load the work order template tx.Load(HttpContext.Current.Server.MapPath( "~/App_Data/workorder.tx"), TXTextControl.StreamType.InternalUnicodeFormat); MailMerge mm = new MailMerge() { TextComponent = tx }; // merge the data into the template mm.MergeObject(workorder); // generate a unique filename and save the work order var sFileName = Helpers.GenerateUID(5); tx.Save(HttpContext.Current.Server.MapPath("~/App_Data/" + sFileName + ".tx"), TXTextControl.StreamType.InternalUnicodeFormat); return(sFileName); } }
public string Merge(DocumentViewModel model) { // convert the template to a byte array byte[] document = Convert.FromBase64String(model.BinaryDocument); // load the the data source DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("/App_Data/data/sample_db.xml"), XmlReadMode.Auto); byte[] sDocument; // create a new ServerTextControl and MailMerge component using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) { MailMerge mm = new MailMerge(); mm.TextComponent = tx; // load the template and merge mm.LoadTemplateFromMemory(document, FileFormat.InternalUnicodeFormat); mm.Merge(ds.Tables[0], true); // save the document mm.SaveDocumentToMemory(out sDocument, TXTextControl.BinaryStreamType.InternalUnicodeFormat, null); } // encode and return the merged document return Convert.ToBase64String(sDocument); }
protected override void DoMergeTypeSetup(ComObjectManager com, MailMerge mailMerge) { ActivateOutlookWorkOffline(com); mailMerge.MailAddressFieldName = @"Email"; mailMerge.MailFormat = WdMailMergeMailFormat.wdMailFormatHTML; mailMerge.MailSubject = GetEmailSubject(); mailMerge.Destination = WdMailMergeDestination.wdSendToEmail; }
public static BarcodeView CreateBarcode(string Filename) { using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) { tx.Create(); // assemble the barcode URL BarcodeData data = new BarcodeData() { Barcode = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/Home/ViewDocument?document=" + Filename }; // load the barcode template tx.Load(HttpContext.Current.Server.MapPath("~/App_Data/barcode.tx"), TXTextControl.StreamType.InternalUnicodeFormat); MailMerge mm = new MailMerge() { TextComponent = tx }; // merge the barcode mm.MergeObject(data); BarcodeView view = new BarcodeView() { Url = data.Barcode }; // create an return the barcode image foreach (TXTextControl.DataVisualization.BarcodeFrame barcode in tx.Barcodes) { byte[] imageArray; MemoryStream ms = new MemoryStream(); ((TXTextControl.Barcode.TXBarcodeControl)barcode.Barcode).SaveImage( ms, System.Drawing.Imaging.ImageFormat.Png); imageArray = new byte[ms.Length]; ms.Seek(0, System.IO.SeekOrigin.Begin); ms.Read(imageArray, 0, (int)ms.Length); view.Image = "data:image/png;base64," + Convert.ToBase64String(imageArray); return(view); } return(null); } }
public string SignDocument(Document model) { byte[] document = Convert.FromBase64String(model.BinaryDocument); string signature = model.BinarySignature; byte[] signatureDocument = null; using (ServerTextControl tx = new ServerTextControl()) { tx.Create(); // use MailMerge to merge the signature template using (MailMerge mailMerge = new MailMerge()) { mailMerge.TextComponent = tx; mailMerge.LoadTemplate(Server.MapPath("/App_Data/signature_template.tx"), FileFormat.InternalUnicodeFormat); // create a new signature object Signature sign = new Signature(); sign.Name = model.Name; sign.SignatureImage = signature; // merge and save the resulting document mailMerge.MergeObject(sign); mailMerge.SaveDocumentToMemory(out signatureDocument, BinaryStreamType.InternalUnicodeFormat, null); } // load the original document from the editor tx.Load(document, BinaryStreamType.InternalUnicodeFormat); // find the "signature" text frame with the name "txsig" foreach (TextFrame frame in tx.TextFrames) { if (frame.Name == "txsig") { frame.Tables.Clear(); frame.Selection.Start = 0; frame.Selection.Length = -1; // load the merged signature template into the // text frame and save the complete document frame.Selection.Load(signatureDocument, BinaryStreamType.InternalUnicodeFormat); tx.Save(out document, BinaryStreamType.InternalUnicodeFormat); break; } } } // finally, return the signed document return(Convert.ToBase64String(document)); }
protected void btnDownloadTemplate_Click(object sender, EventArgs e) { string path = g_Config["WordTemplatePath"]; string filenamewithoutextension = null; string datafilename = null; string originalfilename = null; if ((myReport.WordFile != null) && File.Exists(path + myReport.WordFile.WordFileName)) { filenamewithoutextension = Path.GetFileNameWithoutExtension(myReport.WordFile.WordFileName); if (filenamewithoutextension.LastIndexOf('.') > 0) { filenamewithoutextension = filenamewithoutextension.Substring(0, filenamewithoutextension.LastIndexOf('.')); } datafilename = filenamewithoutextension + ".xlsx"; originalfilename = myReport.WordFile.OrigFileName; } else { int svid = Convert.ToInt32(this.ddlQueryName.SelectedValue); CUSTOMRP.Model.WORDTEMPLATE wordtemplate = WebHelper.bllWORDTEMPLATE.GetModelBySVID(me.ID, svid, me.ID); if (wordtemplate != null) { filenamewithoutextension = Path.GetFileNameWithoutExtension(wordtemplate.TemplateFileName); datafilename = wordtemplate.DataFileName; originalfilename = wordtemplate.TemplateFileName; } } if (filenamewithoutextension == null) { this.lblJavascript.Text = String.Format("<script type=\"text/javascript\">alert(\"{0}\");</script>", AppNum.ErrorMsg.filenotfounderror); return; } MemoryStream filestream = MailMerge.ChangeDataFilePath(path + myReport.WordFile.WordFileName, datafilename); Context.Response.ContentType = "application/octet-stream"; //Encode filename according to RFC5987 //Response.AddHeader("Content-Disposition", "attachment; filename=\"" + originalfilename + "\""); Context.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"; filename*=utf-8''{1}", originalfilename, HttpUtility.UrlPathEncode(originalfilename))); Context.Response.AddHeader("Content-Length", filestream.Length.ToString()); byte[] fileBuffer = new byte[filestream.Length]; filestream.Read(fileBuffer, 0, (int)filestream.Length); filestream.Close(); Context.Response.BinaryWrite(fileBuffer); p_fSuppressRender = true; HttpContext.Current.ApplicationInstance.CompleteRequest(); }
/// <summary> /// 1. Create a new package as a Word document /// 2. Add a style.xml part /// 3. Add an embedded image part /// 4. Create the document.xml part content /// </summary> /// <returns>File path location or error message</returns> public static void ReadDocument(String fileName) { try { // Read the file document into the DOM. Byte[] sourceDocument = default(Byte[]); using (FileStream inputStream = new FileStream(fileName, FileMode.Open)) { sourceDocument = new Byte[inputStream.Length]; inputStream.Read(sourceDocument, 0, sourceDocument.Length); } // This dictionary is used for the mail merge operation. Dictionary <String, Object> dictionary = new Dictionary <string, object>(); dictionary.Add("PayeeCompanyName", "Central Banking"); dictionary.Add("PayeeAddress1", "6 Bay Place"); dictionary.Add("PayeeAddress2", null); dictionary.Add("PayeeCity", "Huntington"); dictionary.Add("PayeeProvinceAbbreviation", "NY"); dictionary.Add("PayeePostalCode", "11743"); dictionary.Add("DebtorLastName", "Franken"); dictionary.Add("DebtorFirstName", "Al"); dictionary.Add("DebtorAddress1", "203 Huntington Avenue"); dictionary.Add("DebtorAddress2", "Apt. 2"); dictionary.Add("DebtorCity", "Boston"); dictionary.Add("DebtorProvinceAbbreviation", "MA"); dictionary.Add("DebtorPostalCode", "02109"); dictionary.Add("DebtorSalutation", "Mr."); dictionary.Add("DebtorOriginalAccountNumber", "2033 2838 8281 3822"); dictionary.Add("AccountBalance", 3402.22M); dictionary.Add("SettlementAmount", 1500.00M); dictionary.Add("PaymentStartDate", DateTime.Parse("7/31/2009")); // Merge the dictionary with the contents of the loaded document and evaluate all the fields. MailMerge mailMerge = new MailMerge(); MemoryStream memoryStream = mailMerge.CreateDocument(sourceDocument, dictionary); // Write the generated data to the output PDF file. using (FileStream outputStream = new FileStream("../../document.pdf", FileMode.OpenOrCreate)) { Byte[] outputBuffer = memoryStream.ToArray(); outputStream.Write(outputBuffer, 0, outputBuffer.Length); } } catch (Exception exception) { Console.WriteLine("{0}, {1}", exception.Message, exception.StackTrace); } }
public static void ReplaceMailMergeFields(string dir, string msWordFileName, IMergeFieldsProvider domainObject, string fileSuffix) { object docName = msWordFileName; object missing = Missing.Value; // Hide MS Word's window. var app = new Application { Visible = false } as _Application; var path = dir + docName as object; _Document doc = app.Documents.Open(ref path); MailMerge mailMerge = doc.MailMerge; // Try to find the field name. foreach (MailMergeField f in mailMerge.Fields) { // Assuming the field code is: MERGEFIELD "mailMergeFieldName" string mailMergeFieldName = f.Code.Text; string newValue = domainObject.GetContentsFor(mailMergeFieldName); if (!string.IsNullOrWhiteSpace(newValue)) { f.Select(); // Replace selected field with supplied value. app.Selection.TypeText(newValue); } } // Save changes and close MS Word. object newName = dir + msWordFileName.Replace(".docx", "") + "-" + fileSuffix + ".docx"; doc.SaveAs2(ref newName); object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref saveChanges, ref missing, ref missing); app.Quit(ref missing, ref missing, ref missing); }
public void MergeFieldsInWordDoc(string sourcePath, IDocumentMergeFieldsProvider sourceObject, string destinationPath) { object missing = Missing.Value; // Hide MS Word's window. Application app = new Application { Visible = false }; var path = sourcePath as object; _Document doc = app.Documents.Open(ref path); MailMerge mailMerge = doc.MailMerge; foreach (MailMergeField f in mailMerge.Fields) { // Assuming the field code is: MERGEFIELD "mailMergeFieldName" string fieldName = f.Code.Text; string newValue = GetValueForMergeField(sourceObject, fieldName); if (!string.IsNullOrWhiteSpace(newValue)) { f.Select(); // Replace selected field with supplied value. app.Selection.TypeText(newValue); } } // Save changes and close MS Word. object newName = destinationPath as object; doc.SaveAs2(ref newName); object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; doc.Close(ref saveChanges, ref missing, ref missing); //TODO: Fix - check with Stef //app.Quit(ref missing, ref missing, ref missing); }
private void MergeTemplate(string templateName, string JsonData) { // creating a new ServerTextControl and MailMerge class using (ServerTextControl tx = new ServerTextControl()) { tx.Create(); MailMerge mailMerge = new MailMerge(); mailMerge.TextComponent = tx; // load the template mailMerge.LoadTemplate(Server.MapPath("templates/" + templateName), FileFormat.InternalUnicodeFormat); // create a new DataSet object DataSet ds = new DataSet(); XmlDocument doc; // convert the JSON string to an XML document // object using Newtonsoft.Json try { doc = JsonConvert.DeserializeXmlNode(JsonData); lblError.Visible = false; } catch (Exception exc) { lblError.Visible = true; lblError.Text = exc.Message; DocumentViewer1.Visible = false; return; } // convert the XML to a DataSet XmlNodeReader reader = new XmlNodeReader(doc); ds.ReadXml(reader, XmlReadMode.Auto); // merge the template with the DataSet mailMerge.Merge(ds.Tables[0]); // load the resulting document into the DocumentViewer byte[] data; mailMerge.SaveDocumentToMemory(out data, BinaryStreamType.InternalUnicodeFormat, null); DocumentViewer1.LoadDocumentFromMemory(data, FileFormat.InternalUnicodeFormat); } }
public ActionResult LettersFiles() { var result = new List <ChartViewModel>(); string pathName = Server.MapPath(@"../SpecialData/HrLetters"); string ListPath = Server.MapPath("/App_Data/ContractsList.mdb"); if (User.Identity.RTL()) { ListPath = Server.MapPath("/App_Data/arContractsList.mdb"); } if (Directory.Exists(pathName)) { var Files = Directory.GetFiles(pathName); foreach (var item in Files) { FileInfo fl = new FileInfo(item); using (WordprocessingDocument docPKG = WordprocessingDocument.Open(item, true)) { MailMerge mymerge = docPKG.MainDocumentPart.DocumentSettingsPart.Settings.Elements <MailMerge>().FirstOrDefault(); if (mymerge != null) { mymerge.ConnectString = new ConnectString() { Val = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" + ListPath + ";Mode=Read;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Engine Type=6;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False" }; var Relation = docPKG.MainDocumentPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource", new Uri(ListPath)); mymerge.DataSourceReference = new DataSourceReference() { Id = Relation.Id }; } docPKG.Save(); docPKG.Dispose(); } var f = new ChartViewModel() { category = fl.Name, color = "/SpecialData/HrLetters/" + fl.Name }; result.Add(f); } } return(PartialView("_ContractFiles", result)); }
static void Main(string[] args) { string template = @"[if [Min] == [Max]][~true]"; Console.WriteLine(template); Console.WriteLine("\n------------------\n"); var data = new Dictionary <string, object>() { { "Min", 100 }, { "Max", 100 } }; string result = MailMerge.Merge(template, data); Console.WriteLine(result); Console.ReadLine(); }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); // Create template message. MailMessage template = new MailMessage("*****@*****.**"); template.Subject = "%FirstName%, check our new offer!"; template.BodyHtml = @"<div> Dear <strong>%Title% %LastName%</strong><br/><br/> Check out our new offer on this <a href=""%link%"">link</a>.<br/> <span style=""color:red;font-size:90%"">Visit us today and get additional %discount%% discount!</span><br/><br/> Sincerely Yours,<br/> Special Store<br/><br/> <span style=""color:gray;font-size:80%"">This email was sent to <a href=""mailto:%To%"">%To%</a>.</span> </div>"; // Create data source. DataTable data = new DataTable(); data.Columns.Add("To", typeof(string)); data.Columns.Add("Title", typeof(string)); data.Columns.Add("FirstName", typeof(string)); data.Columns.Add("LastName", typeof(string)); data.Columns.Add("Discount", typeof(int)); data.Columns.Add("Link", typeof(string)); // Fill data source with some data. data.Rows.Add("*****@*****.**", "Mr.", "John", "Doe", 10, "https://example.com/check.html?name=John"); data.Rows.Add("*****@*****.**", "Mrs.", "Jane", "Doe", 20, "https://example.com/check.html?name=Jane"); data.Rows.Add("*****@*****.**", "Mr.", "Joe", "Unknown", 15, "https://example.com/check.html?name=Joe"); // Perform mail merge operation. IList <MailMessage> messages = MailMerge.Merge(template, data); // Save mail messages. for (int i = 0; i < messages.Count; i++) { messages[i].Save($"Message_{i}.eml"); } }
private void textControl1_Loaded(object sender, RoutedEventArgs e) { textControl1.Focus(); //dsAddresses = new DataSet(); //dsAddresses.ReadXml("data2.xml"); mailMerge1 = new MailMerge(); mailMerge1.TextComponent = textControl1; TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings(); ls.ApplicationFieldFormat = TXTextControl.ApplicationFieldFormat.MSWord; ls.LoadSubTextParts = true; //textControl1.Load("333.docx", StreamType.WordprocessingML, ls); CommClient.MedicalRecord medicalRecordClient = new CommClient.MedicalRecord(); CommContracts.MedicalRecord medicalRecord = medicalRecordClient.GetMedicalRecord(7); textControl1.Load(medicalRecord.ContentXml, TXTextControl.StringStreamType.RichTextFormat); }
void ProcessFile(string filename, int cnt) { progress = Math.Abs((100 / filer.Count) * cnt); if (filename.Contains("~")) return; #region Kverk word-prosesser som henger.. // kill prosesser som ikke skal være der... Process[] procs = Process.GetProcessesByName("WINWORD"); if (procs.Length > 1) foreach (Process process in procs) { process.Kill(); } #endregion try { if (wordApplication.Documents.Count > 0) { procs = Process.GetProcessesByName("WINWORD"); foreach (Process process in procs) process.Kill(); } } catch { } try { string title = wordApplication.Caption; } catch { LogFromThread(progress, "Oppretter word-app.." + Environment.NewLine); CreateApplication(); } DateTime start = DateTime.Now; try { LogFromThread(progress, "(" + (cnt+1).ToString() + " av " + filer.Count + ") ..." + filename.Substring(filename.Length - 15) + " - "); #region Sjekk på tom fil if (new FileInfo(filename).Length == 0) // empty file -> continue.. { FileLog.LogWrite("Filen " + filename + " var tom. Hoppet over.", FileLog.logType.Info); LogFromThread(progress, " Fil er tom. Går videre. " + Environment.NewLine); empty++; return; } #endregion #region Opprettelse av filnavn for pdf string outfile = string.Empty; ut_sti = ut_sti.ToLower(); string tmpFil = Path.GetFileName(filename); if (ut_sti == "") outfile = Path.ChangeExtension(filename, ".pdf"); else { string newPath = Path.GetFullPath(filename).Replace(inn_sti, ut_sti); newPath = Path.ChangeExtension(newPath, ".pdf"); outfile = newPath; } if (File.Exists(outfile) && !chkOverwrite.Checked) // file exists, and not overwrite -> continue.. { LogFromThread(progress, " Eksisterer. Går videre. " + Environment.NewLine); exists++; return; } else if (File.Exists(outfile)) { LogFromThread(progress, " Overskriver. "); } #endregion #region Åpning av fil og passordhåndtering string pwMatch = ""; string key = Path.GetFileName(filename); if (passwordList.ContainsKey(key.ToLower())) { pwMatch = passwordList[key.ToLower()].ToString(); } if (pwMatch != "") { // åpne kilde med passord try { wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); if (wordDocument.ProtectionType != WdProtectionType.wdNoProtection) wordDocument.Protect(WdProtectionType.wdNoProtection, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); passwordprotected++; currentPassword = pwMatch; } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } LogFromThread(progress, " Passord:" + pwMatch); } else { try { // åpne kilde uten passord. wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, 28591, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } } Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (filtype == "txt") { wordDocument.PageSetup.LeftMargin = 1.0f; wordDocument.PageSetup.RightMargin = 1.0f; wordDocument.PageSetup.TopMargin = 1.0f; wordDocument.PageSetup.BottomMargin = 1.0f; wordApplication.Selection.Document.Content.Select(); wordApplication.Selection.Font.Shrink(); wordApplication.Selection.Font.Shrink(); } #endregion #region Ekspandering av sub-dokumenter try { //Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (wordDocument.IsMasterDocument) { bool missingFiles = false; foreach (Subdocument s in wordDocument.Subdocuments) { retry: //stygt.. men dog.. if (!File.Exists(s.Name)) { string p = Directory.GetParent(Path.GetDirectoryName(s.Name)).ToString(); string[] files = Directory.GetFiles(p, Path.GetFileName(s.Name)); if (files.Count() == 0) { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. FileNotFound ved sjekk av " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant ikke subdokumenter '" + s.Name + "'. Går videre." + Environment.NewLine); } else if (files.Count() == 1) { File.Copy(files[0], s.Name); FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Subdokument funnet på annen plassering. kopiert til " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant subdokument ('" + s.Name + "' plassert på '" + files[0] + "') med feil plassering. Kopiert til riktig." + Environment.NewLine); goto retry; } else { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Ett eller flere subdokumenter mangler. For mange matchende alternativer funnet.", FileLog.logType.Info); LogFromThread(progress, "For mange matchende alternative subdokumenter funnet. Går videre." + Environment.NewLine); } } } if (!missingFiles) { int retryCounter = 0; retry: //stygt.. men dog.. try { retryCounter++; wordDocument.ActiveWindow.ActivePane.View.Type = WdViewType.wdOutlineView; wordApplication.ActiveWindow.View.Type = WdViewType.wdMasterView; Thread.Sleep(int.Parse(txtWaitProcess.Text)); wordDocument.Subdocuments.Expanded = true; Thread.Sleep(int.Parse(txtWaitProcess.Text)); } catch (Exception ex) { if (retryCounter < 10) { logg1.Log(".", Logg.LogType.Info); goto retry; } FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Feil ved ekspansjon. Error:" + ex.Message, FileLog.logType.Info); LogFromThread(progress, " Feil ved eksp. av subdoks. Går videre." + Environment.NewLine); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } } catch (Exception ex) { FileLog.LogWrite("Filen '..." + filename.Substring(filename.Length - 15) + "' ble ikke konvertert. Subdokument-feil." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); LogFromThread(progress, "...Feil oppstått " + ex.Message + Environment.NewLine); error++; CloseDocument(); return; } #endregion #region MailMerge string mergeFile = Path.ChangeExtension(filename.ToLower(), "rtf"); if (mergeFile != filename.ToLower() && File.Exists(mergeFile)) { // Det finnes en korresponderende rtf-fil. Sannsynligvis en data-merge-fil. LogFromThread(progress, " Fletter... "); mm = wordDocument.MailMerge; string mergefil = Path.ChangeExtension(filename.ToLower(), "rtf"); mm.OpenDataSource(mergefil, ref paramMissing, false, true, ref paramMissing, false, currentPassword, currentPassword); mm.Destination = WdMailMergeDestination.wdSendToNewDocument; mm.Execute(); Thread.Sleep(4000); if (!saveDocument(wordApplication.Documents[1], outfile)) // lagre dok i nytt vindu { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } else { // Export it in the specified format. if (!saveDocument(wordDocument, outfile)) { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } #endregion Thread.Sleep(int.Parse(txtWaitProcess.Text)); // Close and release the Document object. CloseDocument(); TimeSpan elapsed = DateTime.Now - start; LogFromThread(progress, " (" + elapsed.Seconds + "." + elapsed.Milliseconds + " s)" + Environment.NewLine); } catch (Exception ex) { error++; FileLog.LogWrite("FEIL! Feil ved konvertering av " + filename + "." + Environment.NewLine + "Feilen var :" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, FileLog.logType.Info); LogFromThread(progress, "FEIL! Feil ved konvertering av " + filename.Substring(filename.Length - 15) + "." + Environment.NewLine + "Se info.log for beskrivelse." + Environment.NewLine); CloseDocument(); CloseApplication(); } }
protected void Word(int rpid, ReportCriteria[] rpParam = null, CUSTOMRP.BLL.AppHelper.QueryParamsObject[] qpParam = null) { CUSTOMRP.Model.REPORT myReport = WebHelper.bllReport.GetModel(me.ID, rpid); string WordFilePath = null; if ((myReport.WordFile != null) && (File.Exists(g_Config["WordTemplatePath"] + myReport.WordFile.WordFileName))) { WordFilePath = myReport.WordFile.WordFileName; } else { CUSTOMRP.Model.WORDTEMPLATE template = WebHelper.bllWORDTEMPLATE.GetModelByReportID(me.ID, myReport.ID, me.ID); if (File.Exists(g_Config["WordTemplatePath"] + template.TemplateFileName)) { WordFilePath = template.TemplateFileName; } else { Context.Response.Write(String.Format("<script type=\"text/javascript\">alert(\"{0}\");</script>", AppNum.ErrorMsg.filenotfounderror)); Context.Response.End(); return; } } CUSTOMRP.Model.SOURCEVIEW mySV = WebHelper.bllSOURCEVIEW.GetModel(me.ID, myReport.SVID); string[] colnames; switch (mySV.SourceType) { case CUSTOMRP.Model.SOURCEVIEW.SourceViewType.StoredProc: { colnames = CUSTOMRP.BLL.AppHelper.GetColumnNamesForStoredProc(me.ID, me.DatabaseNAME, mySV.TBLVIEWNAME); } break; default: { colnames = CUSTOMRP.BLL.AppHelper.GetColumnNamesForTblView(me.ID, me.DatabaseNAME, mySV.TBLVIEWNAME); } break; } //just print .no need save to database. List <string> rpcr = new List <string>(); List <string> comments = new List <string>(); List <string> avgs = new List <string>(); List <string> sums = new List <string>(); List <string> groups = new List <string>(); List <string> subtotal = new List <string>(); List <string> subavg = new List <string>(); List <string> subcount = new List <string>(); List <string> count = new List <string>(); //v1.2.0 - Cheong - 2016/07/04 - Add option to hide duplicate items //DataTable dt = CUSTOMRP.BLL.AppHelper.getDataForReport(ref comments, ref avgs, ref sums, ref groups, ref subtotal, ref subavg, ref subcount, ref count, me, rpid, true, rpParam); DataTable dt = CUSTOMRP.BLL.AppHelper.getDataForReport(me.ID, ref comments, ref avgs, ref sums, ref groups, ref subtotal, ref subavg, ref subcount, ref count, me, rpid, myReport.fHideDuplicate, rpParam, QueryParamsToSqlParams(qpParam)); this.p_fSuppressRender = true; string path = g_Config["WordTemplatePath"] + WordFilePath; string downloadFilename = myReport.REPORTNAME.Replace(' ', '_') + ".docx"; // Not calling downloadfile because this function need not write on disk using (MemoryStream filestream = MailMerge.PerformMailMergeFromTemplate(path, dt, colnames)) { Context.Response.ContentType = "application/octet-stream"; //Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + downloadFilename + "\""); Context.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"; filename*=utf-8''{1}", downloadFilename, HttpUtility.UrlPathEncode(downloadFilename))); Context.Response.AddHeader("Content-Length", filestream.Length.ToString()); byte[] fileBuffer = new byte[filestream.Length]; filestream.Read(fileBuffer, 0, (int)filestream.Length); //CA2202 //filestream.Close(); Context.Response.BinaryWrite(fileBuffer); Context.Response.End(); } }
//run protected void btnPrint_Click(object sender, EventArgs e) { string WordFilePath = null; string downloadFilename = null; if ((myReport != null) && (myReport.WordFile != null) && (File.Exists(g_Config["WordTemplatePath"] + myReport.WordFile.WordFileName))) { WordFilePath = myReport.WordFile.WordFileName; downloadFilename = myReport.WordFile.OrigFileName; } else { CUSTOMRP.Model.WORDTEMPLATE template = WebHelper.bllWORDTEMPLATE.GetModelByReportID(me.ID, myReport.ID, me.ID); if (template != null) { if (File.Exists(g_Config["WordTemplatePath"] + template.TemplateFileName)) { WordFilePath = template.TemplateFileName; downloadFilename = myReport.RPTITLE + ".docx"; } } } if (WordFilePath == null) { Response.Write(String.Format("<script type=\"text/javascript\">alert(\"{0}\")</script>", AppNum.ErrorMsg.filenotfounderror)); return; } string strSqlColumn, strSqlPlus, strSqlCriteria, strSqlSortOn; getSql(ref rpcr, out strSqlColumn, out strSqlCriteria, out strSqlPlus, out strSqlSortOn); if (String.IsNullOrWhiteSpace(strSqlColumn)) { #region Get Column Names string[] colnames = null; CUSTOMRP.Model.SOURCEVIEW sv = WebHelper.bllSOURCEVIEW.GetModel(me.ID, myReport.SVID); List <CUSTOMRP.Model.SOURCEVIEWCOLUMN> svc = WebHelper.bllSOURCEVIEWCOLUMN.GetModelsForSourceView(me.ID, sv.ID, true).OrderBy(x => x.DisplayName).ToList(); switch (sv.SourceType) { case CUSTOMRP.Model.SOURCEVIEW.SourceViewType.View: case CUSTOMRP.Model.SOURCEVIEW.SourceViewType.Table: { try { columninfos = CUSTOMRP.BLL.AppHelper.GetColumnInfoForTblView(me.ID, me.DatabaseNAME, sv.TBLVIEWNAME); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); columninfos = new List <CUSTOMRP.Model.ColumnInfo>(); this.lblJavascript.Text = String.Format("<script type=\"text/javascript\">alert('Error in retrieving columns for [{0}]. Please check view defination.');</script>", sv.TBLVIEWNAME); } if (svc == null) { colnames = CUSTOMRP.BLL.AppHelper.GetColumnNamesForTblView(me.ID, me.DatabaseNAME, sv.TBLVIEWNAME); // Filter result to only columns that is requested columninfos = columninfos.Where(x => colnames.Contains(x.ColName)).ToList(); } } break; case CUSTOMRP.Model.SOURCEVIEW.SourceViewType.StoredProc: { try { columninfos = CUSTOMRP.BLL.AppHelper.GetColumnInfoForStoredProc(me.ID, me.DatabaseNAME, sv.ID); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); columninfos = new List <CUSTOMRP.Model.ColumnInfo>(); this.lblJavascript.Text = String.Format("<script type=\"text/javascript\">alert('Error in retrieving columns for [{0}]. Please check stored proc defination.');</script>", sv.TBLVIEWNAME); } if (svc == null) { colnames = CUSTOMRP.BLL.AppHelper.GetColumnNamesForStoredProc(me.ID, me.DatabaseNAME, sv.TBLVIEWNAME); // Filter result to only columns that is requested columninfos = columninfos.Where(x => colnames.Contains(x.ColName)).ToList(); } } break; } if (svc.Count == 0) { // do sorting columninfos = columninfos.OrderBy(p => p.ColName).ToList(); } else { columninfos = (from c in columninfos join s in svc.Where(x => x.ColumnType == CUSTOMRP.Model.SOURCEVIEWCOLUMN.ColumnTypes.Normal) on c.ColName equals s.COLUMNNAME into lefts from s in lefts.DefaultIfEmpty() where (s == null || !s.HIDDEN) orderby s.DisplayName, c.ColName select new CUSTOMRP.Model.ColumnInfo() { ColName = c.ColName, DisplayName = (s == null || String.IsNullOrEmpty(s.DISPLAYNAME)) ? c.ColName : s.DISPLAYNAME, // no need to show actual column name here if DisplayName is supplied DataType = c.DataType, }).ToList(); } strSqlColumn = String.Join(",", columninfos.Select(x => "[" + x.ColName + "]").ToArray()); #endregion } if (strSqlColumn != "") { var sqlParams_queryParams = new List <SqlParameter>(); foreach (var x in container.queryParams) { switch (x.SqlType) { case "bit": sqlParams_queryParams.Add(new SqlParameter() { ParameterName = "@QueryParam_" + x.ParamName, SqlDbType = SqlDbType.Bit, Value = int.Parse(x.Value) }); break; case "int": sqlParams_queryParams.Add(new SqlParameter() { ParameterName = "@QueryParam_" + x.ParamName, SqlDbType = SqlDbType.Int, Value = int.Parse(x.Value) }); break; case "date": sqlParams_queryParams.Add(new SqlParameter() { ParameterName = "@QueryParam_" + x.ParamName, SqlDbType = SqlDbType.Date, Value = x.Value }); break; case "datetime": sqlParams_queryParams.Add(new SqlParameter() { ParameterName = "@QueryParam_" + x.ParamName, SqlDbType = SqlDbType.DateTime, Value = x.Value }); break; case "varchar": sqlParams_queryParams.Add(new SqlParameter() { ParameterName = "@QueryParam_" + x.ParamName, Size = -1, SqlDbType = SqlDbType.VarChar, Value = x.Value }); break; case "nvarchar": sqlParams_queryParams.Add(new SqlParameter() { ParameterName = "@QueryParam_" + x.ParamName, Size = -1, SqlDbType = SqlDbType.NVarChar, Value = x.Value }); break; } } this.rpdt = CUSTOMRP.BLL.AppHelper.getDataForReport(me.ID, myReport.SVID, me.DatabaseNAME, strSqlColumn, strSqlPlus, strSqlCriteria, strSqlSortOn, myReport.fHideDuplicate, sqlParams_queryParams); if (rpdt != null) { if (container.Format == 1) { Server.Transfer("htmlexport.aspx?active=html", true); } else if (container.Format == 0) { string path = g_Config["WordTemplatePath"] + WordFilePath; string fileName = container.ReportName + ".docx"; using (MemoryStream filestream = MailMerge.PerformMailMergeFromTemplate(path, rpdt, columninfos.Select(x => x.DisplayName).ToArray())) { Context.Response.ContentType = "application/octet-stream"; //Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + downloadFilename + "\""); Context.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"; filename*=utf-8''{1}", downloadFilename, HttpUtility.UrlPathEncode(downloadFilename))); Context.Response.AddHeader("Content-Length", filestream.Length.ToString()); byte[] fileBuffer = new byte[filestream.Length]; filestream.Read(fileBuffer, 0, (int)filestream.Length); //CA2202 //filestream.Close(); Context.Response.BinaryWrite(fileBuffer); Context.Response.End(); } } } else { this.lblJavascript.Text = String.Format("<script type=\"text/javascript\">alert(\"{0}\");</script>", "Empty data!"); } } else { this.lblJavascript.Text = String.Format("<script type=\"text/javascript\">alert(\"{0}\");</script>", "Zero Column,please check!"); } }
void ProcessFile(string filename, int cnt) { progress = Math.Abs((100 / filer.Count) * cnt); if (filename.Contains("~")) { return; } #region Kverk word-prosesser som henger.. // kill prosesser som ikke skal være der... Process[] procs = Process.GetProcessesByName("WINWORD"); if (procs.Length > 1) { foreach (Process process in procs) { process.Kill(); } } #endregion try { if (wordApplication != null) { if (wordApplication.Documents.Count > 0) { procs = Process.GetProcessesByName("WINWORD"); foreach (Process process in procs) { process.Kill(); } } } } catch { } try { if (wordApplication != null) { string title = wordApplication.Caption; } else { LogFromThread(progress, "Oppretter word-app.." + Environment.NewLine); CreateApplication(); } } catch { LogFromThread(progress, "Oppretter word-app.." + Environment.NewLine); CreateApplication(); } DateTime start = DateTime.Now; try { //LogFromThread(progress, "(" + (cnt+1).ToString() + " av " + filer.Count + ") ..." + filename.Substring(filename.Length - 15) + " - "); #region Sjekk på tom fil if (new FileInfo(filename).Length == 0) // empty file -> continue.. { FileLog.LogWrite("Filen " + filename + " var tom. Hoppet over.", FileLog.logType.Info); LogFromThread(progress, " Fil er tom. Går videre. " + Environment.NewLine); empty++; return; } #endregion #region Opprettelse av filnavn for pdf string outfile = string.Empty; ut_sti = ut_sti.ToLower(); string tmpFil = Path.GetFileName(filename); if (ut_sti == "") { outfile = Path.ChangeExtension(filename, ".pdf"); } else { string newPath = Path.GetFullPath(filename).Replace(inn_sti, ut_sti); newPath = Path.ChangeExtension(newPath, ".pdf"); outfile = newPath; } if (File.Exists(outfile) && !chkOverwrite.Checked) // file exists, and not overwrite -> continue.. { LogFromThread(progress, " Eksisterer. Går videre. " + Environment.NewLine); exists++; return; } else if (File.Exists(outfile)) { LogFromThread(progress, " Overskriver. "); } #endregion #region Åpning av fil og passordhåndtering string pwMatch = ""; string key = Path.GetFileName(filename); if (passwordList.ContainsKey(key.ToLower())) { pwMatch = passwordList[key.ToLower()].ToString(); } if (pwMatch != "") { // åpne kilde med passord try { wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, pwMatch, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); if (wordDocument.ProtectionType != WdProtectionType.wdNoProtection) { wordDocument.Protect(WdProtectionType.wdNoProtection, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); } passwordprotected++; currentPassword = pwMatch; } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); StreamWriter sw = File.CreateText(outfile + ".errorlog"); sw.WriteLine("Fant ingen måte å åpne fila på. Enten er fila skadet, passord manglet i passordfil, eller en annen feil har oppstått:" + Environment.NewLine + ex.Message); sw.Close(); if (chkCopyOriginalOnError.Checked) { File.Copy(filename, Path.Combine(Path.GetDirectoryName(outfile), Path.GetFileName(filename))); } FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } LogFromThread(progress, " Passord:" + pwMatch); } else { try { // åpne kilde med passord "mypass" to force continue. wordDocument = wordApplication.Documents.OpenNoRepairDialog( filename, ref paramMissing, false, ref paramMissing, "mypass", ref paramMissing, ref paramMissing, "mypass", ref paramMissing, ref paramMissing, 28591, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); } catch (Exception ex) { LogFromThread(progress, "Finner ingen måte å åpne dokumentet på. Går videre. " + Environment.NewLine); FileLog.LogWrite("Fant ingen måte å åpne '" + filename + "' på. Hopper videre." + ex.Message, FileLog.logType.Info); StreamWriter sw = File.CreateText(outfile + ".errorlog"); sw.WriteLine("Fant ingen måte å åpne fila på. Enten er fila skadet, passord manglet i passordfil, eller en annen feil har oppstått:" + Environment.NewLine + ex.Message); sw.Close(); if (chkCopyOriginalOnError.Checked) { File.Copy(filename, Path.Combine(Path.GetDirectoryName(outfile), Path.GetFileName(filename))); } FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; return; } } Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (filtype == "txt") { wordDocument.PageSetup.LeftMargin = 1.0f; wordDocument.PageSetup.RightMargin = 1.0f; wordDocument.PageSetup.TopMargin = 1.0f; wordDocument.PageSetup.BottomMargin = 1.0f; wordApplication.Selection.Document.Content.Select(); wordApplication.Selection.Font.Shrink(); wordApplication.Selection.Font.Shrink(); } #endregion #region Ekspandering av sub-dokumenter try { //Thread.Sleep(int.Parse(txtWaitProcess.Text)); if (wordDocument.IsMasterDocument) { bool missingFiles = false; foreach (Subdocument s in wordDocument.Subdocuments) { retry: //stygt.. men dog.. if (!File.Exists(s.Name)) { string p = Directory.GetParent(Path.GetDirectoryName(s.Name)).ToString(); string[] files = Directory.GetFiles(p, Path.GetFileName(s.Name)); if (files.Count() == 0) { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. FileNotFound ved sjekk av " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant ikke subdokumenter '" + s.Name + "'. Går videre." + Environment.NewLine); } else if (files.Count() == 1) { File.Copy(files[0], s.Name); FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Subdokument funnet på annen plassering. kopiert til " + s.Name + ".", FileLog.logType.Info); LogFromThread(progress, " Fant subdokument ('" + s.Name + "' plassert på '" + files[0] + "') med feil plassering. Kopiert til riktig." + Environment.NewLine); goto retry; } else { missingFiles = true; FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Ett eller flere subdokumenter mangler. For mange matchende alternativer funnet.", FileLog.logType.Info); LogFromThread(progress, "For mange matchende alternative subdokumenter funnet. Går videre." + Environment.NewLine); } } } if (!missingFiles) { int retryCounter = 0; retry: //stygt.. men dog.. try { retryCounter++; wordDocument.ActiveWindow.ActivePane.View.Type = WdViewType.wdOutlineView; wordApplication.ActiveWindow.View.Type = WdViewType.wdMasterView; Thread.Sleep(int.Parse(txtWaitProcess.Text)); wordDocument.Subdocuments.Expanded = true; Thread.Sleep(int.Parse(txtWaitProcess.Text)); } catch (Exception ex) { if (retryCounter < 10) { logg1.Log(".", Logg.LogType.Info); goto retry; } FileLog.LogWrite(filename.Substring(filename.Length - 15) + " ble ikke konvertert. Feil ved ekspansjon. Error:" + ex.Message, FileLog.logType.Info); LogFromThread(progress, " Feil ved eksp. av subdoks. Går videre." + Environment.NewLine); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; CloseDocument(); return; } } } catch (Exception ex) { FileLog.LogWrite("Filen '..." + filename.Substring(filename.Length - 15) + "' ble ikke konvertert. Subdokument-feil." + ex.Message, FileLog.logType.Info); FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); LogFromThread(progress, "...Feil oppstått " + ex.Message + Environment.NewLine); error++; CloseDocument(); return; } #endregion #region MailMerge string mergeFile = Path.ChangeExtension(filename.ToLower(), "rtf"); if (mergeFile != filename.ToLower() && File.Exists(mergeFile)) { // Det finnes en korresponderende rtf-fil. Sannsynligvis en data-merge-fil. LogFromThread(progress, " Fletter... "); mm = wordDocument.MailMerge; string mergefil = Path.ChangeExtension(filename.ToLower(), "rtf"); mm.OpenDataSource(mergefil, ref paramMissing, false, true, ref paramMissing, false, currentPassword, currentPassword); mm.Destination = WdMailMergeDestination.wdSendToNewDocument; mm.Execute(); Thread.Sleep(4000); if (!saveDocument(wordApplication.Documents[1], outfile)) // lagre dok i nytt vindu { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } } else { // Export it in the specified format. if (!saveDocument(wordDocument, outfile)) { FileLog.LogWrite(filename, FileLog.logType.Filliste_ikkekonvertert); error++; } else { FileLog.LogWrite(filename, FileLog.logType.Filliste_konvertert); } } #endregion Thread.Sleep(int.Parse(txtWaitProcess.Text)); // Close and release the Document object. CloseDocument(); TimeSpan elapsed = DateTime.Now - start; LogFromThread(progress, " (" + elapsed.Seconds + "." + elapsed.Milliseconds + " s)" + Environment.NewLine); } catch (Exception ex) { error++; FileLog.LogWrite("FEIL! Feil ved konvertering av " + filename + "." + Environment.NewLine + "Feilen var :" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, FileLog.logType.Info); LogFromThread(progress, "FEIL! Feil ved konvertering av " + filename.Substring(filename.Length - 15) + "." + Environment.NewLine + "Se info.log for beskrivelse." + Environment.NewLine); CloseDocument(); CloseApplication(); } }
static void Main(string[] args) { if (args == null || args.Length < 2) { return; } // get read and write pipe handles // note: Roles are now reversed from how the other process is passing the handles in string pipeWriteHandle = args[0]; string pipeReadHandle = args[1]; // create 2 anonymous pipes (read and write) for duplex communications // (each pipe is one-way) using (var pipeRead = new AnonymousPipeClientStream(PipeDirection.In, pipeReadHandle)) using (var pipeWrite = new AnonymousPipeClientStream(PipeDirection.Out, pipeWriteHandle)) { try { var lsValues = new List <string>(); // get message from other process using (var sr = new StreamReader(pipeRead)) { string sTempMessage; // wait for "sync message" from the other process do { sTempMessage = sr.ReadLine(); } while (sTempMessage == null || !sTempMessage.StartsWith("SYNC")); // read until "end message" from the server while ((sTempMessage = sr.ReadLine()) != null && !sTempMessage.StartsWith("END")) { lsValues.Add(sTempMessage); } } // send value to calling process using (var sw = new StreamWriter(pipeWrite)) { sw.AutoFlush = true; // send a "sync message" and wait for the calling process to receive it sw.WriteLine("SYNC"); pipeWrite.WaitForPipeDrain(); // wait here PassingObject dataObject = JsonConvert.DeserializeObject <PassingObject>(lsValues[0]); ReturningObject returnObject = new ReturningObject(); try { // create a new ServerTextControl for the document processing using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) { tx.Create(); tx.Load(dataObject.Document, TXTextControl.BinaryStreamType.InternalUnicodeFormat); using (MailMerge mailMerge = new MailMerge()) { mailMerge.TextComponent = tx; mailMerge.MergeJsonData(dataObject.Data.ToString()); } byte[] data; tx.Save(out data, TXTextControl.BinaryStreamType.AdobePDF); returnObject.Document = data; } sw.WriteLine(JsonConvert.SerializeObject(returnObject)); sw.WriteLine("END"); } catch (Exception exc) { returnObject.Error = exc.Message; sw.WriteLine(JsonConvert.SerializeObject(returnObject)); sw.WriteLine("END"); } } } catch { } } }
protected override void DoMergeTypeSetup(ComObjectManager com, MailMerge mailMerge) { mailMerge.Destination = WdMailMergeDestination.wdSendToNewDocument; }
public ActionResult CheckDocs(HttpPostedFileBase ContractTempl) { string Message = "Exist"; string[] arr = { "docx", "doc" }; bool MoveOne = true; string Temp = "../SpecialData/TempFolder"; string ListPath = Server.MapPath("/App_Data/ContractsList.mdb"); if (User.Identity.RTL()) { ListPath = Server.MapPath("/App_Data/arContractsList.mdb"); } if (ContractTempl != null) { if (!arr.Any(f => ContractTempl.FileName.EndsWith(f, StringComparison.OrdinalIgnoreCase))) { MoveOne = false; } else { if (!Directory.Exists(Server.MapPath(Temp))) { Directory.CreateDirectory(Server.MapPath(Temp)); } var Files = Directory.GetFiles(Server.MapPath(Temp)); foreach (var item in Files) { System.IO.File.Delete(item); } string Name = ContractTempl.FileName.Split('.')[0] + ".docx"; ContractTempl.SaveAs(Server.MapPath(Temp) + "/" + Name); using (WordprocessingDocument docPKG = WordprocessingDocument.Open(Server.MapPath(Temp) + "/" + Name, true)) { MailMerge mymerge = docPKG.MainDocumentPart.DocumentSettingsPart.Settings.Elements <MailMerge>().FirstOrDefault(); if (mymerge != null) { mymerge.ConnectString = new ConnectString() { Val = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" + ListPath + ";Mode=Read;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Engine Type=6;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False" }; var Relation = docPKG.MainDocumentPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource", new Uri(ListPath)); mymerge.DataSourceReference = new DataSourceReference() { Id = Relation.Id }; } docPKG.Save(); docPKG.Dispose(); } } } else { Message = "NoData"; } return(Json(new { Exist = Message, Move = MoveOne })); }
public ActionResult DownloadLetter(string ObjectName, string Language, string LetterName) { string Path = "/SpecialData/HrLetters/Uploaded/" + Language + "/" + LetterName; string pathName = Server.MapPath(Path); string ListPath = Server.MapPath("/App_Data/" + string.Format("{0}{1}", Language, ObjectName) + ".mdb"); if (!System.IO.File.Exists(ListPath)) { ListPath = Server.MapPath("/App_Data/" + string.Format("{0}{1}", "en-GB", ObjectName) + ".mdb"); } MailMergeViewmodel mail = new MailMergeViewmodel(); if (System.IO.File.Exists(pathName)) { FileInfo fl = new FileInfo(pathName); using (WordprocessingDocument docPKG = WordprocessingDocument.Open(pathName, true)) { MailMerge mymerge = docPKG.MainDocumentPart.DocumentSettingsPart.Settings.Elements <MailMerge>().FirstOrDefault(); var Relation = docPKG.MainDocumentPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource", new Uri(ListPath)); string Connectionval = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=" + ListPath + ";Mode=Read;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Engine Type=6;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False"; if (mymerge != null) { mymerge.ConnectString = new ConnectString() { Val = Connectionval }; mymerge.DataSourceReference = new DataSourceReference() { Id = Relation.Id }; } else { MailMerge m = new MailMerge(); string xmlnsw = @"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; m.MainDocumentType = new MainDocumentType(); m.MainDocumentType.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, "formatLetters")); m.LinkToQuery = new LinkToQuery(); m.DataType = new DataType(); m.DataType.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, "native")); m.ConnectString = new ConnectString(); m.ConnectString.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, Connectionval)); m.Query = new Query(); m.Query.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, "SELECT * FROM `Office Address List` ")); m.ViewMergedData = new ViewMergedData(); m.DataSourceObject = new DataSourceObject(); m.DataSourceObject.UdlConnectionString = new UdlConnectionString(); m.DataSourceObject.UdlConnectionString.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, Connectionval)); m.DataSourceObject.DataSourceTableName = new DataSourceTableName(); m.DataSourceObject.DataSourceTableName.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, "Office Address List")); m.DataSourceObject.ColumnDelimiter = new ColumnDelimiter(); m.DataSourceObject.ColumnDelimiter.SetAttribute(new DocumentFormat.OpenXml.OpenXmlAttribute("val", xmlnsw, "9")); if (m.DataSourceReference == null) { m.DataSourceReference = new DataSourceReference(); m.DataSourceReference.Id = Relation.Id; } m.ViewMergedData.Val = true; docPKG.MainDocumentPart.DocumentSettingsPart.Settings.InsertAt <MailMerge>(m, 0); } docPKG.Save(); docPKG.Dispose(); } mail.Path = Path; mail.Exist = true; } else { mail.Path = ""; mail.Exist = false; } return(Json(mail)); }
// Generates content of documentSettingsPart1. private void GenerateDocumentSettingsPart1Content(DocumentSettingsPart documentSettingsPart1) { Settings settings1 = new Settings() {MCAttributes = new MarkupCompatibilityAttributes() {Ignorable = "w14"}}; settings1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); settings1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office"); settings1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); settings1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"); settings1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml"); settings1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word"); settings1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); settings1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml"); settings1.AddNamespaceDeclaration("sl", "http://schemas.openxmlformats.org/schemaLibrary/2006/main"); Zoom zoom1 = new Zoom() {Percent = "100"}; ProofState proofState1 = new ProofState() {Spelling = ProofingStateValues.Clean, Grammar = ProofingStateValues.Clean}; MailMerge mailMerge1 = new MailMerge(); MainDocumentType mainDocumentType1 = new MainDocumentType() {Val = MailMergeDocumentValues.FormLetter}; DataType dataType1 = new DataType() {Val = MailMergeDataValues.TextFile}; ActiveRecord activeRecord1 = new ActiveRecord() {Val = -1}; mailMerge1.Append(mainDocumentType1); mailMerge1.Append(dataType1); mailMerge1.Append(activeRecord1); DefaultTabStop defaultTabStop1 = new DefaultTabStop() {Val = 720}; CharacterSpacingControl characterSpacingControl1 = new CharacterSpacingControl() {Val = CharacterSpacingValues.DoNotCompress}; HeaderShapeDefaults headerShapeDefaults1 = new HeaderShapeDefaults(); Ovml.ShapeDefaults shapeDefaults1 = new Ovml.ShapeDefaults() {Extension = V.ExtensionHandlingBehaviorValues.Edit, MaxShapeId = 6145}; headerShapeDefaults1.Append(shapeDefaults1); FootnoteDocumentWideProperties footnoteDocumentWideProperties1 = new FootnoteDocumentWideProperties(); FootnoteSpecialReference footnoteSpecialReference1 = new FootnoteSpecialReference() {Id = -1}; FootnoteSpecialReference footnoteSpecialReference2 = new FootnoteSpecialReference() {Id = 0}; footnoteDocumentWideProperties1.Append(footnoteSpecialReference1); footnoteDocumentWideProperties1.Append(footnoteSpecialReference2); EndnoteDocumentWideProperties endnoteDocumentWideProperties1 = new EndnoteDocumentWideProperties(); EndnoteSpecialReference endnoteSpecialReference1 = new EndnoteSpecialReference() {Id = -1}; EndnoteSpecialReference endnoteSpecialReference2 = new EndnoteSpecialReference() {Id = 0}; endnoteDocumentWideProperties1.Append(endnoteSpecialReference1); endnoteDocumentWideProperties1.Append(endnoteSpecialReference2); Compatibility compatibility1 = new Compatibility(); CompatibilitySetting compatibilitySetting1 = new CompatibilitySetting() { Name = CompatSettingNameValues.CompatibilityMode, Uri = "http://schemas.microsoft.com/office/word", Val = "14" }; CompatibilitySetting compatibilitySetting2 = new CompatibilitySetting() { Name = CompatSettingNameValues.OverrideTableStyleFontSizeAndJustification, Uri = "http://schemas.microsoft.com/office/word", Val = "1" }; CompatibilitySetting compatibilitySetting3 = new CompatibilitySetting() { Name = CompatSettingNameValues.EnableOpenTypeFeatures, Uri = "http://schemas.microsoft.com/office/word", Val = "1" }; CompatibilitySetting compatibilitySetting4 = new CompatibilitySetting() { Name = CompatSettingNameValues.DoNotFlipMirrorIndents, Uri = "http://schemas.microsoft.com/office/word", Val = "1" }; compatibility1.Append(compatibilitySetting1); compatibility1.Append(compatibilitySetting2); compatibility1.Append(compatibilitySetting3); compatibility1.Append(compatibilitySetting4); Rsids rsids1 = new Rsids(); RsidRoot rsidRoot1 = new RsidRoot() {Val = "002307CA"}; Rsid rsid25 = new Rsid() {Val = "00021925"}; Rsid rsid26 = new Rsid() {Val = "0005059E"}; Rsid rsid27 = new Rsid() {Val = "002307CA"}; Rsid rsid28 = new Rsid() {Val = "00267818"}; Rsid rsid29 = new Rsid() {Val = "002E2CE3"}; Rsid rsid30 = new Rsid() {Val = "00367B71"}; Rsid rsid31 = new Rsid() {Val = "003C716F"}; Rsid rsid32 = new Rsid() {Val = "00442AD3"}; Rsid rsid33 = new Rsid() {Val = "00485B24"}; Rsid rsid34 = new Rsid() {Val = "004B0395"}; Rsid rsid35 = new Rsid() {Val = "005A7CCB"}; Rsid rsid36 = new Rsid() {Val = "00664E23"}; Rsid rsid37 = new Rsid() {Val = "006D0F9D"}; Rsid rsid38 = new Rsid() {Val = "006F12E1"}; Rsid rsid39 = new Rsid() {Val = "00731A43"}; Rsid rsid40 = new Rsid() {Val = "00736D14"}; Rsid rsid41 = new Rsid() {Val = "007977E5"}; Rsid rsid42 = new Rsid() {Val = "007B10F8"}; Rsid rsid43 = new Rsid() {Val = "007C67E7"}; Rsid rsid44 = new Rsid() {Val = "00960953"}; Rsid rsid45 = new Rsid() {Val = "009F02C7"}; Rsid rsid46 = new Rsid() {Val = "00A056C7"}; Rsid rsid47 = new Rsid() {Val = "00B32099"}; Rsid rsid48 = new Rsid() {Val = "00B92CF0"}; Rsid rsid49 = new Rsid() {Val = "00BC57A3"}; Rsid rsid50 = new Rsid() {Val = "00BE6B68"}; Rsid rsid51 = new Rsid() {Val = "00BF235B"}; Rsid rsid52 = new Rsid() {Val = "00BF5126"}; Rsid rsid53 = new Rsid() {Val = "00C91302"}; Rsid rsid54 = new Rsid() {Val = "00CA68EB"}; Rsid rsid55 = new Rsid() {Val = "00E33AA1"}; Rsid rsid56 = new Rsid() {Val = "00E40D36"}; Rsid rsid57 = new Rsid() {Val = "00E7460D"}; Rsid rsid58 = new Rsid() {Val = "00E95156"}; Rsid rsid59 = new Rsid() {Val = "00F06304"}; Rsid rsid60 = new Rsid() {Val = "00FA5EBC"}; Rsid rsid61 = new Rsid() {Val = "00FB1F22"}; rsids1.Append(rsidRoot1); rsids1.Append(rsid25); rsids1.Append(rsid26); rsids1.Append(rsid27); rsids1.Append(rsid28); rsids1.Append(rsid29); rsids1.Append(rsid30); rsids1.Append(rsid31); rsids1.Append(rsid32); rsids1.Append(rsid33); rsids1.Append(rsid34); rsids1.Append(rsid35); rsids1.Append(rsid36); rsids1.Append(rsid37); rsids1.Append(rsid38); rsids1.Append(rsid39); rsids1.Append(rsid40); rsids1.Append(rsid41); rsids1.Append(rsid42); rsids1.Append(rsid43); rsids1.Append(rsid44); rsids1.Append(rsid45); rsids1.Append(rsid46); rsids1.Append(rsid47); rsids1.Append(rsid48); rsids1.Append(rsid49); rsids1.Append(rsid50); rsids1.Append(rsid51); rsids1.Append(rsid52); rsids1.Append(rsid53); rsids1.Append(rsid54); rsids1.Append(rsid55); rsids1.Append(rsid56); rsids1.Append(rsid57); rsids1.Append(rsid58); rsids1.Append(rsid59); rsids1.Append(rsid60); rsids1.Append(rsid61); M.MathProperties mathProperties1 = new M.MathProperties(); M.MathFont mathFont1 = new M.MathFont() {Val = "Cambria Math"}; M.BreakBinary breakBinary1 = new M.BreakBinary() {Val = M.BreakBinaryOperatorValues.Before}; M.BreakBinarySubtraction breakBinarySubtraction1 = new M.BreakBinarySubtraction() {Val = M.BreakBinarySubtractionValues.MinusMinus}; M.SmallFraction smallFraction1 = new M.SmallFraction() {Val = M.BooleanValues.Zero}; M.DisplayDefaults displayDefaults1 = new M.DisplayDefaults(); M.LeftMargin leftMargin1 = new M.LeftMargin() {Val = (UInt32Value) 0U}; M.RightMargin rightMargin1 = new M.RightMargin() {Val = (UInt32Value) 0U}; M.DefaultJustification defaultJustification1 = new M.DefaultJustification() {Val = M.JustificationValues.CenterGroup}; M.WrapIndent wrapIndent1 = new M.WrapIndent() {Val = (UInt32Value) 1440U}; M.IntegralLimitLocation integralLimitLocation1 = new M.IntegralLimitLocation() {Val = M.LimitLocationValues.SubscriptSuperscript}; M.NaryLimitLocation naryLimitLocation1 = new M.NaryLimitLocation() {Val = M.LimitLocationValues.UnderOver}; mathProperties1.Append(mathFont1); mathProperties1.Append(breakBinary1); mathProperties1.Append(breakBinarySubtraction1); mathProperties1.Append(smallFraction1); mathProperties1.Append(displayDefaults1); mathProperties1.Append(leftMargin1); mathProperties1.Append(rightMargin1); mathProperties1.Append(defaultJustification1); mathProperties1.Append(wrapIndent1); mathProperties1.Append(integralLimitLocation1); mathProperties1.Append(naryLimitLocation1); ThemeFontLanguages themeFontLanguages1 = new ThemeFontLanguages() {Val = "en-US"}; ColorSchemeMapping colorSchemeMapping1 = new ColorSchemeMapping() { Background1 = ColorSchemeIndexValues.Light1, Text1 = ColorSchemeIndexValues.Dark1, Background2 = ColorSchemeIndexValues.Light2, Text2 = ColorSchemeIndexValues.Dark2, Accent1 = ColorSchemeIndexValues.Accent1, Accent2 = ColorSchemeIndexValues.Accent2, Accent3 = ColorSchemeIndexValues.Accent3, Accent4 = ColorSchemeIndexValues.Accent4, Accent5 = ColorSchemeIndexValues.Accent5, Accent6 = ColorSchemeIndexValues.Accent6, Hyperlink = ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = ColorSchemeIndexValues.FollowedHyperlink }; ShapeDefaults shapeDefaults2 = new ShapeDefaults(); Ovml.ShapeDefaults shapeDefaults3 = new Ovml.ShapeDefaults() {Extension = V.ExtensionHandlingBehaviorValues.Edit, MaxShapeId = 6145}; Ovml.ShapeLayout shapeLayout1 = new Ovml.ShapeLayout() {Extension = V.ExtensionHandlingBehaviorValues.Edit}; Ovml.ShapeIdMap shapeIdMap1 = new Ovml.ShapeIdMap() {Extension = V.ExtensionHandlingBehaviorValues.Edit, Data = "1"}; shapeLayout1.Append(shapeIdMap1); shapeDefaults2.Append(shapeDefaults3); shapeDefaults2.Append(shapeLayout1); DecimalSymbol decimalSymbol1 = new DecimalSymbol() {Val = "."}; ListSeparator listSeparator1 = new ListSeparator() {Val = ","}; settings1.Append(zoom1); settings1.Append(proofState1); settings1.Append(mailMerge1); settings1.Append(defaultTabStop1); settings1.Append(characterSpacingControl1); settings1.Append(headerShapeDefaults1); settings1.Append(footnoteDocumentWideProperties1); settings1.Append(endnoteDocumentWideProperties1); settings1.Append(compatibility1); settings1.Append(rsids1); settings1.Append(mathProperties1); settings1.Append(themeFontLanguages1); settings1.Append(colorSchemeMapping1); settings1.Append(shapeDefaults2); settings1.Append(decimalSymbol1); settings1.Append(listSeparator1); documentSettingsPart1.Settings = settings1; }
protected abstract void DoMergeTypeSetup(ComObjectManager com, MailMerge mailMerge);