private Stream CreateLetter(NewLetterModel info) { try { var distributor = _distributorService.GetDistributorById(info.DistNumber); var sponsor = _distributorService.GetDistributorById(info.SponsorNumber); var platium = _distributorService.GetDistributorById(info.PlatiumNumber); var oldDistributor = _distributorService.GetDistributorById(info.OldDistNumber); var outputStream = new MemoryStream(); string filePath = Server.MapPath(Url.Content("~/Template/LetterTemplate.docx")); DocX document = DocX.Load(filePath); Stream mainStream = new MemoryStream(); document.SaveAs(mainStream); mainStream.Position = 0; mainStream = CreateLetterTemplate(mainStream, distributor, sponsor, platium, oldDistributor); //TODO: Add contant for file name Stream distributorLetter = CreateLetterAddress(mainStream, distributor); //zip.AddEntry("Re-apps letter-Nguoi dang ky lai.docx", distributorLetter); Stream sponsorLetter = CreateLetterAddress(mainStream, sponsor); //zip.AddEntry("Re-apps letter -Tuyen tren cu.docx", sponsorLetter); DocX docx = DocX.Load(distributorLetter); docx.InsertSectionPageBreak(); docx.InsertDocument(DocX.Load(sponsorLetter)); if (info.SponsorNumber != info.PlatiumNumber) { Stream platiumLetter = CreateLetterAddress(mainStream, platium); //zip.AddEntry("Re-apps letter -Platinum cu.docx", platiumLetter); docx.InsertSectionPageBreak(); docx.InsertDocument(DocX.Load(platiumLetter)); } docx.SaveAs(outputStream); _distributorService.AddNewLetter(new DistributorLetter { DistName = info.DistName, OldDistNumber = info.OldDistNumber, PlatiniumSponsorId = info.PlatiumNumber, SponsorId = info.SponsorNumber, DistNumber = info.DistNumber, LetterDate = DateTime.Now, UserId = _workContext.User.UserID, WHId = _workContext.User.WarehouseId }); outputStream.Position = 0; return(outputStream); } catch (Exception ex) { //TODO: Redirect to error Page return(null); } }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="docPath"></param> /// <returns></returns> public Task <string> WriteDocs(Guid id, string docPath) { DocX docX = DocX.Create(docPath, DocumentTypes.Document); var query = GetById(id); var docf = WriteDocf(query); docX.InsertDocument(docf); var docs = WriteDocs(query.JingFeis); docX.InsertDocument(docs); docX.SaveAs(docPath); docX.Dispose(); return(null); }
private void AppendDocuments(DocX document, String toAppendDocumentsPath) { try { var documents = Directory.GetFiles(toAppendDocumentsPath); foreach (var d in documents) { if (Path.GetExtension(d) == ".docx") { try { using (DocX doc = DocX.Load(d)) { document.InsertSectionPageBreak(); document.InsertDocument(doc); } } catch (Exception e) { throw new MergerException($"Could not append the document located at \"{d}\"", e.Message); } } } } catch (Exception e) { throw new MergerException($"Could not load documents from \"{toAppendDocumentsPath}\"", e.Message); } }
public MemoryStream ToStream(byte[] orderClause = null) { MemoryStream stream = new MemoryStream(); using (DocX docPage = DocX.Create(System.IO.Path.Combine("Report", "tmp.docx"))) { SetPageMargin(docPage); for (int i = 0; i < infoTmp.Parts.Count; i++) { if (infoTmp.Parts[i].Part_Seq == infoTmp.Item_Clause_Seq && orderClause != null) { using (DocX document = DocX.Load(new MemoryStream(orderClause))) { SetPageMargin(document); docPage.InsertDocument(document, true); } } else { using (DocX document = DocX.Load(new MemoryStream(infoTmp.Parts[i].Part_File))) { SetPageMargin(document); docPage.InsertDocument(document, true); } } } //替换变量 //SetOrderHead(); InitVar(); ReplaceVar(docPage, dicVarMap); //录入产品信息 InsertTable(docPage); SetHeaderFooter(docPage); docPage.SaveAs(stream); stream.Seek(0, SeekOrigin.Begin); } return(stream); }
private void WriteFile(string pathTemplate, string pathCsv, string pathDist) { try { Task task = DisableAllButtonsAsync(); using (DocX docuement = DocX.Create(pathDist)) { using (DocX template = DocX.Load(pathTemplate)) { int lineCount = 0; using (var csv = new CsvReader(new StreamReader(pathCsv), true)) { lineCount = csv.Count(); } using (var csv = new CsvReader(new StreamReader(pathCsv), true)) { var fieldCount = csv.FieldCount; var headers = csv.GetFieldHeaders(); while (csv.ReadNextRecord()) { if (csv.CurrentRecordIndex != 0) { docuement.InsertSectionPageBreak(); } docuement.InsertDocument(template); for (var i = 0; i < fieldCount; i++) { docuement.ReplaceText(String.Format("<<{0}>>", headers[i]), csv[i]); } Task t = UpdatePgbAsync((double)(csv.CurrentRecordIndex + 1) / lineCount * 100); } } } docuement.Save(); if (docuement.Text.Contains("<<") || docuement.Text.Contains(">>")) { MessageBox.Show("There is some << / >> not merged."); } Task t2 = FinishMergeAsync(); } } catch (Exception ex) { MessageBox.Show(String.Format("{0}", ex.Message), "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } finally { Task task = EnableAllButtonsAsync(); } }
protected void AppendDocument(string outputFolder, string outputFile, params string[] inputfiles) { using (DocX root = DocX.Load(Path.Combine(outputFolder, inputfiles[0]))) { for (int i = 1; i < inputfiles.Length; i++) { using (DocX document2 = DocX.Load(Path.Combine(outputFolder, inputfiles[i]))) { root.InsertDocument(document2, true); } } root.SaveAs(Path.Combine(outputFolder, outputFile)); } }
public byte[] GenerateDocx(int themeId) { var theme = _context.GetThemes().FirstOrDefault(t => t.Id == themeId); var supervisor = _context.Supervisors.FirstOrDefault(s => s.Id == theme.SupervisorId); var stProgram = _context.StPrograms.FirstOrDefault(s => s.Id == theme.StProgramId); DirectoryInfo di = new DirectoryInfo("..\\..\\..\\Data\\Word"); DocX template = DocX.Load(di.FullName + "\\PhD_temy_sablona.docx"); byte[] ret = null; string fileNamePath = di.FullName + "\\Result" + di.GetFiles().Length + ".docx"; using (DocX newFile = DocX.Create(fileNamePath)) { newFile.InsertDocument(template); newFile.ReplaceText("#=ThemeName=#", theme.Name); newFile.ReplaceText("#=Supervisor=#", supervisor.FullName); newFile.ReplaceText("#=StProgram=#", stProgram.Name); newFile.ReplaceText("#=FieldOfStudy=#", stProgram.FieldOfStudy); string resType = ""; switch (theme.ResearchType) { case ResearchType.BasicResearch: resType = "základný výskum"; break; case ResearchType.AppliedResearch: resType = "aplikovaný výskum"; break; case ResearchType.AppliedResearchExpDevelopment: resType = "aplikovaný výskum a experimentálny vývoj"; break; case null: break; default: throw new ArgumentOutOfRangeException(); } newFile.ReplaceText("#=ResearchType=#", resType); newFile.ReplaceText("#=Description=#", theme.Description); ret = Encoding.ASCII.GetBytes(newFile.ToString()); newFile.Save(); } Process.Start(fileNamePath); return(ret); }
public static void MergeDocs(String ExportDoc, String CurrentDoc, bool Clear, bool Last) { object missing = System.Reflection.Missing.Value; object oExportDoc = ExportDoc; //+ ".dotx"; object oCurrentDoc = CurrentDoc; //object pageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; //Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); //Microsoft.Office.Interop.Word.Document oWordDocExport = oWordApp.Documents.Add(ref oExportDoc, ref missing, ref missing, ref missing); DocX owordDocnew = DocX.Load(oExportDoc.ToString()); DocX oWordCurrent = DocX.Load(CurrentDoc.ToString()); if (Clear) { //oWordDocExport.Content.Delete(); //owordDocnew.Text.Remove(0, 100000); owordDocnew.SaveAs(ExportDoc.Replace(".docx", "-temp.docx")); } owordDocnew = DocX.Load(ExportDoc.Replace(".docx", "-temp.docx")); //Microsoft.Office.Interop.Word.Selection selection = oWordApp.Selection; //selection.InsertFile(CurrentDoc, ref missing, ref missing, ref missing, ref missing); owordDocnew.InsertDocument(oWordCurrent, true); //if(!Last) // selection.InsertBreak(ref pageBreak); //oWordDocExport.Activate(); //oWordDocExport.PageSetup.Orientation = WdOrientation.wdOrientLandscape; //oWordDocExport.SaveAs(ExportDoc); owordDocnew.PageLayout.Orientation = Novacode.Orientation.Landscape; owordDocnew.SaveAs(ExportDoc.Replace(".docx", "-temp.docx")); if (Last) { //oWordDocExport.SaveAs(ExportDoc.Replace(".docx", ".pdf"), WdSaveFormat.wdFormatPDF); owordDocnew.SaveAs(ExportDoc.Replace(".docx", "-1.docx")); } //object oMissing = System.Reflection.Missing.Value; //object saveChanges = WdSaveOptions.wdDoNotSaveChanges; //((_Document)oWordDocExport).Close(ref saveChanges, ref oMissing, ref oMissing); //oWordDocExport = null; owordDocnew = null; }
/// <summary> /// Insert a document at the end of another document. /// </summary> public static void AppendDocument() { Console.WriteLine("\tAppendDocument()"); // Load the first document. using (DocX document1 = DocX.Load(DocumentSample.DocumentSampleResourcesDirectory + @"First.docx")) { // Load the second document. using (DocX document2 = DocX.Load(DocumentSample.DocumentSampleResourcesDirectory + @"Second.docx")) { // Insert a document at the end of another document. // When true, document is added at the end. When false, document is added at beginning. document1.InsertDocument(document2, true); // Save this document to disk. document1.SaveAs(DocumentSample.DocumentSampleOutputDirectory + @"AppendDocument.docx"); Console.WriteLine("\tCreated: AppendDocument.docx\n"); } } }
private void button1_Click(object sender, EventArgs e) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pl-PL"); using (DocX document = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój1.docx")) { // Check if all the replace patterns are used in the loaded document. document.ReplaceText("@PrzykładowyTekstDoZmiany0", "PierwszaWstawkaBezSPacji_Znakmi!#$%^)&()", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting() { Bold = true }); document.ReplaceText("@PrzykładowyTekstDoZmiany1", "Zwykły tekst ", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting() { Bold = true }); document.ReplaceText("@PrzykładowyTekstDoZmiany2", "Zwykły tekst, dodany przez aplikację ( ) ", false, System.Text.RegularExpressions.RegexOptions.None, new Formatting() { Bold = true }); var p = document.InsertParagraph(); p.Append("Przykładowy czerwony tekst dodany na końcu,") .Font(new Font("Arial")) .FontSize(25) .Color(System.Drawing.Color.Red) .Bold() .Append(" zawierający dodatkowe inne niebieskie formatowanie").Font(new Font("Times New Roman")).Color(System.Drawing.Color.Blue).Italic() .SpacingAfter(40); // Save this document to disk. document.SaveAs(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"); using (DocX document1 = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój1.docx")) { using (DocX document3 = DocX.Load(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx")) { document1.InsertDocument(document3, true); document1.SaveAs(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój3.docx"); } } var n = DateTime.Now; var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second)); tempDi.Create(); /* * This example loads each document into a byte array, then into a memory stream, so that the document can be opened for writing without * modifying the source document. */ //foreach (var file in Directory.GetFiles("../../", "*.docx")) //{ // ConvertToHtml(file, tempDi.FullName); //} byte[] byteArray = File.ReadAllBytes(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"); using (MemoryStream memoryStream = new MemoryStream()) { memoryStream.Write(byteArray, 0, byteArray.Length); using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true)) { HtmlConverterSettings settings = new HtmlConverterSettings() { PageTitle = "My Page Title" }; XElement html = HtmlConverter.ConvertToHtml(doc, settings); File.WriteAllText(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.html", html.ToStringNewLineOnAttributes()); } } string test = File.ReadAllText(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.hmtl"); //Byte[] res = null; //using (MemoryStream ms = new MemoryStream()) //{ // var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(test, PdfSharp.PageSize.A4); // pdf.Save(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.pdf"); // res = ms.ToArray(); //} //Load Document Spire.Doc.Document document2 = new Spire.Doc.Document(); document2.LoadFromFile(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\Mój2.docx"); //Convert Word to PDF document2.SaveToFile("toPDF.PDF", FileFormat.PDF); //Launch Document System.Diagnostics.Process.Start("toPDF.PDF"); string[] pdfFiles = { @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF", @"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF.PDF" }; PdfDocument outputPDFDocument = new PdfDocument(); foreach (string pdfFile in pdfFiles) { PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import); outputPDFDocument.Version = inputPDFDocument.Version; foreach (PdfPage page in inputPDFDocument.Pages) { outputPDFDocument.AddPage(page); } } outputPDFDocument.Save(@"C:\Users\Ernest\source\repos\Word_Pdf\Word_Pdf\bin\Debug\toPDF2.PDF"); } }
//合并 /// <summary> /// 合并多个word,按页 /// </summary> /// <param name="tempDoc">word活动页</param> /// <param name="lastDoc">word尾页</param> /// <param name="outDoc">保存路径</param> /// <param name="pageCount">页数</param> public void getMergeTempByCount(string tempDoc, string lastDoc, string outDoc, int pageCount) { try { DocX oldDocument = DocX.Load(tempDoc); //DocX tempDocument = DocX.Load(tempDoc); DocX newDocument = DocX.Load(tempDoc); DocX lastDocument = DocX.Load(lastDoc); //reportno = fine + reportno; if (pageCount == 1) { ////替换报告单号 //ReplaceFlag(lastDocument, reportFlag, reportno, null, true); ////替换总页数 //ReplaceFlag(lastDocument, totalPageFlag, (startPage).ToString(), null, true); ////替换当前页数 //ReplaceFlag(lastDocument, nowPageFlag, (startPage).ToString(), null, true); lastDocument.SaveAs(outDoc); return; } else { int i = 1; for (i = 1; i <= pageCount - 2; i++) { ////还原临时文件 //newDocument = tempDocument; ////替换报告单号 //ReplaceFlag(newDocument, reportFlag, reportno, null, true); ////替换总页数 //ReplaceFlag(newDocument, totalPageFlag, (pageCount + startPage - 1).ToString(), null, true); ////替换当前页数 //ReplaceFlag(newDocument, nowPageFlag, (startPage + i).ToString(), null, true); oldDocument.InsertDocument(newDocument); } ////写入首页 //ReplaceFlag(oldDocument, reportFlag, reportno, null, true); //ReplaceFlag(oldDocument, totalPageFlag, (pageCount + startPage - 1).ToString(), null, true); //ReplaceFlag(oldDocument, nowPageFlag, (startPage).ToString(), null, true); ////写入尾页 //ReplaceFlag(lastDocument, reportFlag, reportno, null, true); //ReplaceFlag(lastDocument, totalPageFlag, (pageCount + startPage - 1).ToString(), null, true); //ReplaceFlag(lastDocument, nowPageFlag, (pageCount + startPage - 1).ToString(), null, true); oldDocument.InsertDocument(lastDocument); oldDocument.SaveAs(outDoc); return; } } catch (Exception ex) { classLims_NPOI.WriteLog(ex, ""); return; } }
/// <summary> /// Writes Descriptive and Grade-Tonnage tool's appendixes. /// </summary> /// <param name="input">Inputs.</param> /// <param name="document">Word document.</param> private void WriteAppendixes(ReportingAssesmentInputParams input, DocX document) { string paragraph = ""; if (input.AddDescriptive == "True" && File.Exists(input.DescModel)) { document.InsertParagraph().InsertPageBreakAfterSelf(); paragraph = "Appendix 1" + "\r\n"; document.InsertParagraph(paragraph).FontSize(14).Bold(); paragraph = "Desciptive model for " + input.DepositType + "(" + input.DescModelName + ")\r\n"; document.InsertParagraph(paragraph).FontSize(14).Bold(); if (File.Exists(input.DescModel)) { using (var reportDocument = DocX.Load(input.DescModel)) { document.InsertDocument(reportDocument, true); } } //if (File.Exists(input.DescModel)) //{ // using (var paraDocument = DocX.Load(input.DescModel)) // { // if (paraDocument != null) // { // foreach (var para in paraDocument.Paragraphs) // { // document.InsertParagraph(para); // } // } // } //} } if (input.AddGradeTon == "True" && Directory.Exists(input.GTModel)) { document.InsertParagraph().InsertPageBreakAfterSelf(); paragraph = "Appendix 2" + "\r\n"; document.InsertParagraph(paragraph).FontSize(14).Bold(); paragraph = "Grade-tonnage model for " + input.DepositType + "(" + input.GTModelName + ")\r\n"; document.InsertParagraph(paragraph).FontSize(14).Bold(); paragraph = Path.Combine(input.GTModel, "grade_summary.txt"); if (File.Exists(paragraph)) { paragraph = File.ReadAllText(paragraph); document.InsertParagraph(paragraph).FontSize(11).Font(new Font("Calibri")); } paragraph = Path.Combine(input.GTModel, "grade_plot.jpeg"); if (File.Exists(paragraph)) { var img = document.AddImage(paragraph); Picture p = img.CreatePicture(600, 605); paragraph = ""; Paragraph par = document.InsertParagraph(paragraph); par.AppendPicture(p); par.Append("\r\n"); paragraph = "Histogram (A) and cumulative distribution function (B) that are calculated from the probability density" + " function representing the grades. In A, the vertical red lines at the plot bottom represent the log-ratios" + " calculated from the grade and tonnage model. In B, the red dots constitute empirical cumulative distribution" + " function for the log-ratios calculated from the grade and tonnage model." + "\r\n"; document.InsertParagraph(paragraph).FontSize(11); } paragraph = Path.Combine(input.GTModel, "tonnage_summary.txt"); if (File.Exists(paragraph)) { paragraph = File.ReadAllText(paragraph); document.InsertParagraph(paragraph).FontSize(11).Font(new Font("Calibri")); } paragraph = Path.Combine(input.GTModel, "tonnage_plot.jpeg"); if (File.Exists(paragraph)) { var img = document.AddImage(paragraph); Picture p = img.CreatePicture(600, 605); paragraph = ""; Paragraph par = document.InsertParagraph(paragraph); par.AppendPicture(p); par.Append("\r\n"); paragraph = "A: Probability density function that represents the ore tonnage in an undiscovered deposit.The vertical" + " lines at the bottom represent the ore tonnages from the grade and tonnage model. B: Corresponding cumulative " + "distribution function(solid line). The red dots constitute the empirical cumulative distribution function " + "for the ore tonnages from the grade and tonnage model." + "\r\n"; document.InsertParagraph(paragraph).FontSize(11); } } if (Directory.Exists(Path.Combine(input.Env.RootPath, "EconFilter", "RAEF", input.SelectedTractCombination, "SelectedResult"))) { DirectoryInfo di = new DirectoryInfo(Path.Combine(input.Env.RootPath, "EconFilter", "RAEF", input.SelectedTractCombination, "SelectedResult")); foreach (FileInfo file in di.GetFiles()) { if (input.AddRaef == "True" && file.Name.Contains("EF_01_Parameters_")) //Path.Combine(input.Env.RootPath, "EconFilter", "RAEF", "SelectedResult", "EF_01_Parameters_C.csv") { paragraph = "Appendix 3"; document.InsertParagraph(paragraph).FontSize(14).Bold(); paragraph = ""; using (TextReader fileReader = File.OpenText(file.FullName)) { using (var csv = new CsvReader(fileReader)) { csv.Configuration.HasHeaderRecord = false; csv.Configuration.BadDataFound = null; csv.Configuration.Delimiter = ";"; var t = document.AddTable(1, 2); bool addToFirstRow = true; while (csv.Read()) { // Gets information from CSV file. for (int i = 0; csv.TryGetField <string>(i, out paragraph); i++) { char[] valueArray = paragraph.ToArray(); int j = 0; while (valueArray[j] != '"') { paragraph = paragraph.Remove(0, 1); j++; } string[] cellArray = paragraph.Split(','); var r = t.Rows[0]; if (addToFirstRow == true) { r = t.Rows[0]; addToFirstRow = false; } else { r = t.InsertRow(); } r.Cells[0].Paragraphs[0].Append(cellArray[0]).ReplaceText("\"", ""); r.Cells[1].Paragraphs[0].Append(cellArray[1]).ReplaceText("\"", ""); r.Cells[1].Paragraphs[0].Alignment = Alignment.right; } } document.InsertTable(t); // Add table into a document. } } document.InsertParagraph("\r\n"); } } } // Add chosed tractReports if (input.TractIDNames != null && input.TractIDChoices != null) { foreach (var name in input.TractIDNames) { if (input.TractIDChoices.Count > input.TractIDNames.IndexOf(name) && input.TractIDNames.IndexOf(name) != -1) { if (input.TractIDChoices[input.TractIDNames.IndexOf(name)] == "True" && name != null) { string report = Path.Combine(input.Env.RootPath, "Reporting", name, "TractReport" + name + ".docx"); if (File.Exists(report)) { using (var reportDocument = DocX.Load(report)) { document.InsertParagraph().InsertPageBreakAfterSelf(); document.InsertDocument(reportDocument, true); } } } } } } }
protected void Page_Load(object sender, EventArgs e) { int id = int.Parse(Request["id"]); // get list of species for this catalog List <int> list = GetSpeciesList(id); // get catalogue info CatalogInfo info = GetCatlogInfo(id); String rootDir = Server.MapPath("temp/catalog/" + id); if (Directory.Exists(rootDir) == false) { Directory.CreateDirectory(rootDir); } String ext = Path.GetExtension(info.fTemplatePath); List <CatalogPage> pages = new List <CatalogPage>(); for (int i = 0; i < list.Count; i++) { int species = list[i]; int page = i + 1; String outPath = rootDir + "\\Page" + page + ext; if (File.Exists(outPath)) { File.Delete(outPath); } CatalogPage cpage = new CatalogPage(); cpage.index = i; cpage.path = outPath; pages.Add(cpage); File.Copy(info.fTemplatePath, outPath); using (DocX doc = DocX.Load(outPath)) { String query = "SELECT * FROM TblSpecies WHERE fSpeciesID = " + species; using (SqlConnection con = new SqlConnection(DataSources.dbConSpecies)) { con.Open(); using (SqlCommand command = new SqlCommand(query, con)) { using (SqlDataReader set = command.ExecuteReader()) { if (!set.Read()) { Response.Write("Invalid species id: " + species); Response.End(); } Response.Write("Add: " + set["fSpeciesName"].ToString() + "<br>"); Response.Flush(); doc.ReplaceText("~SCIENT~", set["fSpeciesName"].ToString()); doc.ReplaceText("~COMMON~", set["fCommonName"].ToString()); doc.ReplaceText("~FISHBOARD~", set["fFishBoard"].ToString()); doc.ReplaceText("~FEATURES~", set["fFeatures"].ToString()); doc.ReplaceText("~COLOUR~", set["fColour"].ToString()); doc.ReplaceText("~SIZE~", set["fSize"].ToString()); doc.ReplaceText("~HABITAT~", set["fHabitat"].ToString()); doc.ReplaceText("~DISTRIBUTION~", set["fDistribution"].ToString()); doc.ReplaceText("~SIMILAR~", set["fSimilar"].ToString()); doc.ReplaceText("~REFERENCES~", set["fReferences"].ToString()); doc.ReplaceText("~NOTES~", set["fNotes"].ToString()); // doc.r ResolveTaxon(doc, (int)set["fTaxonomyID"]); doc.ReplaceText("~CLASS~", ""); doc.ReplaceText("~ORDER~", ""); doc.ReplaceText("~FAMILY~", ""); doc.ReplaceText("~GENUS~", ""); doc.ReplaceText("~SPECIES~", ""); doc.ReplaceText("~COMMON~", ""); } } } // add media int photoIndex = 1; String sql = "SELECT TOP 4 * FROM vwSpeciesMedia WHERE fCatalogueOrder > 0 AND fSpeciesID = " + species; // Response.Write(sql); using (SqlConnection con = new SqlConnection(DataSources.dbConSpecies)) { con.Open(); using (SqlCommand command = new SqlCommand(sql, con)) { using (SqlDataReader set = command.ExecuteReader()) { while (set.Read()) { // String url = HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath + '/' + set["fMediaPath"].ToString(); // url = url.Replace("//", "/"); // if (url.IndexOf("http://") == -1) // url = "http://" + url; String url = set["fMediaPath"].ToString(); String srv = Request.Url.AbsoluteUri; int index = srv.IndexOf("publisher.aspx"); srv = srv.Substring(0, index); url = srv + "ic.aspx?url=" + Server.UrlEncode(url); Response.Write("Add photo: " + url + "<br>"); Response.Flush(); String tag_old = "~PHOTO" + photoIndex + "~"; String tag_new = "~PHOTO" + "_" + i + "_" + photoIndex + "~"; doc.ReplaceText(tag_old, tag_new); CatalogPhoto photo = new CatalogPhoto(); photo.url = url; photo.tag = tag_new; cpage.photos.Add(photo); photoIndex++; /* * Bitmap bmp = LoadBitmap(url); * Bitmap outBmp = ScaleImage(bmp, 400, 400); * * ReplaceTextWithImage(doc, tag, outBmp, 100); * * bmp.Dispose(); * outBmp.Dispose(); */ } } } } doc.Save(); } } String docPath = rootDir + "\\" + info.fCatalogueName + ext; if (pages.Count == 0) { Response.Write("No items found"); Response.End(); return; } CatalogPage catpage = pages[0]; using (DocX master = DocX.Load(catpage.path)) { for (int i = 1; i < pages.Count; i++) { catpage = pages[i]; DocX d = DocX.Load(catpage.path); master.InsertSectionPageBreak(); master.InsertDocument(d); } docName = info.fCatalogueName + ext; docURL = "temp/catalog/" + id + "/" + docName; master.SaveAs(docPath); } using (DocX master = DocX.Load(docPath)) { // insert images into master for (int i = 0; i < pages.Count; i++) { catpage = pages[i]; foreach (CatalogPhoto photo in catpage.photos) { Response.Write("Load: " + photo.url + "<br>"); Response.Flush(); Bitmap bmp = LoadBitmap(photo.url); Bitmap outBmp = ScaleImage(bmp, 400, 400); outBmp.SetResolution(300, 300); ReplaceTextWithImage(master, photo.tag, outBmp, 100); bmp.Dispose(); outBmp.Dispose(); } } master.ReplaceText("~PHOTO1~", ""); master.ReplaceText("~PHOTO2~", ""); master.ReplaceText("~PHOTO3~", ""); master.ReplaceText("~PHOTO4~", ""); String final = rootDir + "\\" + info.fCatalogueName + "" + ext; master.SaveAs(final); } }
public override void ExecuteResult(ControllerContext context) { var ctl = new MailingController { UseTitles = Titles ?? false, UseMailFlags = UseMailFlags ?? false }; var response = context.HttpContext.Response; IEnumerable <MailingController.MailingInfo> q = null; switch (Format) { case "Individual": q = ctl.FetchIndividualList(Sort, id); break; case "GroupAddress": q = ctl.GroupByAddress(Sort, id); break; case "Family": case "FamilyMembers": q = ctl.FetchFamilyList(Sort, id); break; case "ParentsOf": q = ctl.FetchParentsOfList(Sort, id); break; case "CouplesEither": q = ctl.FetchCouplesEitherList(Sort, id); break; case "CouplesBoth": q = ctl.FetchCouplesBothList(Sort, id); break; default: response.Write("unknown format"); return; } var bytes = AveryLabelTemplate() ?? Resource1.DocxAveryLabel; var ms = new MemoryStream(bytes); var docx = DocX.Load(ms); var row = 0; var col = 0; DocX finaldoc = null; DocX currpage = null; foreach (var p in q) { if (currpage == null || (row == 0 && col == 0)) { currpage = docx.Copy(); } if (Skip > 0) { row = Skip / 3; col = Skip % 3; if (col > 0) { col *= 2; } Skip = 0; } var cell = currpage.Tables[0].Rows[row].Cells[col]; var pg = cell.Paragraphs[0]; if (Format == "GroupAddress") { pg.InsertText(p.LabelName + " " + p.LastName); } else if ((Format == "CouplesEither" || Format == "CouplesBoth") && p.CoupleName.HasValue()) { pg.InsertText(p.CoupleName); } else { pg.InsertText(p.LabelName); } if (p.MailingAddress.HasValue()) { pg.InsertText($"\n{p.MailingAddress.Trim()}"); } else { pg.InsertText($"\n{p.Address}"); if (p.Address2.HasValue()) { pg.InsertText($"\n{p.Address2}"); } pg.InsertText($"\n{p.CSZ}"); } if (UsePhone == true) { var phone = Util.PickFirst(p.CellPhone.FmtFone("C "), p.HomePhone.FmtFone("H ")); pg.InsertText($"\n{phone}"); } col += 2; if (col != 6) { continue; } col = 0; row++; if (row != 10) { continue; } row = 0; if (finaldoc == null) { finaldoc = currpage; } else { finaldoc.InsertDocument(currpage); } currpage = null; } if (finaldoc == null && currpage == null) { response.Write("no data found"); return; } if (finaldoc == null) { finaldoc = currpage; } else if (currpage != null) { finaldoc.InsertDocument(currpage); } response.Clear(); response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; response.AddHeader("content-disposition", $"attachment;filename=AveryLabels-{DateTime.Now.ToSortableDateTime()}.docx"); ms = new MemoryStream(); finaldoc.SaveAs(ms); ms.WriteTo(response.OutputStream); response.End(); }
private void btImprimir_Click(object sender, EventArgs e) { if (txtIdVendedor.Text != "") { if (cbbPraça.SelectedItem != null) { if (dgvListaImpressão.Rows.Count > 0) { string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Impressões"; string fileName = "Pedidos para Impressão - " + cbbPraça.SelectedItem.ToString() + ".docx"; System.IO.Directory.CreateDirectory(docPath); docPath = System.IO.Path.Combine(docPath, fileName); DocX docForPrint = DocX.Create(docPath); docForPrint.MarginLeft = 36; docForPrint.MarginRight = 36; docForPrint.MarginTop = 36; docForPrint.MarginBottom = 36; foreach (DataGridViewRow row in dgvListaImpressão.Rows) { if (bool.Parse(row.Cells["cbImprimir"].Value.ToString())) { string docTempPath = GerarArquivoImpressão(row); if (docTempPath != "") { docForPrint.InsertDocument(DocX.Load(docTempPath), false); } } } /*ProcessStartInfo info = new ProcessStartInfo(docPath); * * info.Verb = "Print"; * * info.CreateNoWindow = false; * * info.WindowStyle = ProcessWindowStyle.Normal; * * Process.Start(info); * * * PrintDialog printDlg = new PrintDialog(); * PrintDocument printDoc = new PrintDocument(); * printDoc.DocumentName = docPath; * printDlg.Document = printDoc; * printDlg.AllowSelection = true; * printDlg.AllowSomePages = true; * //Call ShowDialog * if (printDlg.ShowDialog() == DialogResult.OK) * { * printDoc.Print(); * }*/ if (dgvListaImpressão.Rows.Count > 1) { try { docForPrint.Save(); DialogResult result = MessageBox.Show("Relatorio gerado na pasta Meus Documentos -> Impressões ( " + (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Impressões)"), "Atenção!", MessageBoxButtons.OK); } catch { DialogResult resultDialog = MessageBox.Show("Arquivo aberto em outro aplicativo, favor fecha-lo antes de continuar", "Atenção!", MessageBoxButtons.OK); } } } else { DialogResult result = MessageBox.Show("Lista de Clientes para Impressão vazia", "Atenção!", MessageBoxButtons.OK); } } else { DialogResult result = MessageBox.Show("Selecione uma Praça primeiro", "Atenção!", MessageBoxButtons.OK); } } else { DialogResult result = MessageBox.Show("Selecione um Vendedor primeiro", "Atenção!", MessageBoxButtons.OK); } }