private void Button1_Click(object sender, EventArgs e) { //Print float sum = 0; for (int s = 0; s < listBox1.Items.Count; s++) { sum += (float)Convert.ToDouble(listBox1.Items[s]); } textBox1.Text = sum.ToString(); txtTotal.Text = "Prix Total : " + sum.ToString() + "€"; Addtc(sum.ToString()); //Print document String filename = "Ticket.docx"; var doc = DocX.Create(filename); String title = "Welcome To MerlaCoffee ^.^"; Formatting titleFormat = new Formatting { FontFamily = new Xceed.Document.NET.Font("Times new roman"), Size = 20D, Position = 40, FontColor = Color.Blue, UnderlineColor = Color.Brown, Italic = true }; doc.InsertParagraph(title, false, titleFormat); Xceed.Document.NET.Image img = doc.AddImage(@"cap.jpg"); Picture p = img.CreatePicture(); Paragraph par = doc.InsertParagraph(""); par.AppendPicture(p); doc.InsertParagraph("Le " + DateTime.Now.ToString() + " a Rabat"); for (int n = 0; n < listBox2.Items.Count; n++) { doc.InsertParagraph(listBox2.Items[n].ToString()); } for (int s = 0; s < listBox1.Items.Count; s++) { doc.InsertParagraph(listBox1.Items[s].ToString() + " €"); } doc.InsertParagraph("Prix Total : " + sum.ToString() + "€"); float a = sum * Convert.ToInt32(10.7); doc.InsertParagraph("Prix Total : " + a.ToString() + "dh"); doc.Save(); Process.Start("WINWORD.EXE", filename); }
private void ManipulateWord(string dest, string[] paths) { richTextBox1.Text += "Generating to print file(.doc): " + dest + "... " + "\n"; var doc = DocX.Create(dest); doc.MarginLeft = 47; doc.MarginRight = 47; doc.MarginTop = 56; doc.MarginBottom = 56; Xceed.Document.NET.Paragraph par = doc.InsertParagraph(); int successedCard = 0; foreach (string _path in paths) { try { FileInfo fileInfo = new FileInfo(_path); richTextBox1.Text += "Processing card number: " + fileInfo.Name.Replace(".jpg", "") + "... "; string tempPath = Path.GetTempPath() + fileInfo.Name; Image img = doc.AddImage(_path); Picture p = img.CreatePicture(); double _r = 37.788578371810449574726609963548; p.Width = (int)(5.9 * _r); p.Height = (int)(8.6 * _r); //Create a new paragraph par.AppendPicture(p); successedCard++; richTextBox1.Text += "Success!" + "\n"; } catch (Exception ex) { richTextBox1.Text += "Fail! " + ex.Message + "\n"; } } if (successedCard > 0) { doc.Save(); richTextBox1.Text += "Generated print file(.doc): " + dest + "\n"; if (convertWordToPdf(dest, dest.Replace(".doc", ".pdf"))) { File.Delete(dest); } } }
private void CreateHeaderAndFooter(DocX doc) { var pngPath = Path.Combine(_hostingEnvironment.WebRootPath, "nccsoftlogo.png"); string titleHeader = "NCCPLUS VIET NAM JSC"; doc.AddHeaders(); Header h = doc.Headers.Odd; Xceed.Document.NET.Image image = doc.AddImage(pngPath); Xceed.Document.NET.Picture p = image.CreatePicture(29, 72); h.InsertParagraph(titleHeader).Alignment = Alignment.left; h.InsertParagraph().AppendPicture(p).Alignment = Alignment.right; h.InsertParagraph(); doc.AddFooters(); Footer footer = doc.Footers.Odd; footer.InsertParagraph().Append("Page ").AppendPageNumber(PageNumberFormat.normal).Append(" of ").AppendPageCount(PageNumberFormat.normal).Alignment = Alignment.center; }
/// <summary> /// Obtenir une picture à partir d'un tableau de byte, dont la taille est calculée pour qu'elle s'affiche correctement dans le document. /// </summary> /// <param name="templateDoc"></param> /// <param name="byteArrayIn"></param> /// <returns></returns> public Picture GetPicture(DocX templateDoc, byte[] byteArrayIn) { using (var ms = new MemoryStream(byteArrayIn)) { Xceed.Document.NET.Image image = templateDoc.AddImage(ms); Picture picture = image.CreatePicture(); if ((picture.Width > templateDoc.PageWidth || picture.Height > templateDoc.PageHeight) && picture.Width >= picture.Height) { picture.Height = (int)(templateDoc.PageWidth * ((float)picture.Height / picture.Width)); picture.Width = (int)templateDoc.PageWidth; } else if ((picture.Width > templateDoc.PageWidth || picture.Height > templateDoc.PageHeight) && picture.Width < picture.Height) { picture.Width = (int)(595 * ((float)picture.Height / picture.Width)); picture.Height = 595; } return(picture); } }
private bool AddSignAndConvertToPDF(typeFile tFile, FileData fData) { string FileName = fData.FileName; FileInfo newFile = new FileInfo(FileName); string FileNameToSaveAndSign = pathSignTmpPDF + "\\" + Path.GetFileNameWithoutExtension(FileName) + newFile.Extension; string FileAndParse = pathEndParse + "\\" + Path.GetFileNameWithoutExtension(FileName) + newFile.Extension; File.Copy(FileName, FileNameToSaveAndSign, true); string filePDF = pathSignTmpPDF + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".pdf"; newFile = new FileInfo(FileNameToSaveAndSign); Logging.Comment($"Начало обработки файла: { Path.GetFileNameWithoutExtension(filePDF)}"); if (tFile == typeFile.word) { using (var document = DocX.Load(FileNameToSaveAndSign)) { string StrImage = GetImageAgreements(fData.id_Landlord); if (StrImage.Length == 0) { if (File.Exists(FileNameToSaveAndSign)) { File.Delete(FileNameToSaveAndSign); } string sError = $"{fData.nameLandLord}: Отсутствует файлы для подписи"; if (!lStringError.Contains(fData.nameLandLord.Trim())) { lStringError.Add(fData.nameLandLord + "/" + fData.nameObject); } return(false); } Xceed.Document.NET.Image image = document.AddImage(StrImage); Picture picture = image.CreatePicture(); //picture.Rotation = 10; picture.SetPictureShape(BasicShapes.cube); //picture.Height = 115; //picture.Width = 931; //Table table = document.Tables[3]; //table.Rows[7].Remove(); //table.Rows[8].Remove(); //table.Rows[7].MergeCells(0, table.Rows[7].Cells.Count); //table.Rows[7].Cells[0].Paragraphs[0].AppendPicture(picture); Table table = document.Tables[5]; //table.Rows[7].Remove(); table.Rows[10].Remove(); table.Rows[10].MergeCells(0, table.Rows[10].Cells.Count); //table.Rows[10].Cells[0].Paragraphs[0].InsertText("test"); table.Rows[10].Cells[0].Paragraphs[0].AppendPicture(picture); document.Save(); } filePDF = cnvWordToPDF.ConvertData(FileNameToSaveAndSign); } else if (tFile == typeFile.excel) { if (newFile.Extension.Equals(".xls")) { object paramMissing = Type.Missing; string newFileName = newFile.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".xlsx"; var app = new Microsoft.Office.Interop.Excel.Application(); app.Caption = System.Guid.NewGuid().ToString().ToUpper(); var wb = app.Workbooks.Open(FileName); wb.SaveAs(newFileName, FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook); wb.Close(false, paramMissing, paramMissing); app.Quit(); Config.EnsureProcessKilled(IntPtr.Zero, app.Caption); Marshal.ReleaseComObject(wb); Marshal.FinalReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(app); Marshal.FinalReleaseComObject(app); app = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); File.Delete(FileNameToSaveAndSign); FileNameToSaveAndSign = newFileName; newFile = new FileInfo(FileNameToSaveAndSign); } if (newFile.Extension.Equals(".xlsx")) { string StrImage = GetImageAgreements(fData.id_Landlord); if (StrImage.Length == 0) { if (File.Exists(FileNameToSaveAndSign)) { File.Delete(FileNameToSaveAndSign); } string sError = $"{fData.nameLandLord}: Отсутствует файлы для подписи"; if (!lStringError.Contains(fData.nameLandLord.Trim())) { //lStringError.Add(fData.nameLandLord); lStringError.Add(fData.nameLandLord + "/" + fData.nameObject); } return(false); } ExcelPackage epp = new ExcelPackage(newFile); Bitmap image = new Bitmap(StrImage); OfficeOpenXml.Drawing.ExcelPicture excelImage = null; var worksheet = epp.Workbook.Worksheets[0]; int countRow = worksheet.Dimension.End.Row; int countColumns = worksheet.Dimension.End.Column; bool isStop = false; for (int i = countRow; i > 0; i--) { for (int j = 1; j < countColumns; j++) { object value = worksheet.Cells[i, j].Value; if (value != null) { //Console.WriteLine(value); if (value.ToString().ToLower().Equals("Руководитель".ToLower()) || value.ToString().ToLower().Equals("Предприниматель".ToLower())) { fData.positonInsertSign = i - 1; isStop = true; break; } } } if (isStop) { break; } } excelImage = worksheet.Drawings.AddPicture("image", image); // In .SetPosition, we are using 8th Column and 8th Row, with 0 Offset //var rowCnt = worksheet.Dimension.End.Row; //var colCnt = worksheet.Dimension.End.Column; //worksheet.SetValue(fData.positonInsertSign, 1, "test"); //excelImage.SetPosition(38, 0, 0, 0); excelImage.SetPosition(fData.positonInsertSign, 0, 0, 0); //set size of image, 100= width, 100= height //excelImage.SetSize(931, 115); epp.Save(); //epp.SaveAs() } filePDF = cnvXLSToPDF.ConvertData(FileNameToSaveAndSign); } File.Delete(FileNameToSaveAndSign); newFile = new FileInfo(filePDF); DataTable dtScan = Config.hCntMain.getScan(fData.idAgreement, -1); bool isoverwrite = false; int id_Scane = 0; if (dtScan != null && dtScan.Rows.Count > 0) { EnumerableRowCollection <DataRow> rowCollectScan = dtScan.AsEnumerable().Where(r => r.Field <string>("cName").Contains(Path.GetFileNameWithoutExtension(filePDF))).OrderBy(r => r.Field <int>("id")); if (rowCollectScan.Count() > 0) { DialogResult dlResult = DialogResult.Cancel; Config.DoOnUIThread(() => { dlResult = new MyMessageBox.MyMessageBox($"В каталоге арендатора уже существует файл с сохраняемым именем \r\n \"{Path.GetFileNameWithoutExtension(filePDF)}\"", "Сохранение PDF файла счёта", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string>(new string[] { "Перезаписать", "Создать копию", "Отмена" })) { Owner = this }.ShowDialog(); }, this); if (dlResult == DialogResult.Cancel) { if (File.Exists(filePDF)) { File.Delete(filePDF); } Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: файл счёта не сохранён. Операция прервана пользователем"); MessageBox.Show(Config.centralText("PDF файл счёта не сохранён.\nОперация прервана пользователем\n"), "Сохранение PDF файла счёта", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } if (dlResult == DialogResult.Yes) { Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: Перезапись"); isoverwrite = true; //id_Scane = (int)rowCollectScan.First()["id"]; } else if (dlResult == DialogResult.No) { string filePDFTmp = filePDF.Replace(Path.GetFileNameWithoutExtension(filePDF), Path.GetFileNameWithoutExtension(filePDF) + $"({rowCollectScan.Count()})"); File.Move(filePDF, filePDFTmp); Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: Копирование: Новое наименование файла: {Path.GetFileNameWithoutExtension(filePDFTmp)}"); filePDF = filePDFTmp; } } } string ServerPath = $"{net.server}\\{fData.idAgreement}"; //if (id_Scane == 0) //{ DataTable dtResult = Config.hCntMain.setScan(fData.idAgreement, Path.GetFileNameWithoutExtension(filePDF), newFile.Extension, 11, fData.Date, ServerPath); if (dtResult != null && dtResult.Rows.Count > 0) { id_Scane = (int)dtResult.Rows[0]["id"]; net.CopyFile(fData.idAgreement.ToString(), filePDF, Path.GetFileNameWithoutExtension(filePDF) + newFile.Extension, isoverwrite); } //} //else //{ // net.CopyFile(fData.idAgreement.ToString(), filePDF, Path.GetFileNameWithoutExtension(filePDF) + newFile.Extension, isoverwrite); //} Config.hCntMain.SetAgreement1CForAgreement(fData.idAgreement, fData.Number, fData.Date, fData.Agreement, fData.TypePay, fData.isAdd, id_Scane, !isoverwrite); Logging.Comment($"Запись в БД:[idAgreement:{fData.idAgreement};Номер: {fData.Number};Дата: {fData.Date}; Agreement: {fData.Agreement}; Тип оплаты:{fData.TypePay}]"); File.Delete(filePDF); try { File.Move(FileName, FileAndParse); } catch (IOException ex) { newFile = new FileInfo(FileName); string[] listFileInDir = Directory.GetFiles(pathEndParse + "\\", Path.GetFileNameWithoutExtension(FileName) + "*"); if (listFileInDir.Count() > 0) { FileAndParse = pathEndParse + "\\" + Path.GetFileNameWithoutExtension(FileName) + $"({listFileInDir.Count()})" + newFile.Extension; } File.Move(FileName, FileAndParse); } Logging.Comment($"Завершение обработки файла: { Path.GetFileNameWithoutExtension(filePDF)}"); return(true); }
public IActionResult PrintReport([FromBody] ExportReportViewModel model) { var electronicBook = _context.ElectronicBooks .Include(x => x.User) .Include(x => x.ElectronicBookFiles) .Where(x => x.Id == model.electronicBookId) .FirstOrDefault(); System.Console.WriteLine("in printtttt"); if (!Directory.Exists(_environment.WebRootPath + "//Uploads//")) { Directory.CreateDirectory(_environment.WebRootPath + "//Uploads//"); //สร้าง Folder Upload ใน wwwroot } var filePath = _environment.WebRootPath + "/Uploads/"; var filePath2 = _environment.WebRootPath + "/Signature/"; var filename = "สมุดตรวจราชการอิเล็กทรอนิกส์" + DateTime.Now.ToString("dd MM yyyy") + ".docx"; var createfile = filePath + filename; var myImageFullPath = filePath + "logo01.png"; System.Console.WriteLine("3"); System.Console.WriteLine("in create"); using (DocX document = DocX.Create(createfile)) { Image image = document.AddImage(myImageFullPath); Picture picture = image.CreatePicture(85, 85); var logo = document.InsertParagraph(); logo.AppendPicture(picture).Alignment = Alignment.center; document.SetDefaultFont(new Xceed.Document.NET.Font("ThSarabunNew")); document.AddHeaders(); document.AddFooters(); // Force the first page to have a different Header and Footer. document.DifferentFirstPage = true; // Force odd & even pages to have different Headers and Footers. document.DifferentOddAndEvenPages = true; // Insert a Paragraph into the first Header. document.Footers.First.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right; // Insert a Paragraph into the even Header. document.Footers.Even.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right; // Insert a Paragraph into the odd Header. document.Footers.Odd.InsertParagraph("วันที่ออกรายงาน: ").Append(DateTime.Now.ToString("dd MMMM yyyy HH:mm", new CultureInfo("th-TH"))).Append(" น.").Alignment = Alignment.right; // Add the page number in the first Footer. document.Headers.First.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center; // Add the page number in the even Footers. document.Headers.Even.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center; // Add the page number in the odd Footers. document.Headers.Odd.InsertParagraph("").AppendPageNumber(PageNumberFormat.normal).Alignment = Alignment.center; System.Console.WriteLine("5"); // Add a title var reportType = document.InsertParagraph("สมุดตรวจราชการอิเล็กทรอนิกส์"); reportType.FontSize(18d); reportType.SpacingBefore(15d); reportType.SpacingAfter(5d); reportType.Bold(); reportType.Alignment = Alignment.center; System.Console.WriteLine("6"); Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH"); var testDate = electronicBook.StartDate.Value.ToString("dddd dd MMMM yyyy"); var printDate = DateTime.Now.ToString("dd MMMM yyyy"); // Insert a title paragraph. var title = document.InsertParagraph("วันที่ตรวจราชการ: " + testDate); title.Alignment = Alignment.center; title.SpacingAfter(15d); title.FontSize(16d); title.Bold(); //var printReport = document.InsertParagraph("วันที่ออกรายงาน: " + printDate); //printReport.Alignment = Alignment.center; //printReport.SpacingAfter(25d); //printReport.FontSize(16d); //printReport.Bold(); System.Console.WriteLine("7"); //var year = document.InsertParagraph("ตรวจ ณ สถานที่: "); //year.Alignment = Alignment.center; //year.SpacingAfter(10d); //year.FontSize(16d); //System.Console.WriteLine("8"); var subjectTitle = document.InsertParagraph("เรื่อง/ประเด็น/โครงการที่ตรวจติดตาม"); subjectTitle.Alignment = Alignment.left; //subjectTitle.SpacingAfter(10d); subjectTitle.FontSize(16d); subjectTitle.Bold(); System.Console.WriteLine("8"); var subject = document.InsertParagraph(""); int s = 0; for (var i = 0; i < model.subjectData.Length; i++) { s += 1; subject.FontSize(16d).Append(s.ToString()).Append(") ").Append(model.subjectData[i] + "\n").FontSize(16d); } var detailTitle = document.InsertParagraph("ผลการตรวจ"); detailTitle.SpacingBefore(10d); detailTitle.FontSize(16d); detailTitle.Bold(); var detail = document.InsertParagraph(electronicBook.Detail); detail.SpacingBefore(5d); detail.FontSize(16d); // detail.UnderlineColor(Color.Black); // detail.UnderlineStyle(UnderlineStyle.dotted); var suggestionTitle = document.InsertParagraph("ปัญหาและอุปสรรค"); suggestionTitle.SpacingBefore(15d); suggestionTitle.FontSize(16d); suggestionTitle.Bold(); var suggestion = document.InsertParagraph(electronicBook.Problem); suggestion.SpacingBefore(5d); suggestion.FontSize(16d); // suggestion.UnderlineColor(Color.Black); // suggestion.UnderlineStyle(UnderlineStyle.dotted); var commandTitle = document.InsertParagraph("ข้อเสนอแนะ"); commandTitle.SpacingBefore(15d); commandTitle.FontSize(16d); commandTitle.Bold(); var command = document.InsertParagraph(electronicBook.Suggestion); command.SpacingBefore(5d); command.FontSize(16d); // command.UnderlineColor(Color.Black); // command.UnderlineStyle(UnderlineStyle.dotted); //command.InsertPageBreakAfterSelf(); System.Console.WriteLine("11"); //System.Console.WriteLine("9"); //var region = document.InsertParagraph("เขตตรวจราชการที่: " + model.reportData2[i].region + "(จังหวัด: " + model.reportData2[i].province + ")"); //region.Alignment = Alignment.center; //region.SpacingAfter(30d); //region.FontSize(16d); //var statusReport = document.InsertParagraph("สถานะของรายงาน: " + exportData.Status); //statusReport.FontSize(16d); //statusReport.Alignment = Alignment.right; //var monitorTopic = document.InsertParagraph("หัวข้อการตรวจติดตาม: " + exportData.MonitoringTopics); //monitorTopic.SpacingBefore(15d); //monitorTopic.FontSize(16d); //monitorTopic.Bold(); //System.Console.WriteLine("99"); var inspectorTitle = document.InsertParagraph("คำแนะนำผู้ตรวจราชการ"); inspectorTitle.SpacingBefore(30d); inspectorTitle.SpacingAfter(5d); inspectorTitle.FontSize(16d); inspectorTitle.Bold(); int dataCount = 0; dataCount = model.printReport.Count(); dataCount += 1; System.Console.WriteLine("Data Count: " + dataCount); // Add a table in a document of 1 row and 3 columns. var columnWidths = new float[] { 40f, 250f, 90f, 120f, }; var t = document.InsertTable(dataCount, columnWidths.Length); //System.Console.WriteLine("8"); //// Set the table's column width and background t.SetWidths(columnWidths); t.AutoFit = AutoFit.Contents; t.Alignment = Alignment.center; var row = t.Rows.First(); //System.Console.WriteLine("9"); // Fill in the columns of the first row in the table. //for (int i = 0; i < row.Cells.Count; ++i) //{ row.Cells[0].Paragraphs.First().Append("ลำดับ").FontSize(16d).Alignment = Alignment.center; row.Cells[1].Paragraphs.First().Append("คำแนะนำหรือสั่งการของผู้ตรวจ").FontSize(16d).Alignment = Alignment.center; row.Cells[2].Paragraphs.First().Append("ความเห็นผู้ตรวจ").FontSize(16d).Alignment = Alignment.center; row.Cells[3].Paragraphs.First().Append("ลายมือชื่อผู้ตรวจ").FontSize(16d).Alignment = Alignment.center; System.Console.WriteLine("10"); //} // Add rows in the table. int j = 0; for (int k = 0; k < model.printReport.Length; k++) { j += 1; System.Console.WriteLine("10.1"); System.Console.WriteLine("9.1: " + model.printReport[k].inspectorDescription); t.Rows[j].Cells[0].Paragraphs[0].Append(j.ToString()).FontSize(16d).Alignment = Alignment.center; t.Rows[j].Cells[1].Paragraphs[0].Append(model.printReport[k].inspectorDescription).FontSize(16d); t.Rows[j].Cells[2].Paragraphs[0].Append(model.printReport[k].approve).FontSize(16d); if (model.printReport[k].inspectorSign != null && model.printReport[k].inspectorSign != "null" && model.printReport[k].inspectorSign != "") { System.Console.WriteLine("9.3: " + model.printReport[k].inspectorSign); var myImageFullPath2 = filePath2 + model.printReport[k].inspectorSign; Image image2 = document.AddImage(myImageFullPath2); System.Console.WriteLine("JJJJJ: "); Picture picture2 = image2.CreatePicture(30, 30); t.Rows[j].Cells[3].Paragraphs[0].AppendPicture(picture2).SpacingBefore(3d).Append("\n" + model.printReport[k].inspectorName).FontSize(16d).Alignment = Alignment.center; } else { System.Console.WriteLine("9.4: "); t.Rows[j].Cells[3].Paragraphs[0].Append(model.printReport[k].inspectorName).FontSize(16d).Alignment = Alignment.center; } System.Console.WriteLine("10"); } // Set a blank border for the table's top/bottom borders. var blankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White); //t.SetBorder(TableBorderType.Bottom, blankBorder); //t.SetBorder(TableBorderType.Top, blankBorder); // document.InsertSectionPageBreak(); System.Console.WriteLine("IN DEPARTMENT"); var departmentTitle = document.InsertParagraph("การดำเนินการของหน่วยรับตรวจ"); departmentTitle.SpacingBefore(30d); departmentTitle.SpacingAfter(5d); departmentTitle.FontSize(16d); departmentTitle.Bold(); System.Console.WriteLine("IN DEPARTMENT2"); int dataCount2 = 0; dataCount2 = model.printReport2.Count(); dataCount2 += 1; System.Console.WriteLine("Data Count department: " + dataCount2); // Add a table in a document of 1 row and 3 columns. var columnWidths2 = new float[] { 40f, 250f, 80f, 120f, }; var t2 = document.InsertTable(dataCount2, columnWidths2.Length); //System.Console.WriteLine("8"); //// Set the table's column width and background t2.SetWidths(columnWidths2); t2.AutoFit = AutoFit.Contents; t2.Alignment = Alignment.center; var row2 = t2.Rows.First(); //System.Console.WriteLine("9"); // Fill in the columns of the first row in the table. //for (int i = 0; i < row.Cells.Count; ++i) //{ row2.Cells[0].Paragraphs.First().Append("ลำดับ").FontSize(16d).Alignment = Alignment.center; row2.Cells[1].Paragraphs.First().Append("การดำเนินการของหน่วยรับตรวจ").FontSize(16d).Alignment = Alignment.center; row2.Cells[2].Paragraphs.First().Append("หน่วยรับตรวจ").FontSize(16d).Alignment = Alignment.center; row2.Cells[3].Paragraphs.First().Append("ลายมือชื่อผู้รับตรวจ").FontSize(16d).Alignment = Alignment.center; System.Console.WriteLine("10"); //} // Add rows in the table. int j2 = 0; for (int k = 0; k < model.printReport2.Length; k++) { j2 += 1; t2.Rows[j2].Cells[0].Paragraphs[0].Append(j2.ToString()).FontSize(16d).Alignment = Alignment.center; t2.Rows[j2].Cells[1].Paragraphs[0].Append(model.printReport2[k].departmentDescription).FontSize(16d); t2.Rows[j2].Cells[2].Paragraphs[0].Append(model.printReport2[k].department).FontSize(16d); if (model.printReport2[k].departmentSign != null && model.printReport2[k].departmentSign != "null" && model.printReport2[k].departmentSign != "") { var myImageFullPath3 = filePath2 + model.printReport2[k].departmentSign; Image image3 = document.AddImage(myImageFullPath3); System.Console.WriteLine("JJJJJ: "); Picture picture2 = image3.CreatePicture(30, 30); t2.Rows[j2].Cells[3].Paragraphs[0].AppendPicture(picture2).SpacingBefore(3d).Append("\n" + model.printReport2[k].departmentName).FontSize(16d).Alignment = Alignment.center; } else { t2.Rows[j2].Cells[3].Paragraphs[0].Append(model.printReport2[k].departmentName).FontSize(16d); } System.Console.WriteLine("10"); } // Set a blank border for the table's top/bottom borders. var blankBorder2 = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White); document.Save(); Console.WriteLine("\tCreated: InsertHorizontalLine.docx\n"); } return(Ok(new { data = filename })); }
//public FormattedText(string textToFormat, Typeface typeface, double emSize, System.Windows.Media.Brush foreground) //{ //} //public String titleFormat { get; set; } //private void CreateDocument() //{ // DateTime Datum = DateTime.Now; // string selected = cmbKl.Text; // string id = cmbKl.SelectedValue.ToString(); // var klt = Convert.ToInt32(id); // string file = ($"{selected}{Datum:yyyy.M.dd}.pdf"); // // string fileName = @"C:\Users\HP\source\repos\ProjectInlog\ProjectInlog\bin\Debug\temp1.docx"; // // var doc = DocX.Create(file); // // using (ProjectContext ctx = new ProjectContext()) // // { // // var sell = ctx.OrderLines.Join(ctx.Orders, // // s => s.Order.OrderId, // // a => a.OrderId, // // (s, a) => new { s, a }) // // .Where(z => z.a.ClientId == klt); // // var best = sell.Join(ctx.Products, // // sa => sa.s.ProductId, // // alb => alb.ProductId, // // // (sa, alb) => new { Name = alb.Description, Price = alb.Price, Aantal = sa.s.O_Aantal, Kl = sa.a.ClientId, Ordr = sa.a.OrderId, Tot = Math.Round(alb.Price * sa.s.O_Aantal) }).ToList(); // // (sa, alb) => new { sa, alb }); // // var ok = best.Join(ctx.Clients, // // b => b.sa.a.ClientId, // // c => c.ClientId, // // (b, c) => new // // { // // Name = b.alb.Description, // // Price = b.alb.Price, // // Aantal = b.sa.s.O_Aantal, // // Kl = b.sa.a.ClientId, // // Ordr = b.sa.a.OrderId, // // KL_name = c.C_Name, // // KL_adres = c.C_Adress, // // KL_woonplaats = c.C_Woonplaats, // // KL_postcode = c.C_PostCode, // // KL_btw = c.C_BtwNr, // // Tot = Math.Round(b.alb.Price * b.sa.s.O_Aantal) // // }).ToList(); // using (PdfDocument pdf = new PdfDocument()) // { // PdfPage Page = pdf.AddPage(); // PdfPage page = pdf.Pages.Add(); // PdfGraphics graph = page.Graphics; // //PdfSharp.Pdf.PdfDocument pdf = new PdfSharp.Pdf.PdfDocument(); // ////Add a page // //PdfSharp.Pdf.PdfPage page = pdf.AddPage(); // // PdfGraphics graph = ; // PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 24, PdfFontStyle.Bold); // PdfFont font1 = new PdfStandardFont(PdfFontFamily.TimesRoman, 14); // graph.DrawString("Factuur", font, PdfBrushes.Black, new PointF(10, 50)); // ; // //string file = ($"{selected}{Datum:yyyy.M.dd}.txt"); // using (ProjectContext ctx = new ProjectContext()) // { // var sell = ctx.OrderLines.Join(ctx.Orders, // s => s.Order.OrderId, // a => a.OrderId, // (s, a) => new { s, a }) // .Where(z => z.a.ClientId == klt); // var best = sell.Join(ctx.Products, // sa => sa.s.ProductId, // alb => alb.ProductId, // // (sa, alb) => new { Name = alb.Description, Price = alb.Price, Aantal = sa.s.O_Aantal, Kl = sa.a.ClientId, Ordr = sa.a.OrderId, Tot = Math.Round(alb.Price * sa.s.O_Aantal) }).ToList(); // (sa, alb) => new { sa, alb }); // var ok = best.Join(ctx.Clients, // b => b.sa.a.ClientId, // c => c.ClientId, // (b, c) => new // { // Name = b.alb.Description, // Price = b.alb.Price, // Aantal = b.sa.s.O_Aantal, // Kl = b.sa.a.ClientId, // Ordr = b.sa.a.OrderId, // KL_name = c.C_Name, // KL_adres = c.C_Adress, // KL_woonplaats = c.C_Woonplaats, // KL_postcode = c.C_PostCode, // KL_btw = c.C_BtwNr, // Tot = Math.Round(b.alb.Price * b.sa.s.O_Aantal) // }).ToList(); // var eind = false; // var tel = 0; // double tota = 0; // // graph.DrawString(, font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft); // var i = 150; // var j = 50; // foreach (var item in ok) // { // if (tel == 0) // { // var gem = item.KL_postcode + " " + item.KL_woonplaats; // graph.DrawString(item.KL_name, font1, PdfBrushes.Black, new PointF(10, 30)); // graph.DrawString(item.KL_adres, font1, PdfBrushes.Black, new PointF(10, 40)); // graph.DrawString(gem, font1, PdfBrushes.Black, new PointF(10, 50)); // graph.DrawString(item.KL_btw, font1, PdfBrushes.Black, new PointF(10, 60)); // graph.DrawString("Product", font1, PdfBrushes.Black, new PointF(10, 70)); // DataTable datatable = new DataTable(); // datatable.Columns.Add("Product"); // datatable.Columns.Add("Description"); // datatable.Columns.Add("Quantity"); // datatable.Columns.Add("Price"); // tel = 1; // } // graph.DrawString(item.Name, font1, PdfBrushes.Black, new PointF(0, 160)); // graph.DrawString((item.Aantal).ToString(), font1, PdfBrushes.Black, new PointF(10, 30)); // graph.DrawString((item.Price).ToString(), font1, PdfBrushes.Black, new PointF(10, 30)); // graph.DrawString((item.Tot).ToString(), font1, PdfBrushes.Black, new PointF(10, 30)); // } // } // pdf.Save("firstpage.pdf"); // Process.Start("Firstpage.pdf"); // pdf.Close(true); // } //} private void CreateTest() { DateTime Datum = DateTime.Now; string selected = cmbKl.Text; if (selected == "") { MessageBox.Show("Kies een klant voor het maken van de factuur"); } else { string id = cmbKl.SelectedValue.ToString(); var klt = Convert.ToInt32(id); string file = ($"{selected}{Datum:yyyy.M.dd}.docx"); //string file2 = ($"{selected}{Datum:yyyy.M.dd}.pdf"); string dat = Datum.ToString("dd MMMM yyyy"); string title = "Factuur "; Formatting titleFormat = new Formatting(); //Specify font family titleFormat.FontFamily = new Xceed.Document.NET.Font("arial"); //Specify font size titleFormat.Size = 25D; titleFormat.Position = 30; titleFormat.FontColor = System.Drawing.Color.Orange; titleFormat.UnderlineColor = System.Drawing.Color.Gray; titleFormat.Italic = true; titleFormat.Bold = true; titleFormat.Spacing = 20; Formatting textParagraphFormat = new Formatting(); textParagraphFormat.FontFamily = new Xceed.Document.NET.Font("times new roman"); textParagraphFormat.Size = 20D; textParagraphFormat.Spacing = 1; //string fileName = @"firstpage.docx"; var doc = DocX.Create(file); // doc.InsertParagraph("Factuur"); Table v = doc.AddTable(1, 2); v.Alignment = Alignment.center; v.Design = TableDesign.ColorfulList; Image img = doc.AddImage(@"C:\Users\HP\source\repos\ProjectInlog\ProjectInlog\Images\meubels.png"); Picture pic = img.CreatePicture(); Paragraph p1 = doc.InsertParagraph(); p1.AppendPicture(pic); // Paragraph.AppendPicture(pic); Paragraph paragraphTitle = doc.InsertParagraph(title, false, titleFormat); //v.Rows[0].Cells[0].Paragraphs.First().Append(p1); //v.Rows[0].Cells[1].Paragraphs.First().Append("BB"); using (ProjectContext ctx = new ProjectContext()) { //DataRow LastRow = ctx.Invoices.Rows.Count() ; //var aan = Convert.ToInt32(ctx.Invoices.LastOrDefault()); var sell = ctx.OrderLines.Join(ctx.Orders, s => s.Order.OrderId, a => a.OrderId, (s, a) => new { s, a }) .Where(z => z.a.ClientId == klt); var best = sell.Join(ctx.Products, sa => sa.s.ProductId, alb => alb.ProductId, // (sa, alb) => new { Name = alb.Description, Price = alb.Price, Aantal = sa.s.O_Aantal, Kl = sa.a.ClientId, Ordr = sa.a.OrderId, Tot = Math.Round(alb.Price * sa.s.O_Aantal) }).ToList(); (sa, alb) => new { sa, alb }); var ok = best.Join(ctx.Clients, b => b.sa.a.ClientId, c => c.ClientId, (b, c) => new { Name = b.alb.Description, Price = b.alb.Price, Aantal = b.sa.s.O_Aantal, Kl = b.sa.a.ClientId, Ordr = b.sa.a.OrderId, KL_name = c.C_Name, KL_adres = c.C_Adress, KL_woonplaats = c.C_Woonplaats, KL_postcode = c.C_PostCode, KL_btw = c.C_BtwNr, Tot = Math.Round((b.alb.Price * b.sa.s.O_Aantal), 2) }).ToList(); if (ok.Count != 0) { //var eind = false; var tel = 0; double tota = 0; var tt = 0; // //var ord = 0; Table t = doc.AddTable(21, 5); t.Alignment = Alignment.center; t.Design = TableDesign.ColorfulList; var i = 1; foreach (var item in ok) { if (tel == 0) { var gem = item.KL_postcode + " " + item.KL_woonplaats; doc.InsertParagraph($"FACTUUR { item.Ordr} FURNITURE"); doc.InsertParagraph(); doc.InsertParagraph($"{item.KL_name} Industrieweg 20"); doc.InsertParagraph($"{item.KL_adres} 2440 GEEL"); doc.InsertParagraph(gem); doc.InsertParagraph($"BTW {item.KL_btw}"); doc.InsertParagraph(); tel = 1; t.Rows[0].Cells[0].Paragraphs.First().Append("Omschrijving"); t.Rows[0].Cells[1].Paragraphs.First().Append("Aantal"); t.Rows[0].Cells[2].Paragraphs.First().Append("EenheidsPrijs"); t.Rows[0].Cells[3].Paragraphs.First().Append("Totaal"); t.Rows[0].Cells[4].Paragraphs.First().Append("Order"); tt = item.Ordr; } //Create Table with 24 rows and 5 columns. //Fill cells by adding text. t.Rows[i].Cells[0].Paragraphs.First().Append(item.Name); t.Rows[i].Cells[1].Paragraphs.First().Append(item.Aantal.ToString()); t.Rows[i].Cells[2].Paragraphs.First().Append("€" + item.Price.ToString()); t.Rows[i].Cells[3].Paragraphs.First().Append("€" + item.Tot.ToString()); t.Rows[i].Cells[4].Paragraphs.First().Append(item.Ordr.ToString()); tota += item.Tot; i += 1; } ctx.Invoices.Add(new Invoice() { Amount = tota, Status = false, CreatedAt = Datum, PayedAt = Datum, OrderId = tt }); ctx.SaveChanges(); t.Rows[18].Cells[2].Paragraphs.First().Append("Totaal zonder BTW"); t.Rows[18].Cells[3].Paragraphs.First().Append("€" + tota.ToString()); // t.Rows[21].Cells[0].); var btw = Math.Round((tota * 0.21), 2); t.Rows[19].Cells[2].Paragraphs.First().Append("BTW bedrag"); t.Rows[19].Cells[3].Paragraphs.First().Append("€" + btw.ToString()); var total = Math.Round((tota + btw), 2); t.Rows[20].Cells[2].Paragraphs.First().Append("Totaal met BTW"); t.Rows[20].Cells[3].Paragraphs.First().Append("€" + total.ToString()); doc.InsertTable(t); doc.InsertParagraph(); doc.InsertParagraph("Ondernemingsnummer: 0123 456 789"); doc.InsertParagraph("Bank : ING Belgium NV"); doc.InsertParagraph("SWIFT/BIC : BBRUBEBB"); doc.InsertParagraph("IBAN : BE33 7894 6324 4587"); doc.Save(); MessageBoxResult result = MessageBox.Show("Wenst u het factuur te beijken?", "Factuur aangemaakt", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { //Process process = new Process(); //process.StartInfo.FileName = file; //process.Start(); Process.Start("WINWORD.EXE", file); } // Process.Start("WINWORD.EXE", file); } else { MessageBox.Show("er is geen verkoop voor de gekozen klant"); } } } }
private void btnGenerate_Click(object sender, EventArgs e) { //Path to save the sheet string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string fileName = Character.Name.Replace(' ', '_') + ".docx"; string savePath = Path.Combine(desktopPath, fileName); //Create Title string title = Character.Name; //Formatting Title Formatting titleFormat = new Formatting(); titleFormat.FontFamily = new Xceed.Document.NET.Font("Calibri Light"); titleFormat.Size = 28D; titleFormat.FontColor = System.Drawing.Color.Black; //Create Subtitle string subtitle = Character.Title + ", " + Character.Rank + " '" + Character.Group + "'" + Environment.NewLine + Environment.NewLine + Environment.NewLine; //Formatting Subtitle Formatting textParagraphFormat = new Formatting(); textParagraphFormat.FontFamily = new Xceed.Document.NET.Font("Calibri"); textParagraphFormat.Size = 11D; textParagraphFormat.FontColor = ColorTranslator.FromHtml("#5A5A5A"); //Create word document var doc = DocX.Create(savePath); //Insert title Paragraph paragraphTitle = doc.InsertParagraph(title, false, titleFormat); paragraphTitle.Alignment = Alignment.center; //Insert subtitle Paragraph paragraphSubTitle = doc.InsertParagraph(subtitle, false, textParagraphFormat); paragraphSubTitle.Alignment = Alignment.center; //Create Table with 11 rows and 3 columns. Table t = doc.AddTable(11, 3); t.Alignment = Alignment.center; Border tableBorder = new Border(Xceed.Document.NET.BorderStyle.Tcbs_none, 0, 0, Color.Black); t.SetBorder(TableBorderType.Bottom, tableBorder); t.SetBorder(TableBorderType.InsideH, tableBorder); t.SetBorder(TableBorderType.InsideV, tableBorder); t.SetBorder(TableBorderType.Left, tableBorder); t.SetBorder(TableBorderType.Right, tableBorder); t.SetBorder(TableBorderType.Top, tableBorder); t.SetWidths(new float[] { 180f, 135, 135f }); //Add image: string path = Path.Combine("Images", Character.imageName); Xceed.Document.NET.Image img = doc.AddImage(path); Picture p = img.CreatePicture(230, 150); t.MergeCellsInColumn(0, 0, 10); t.Rows[0].Cells[0].Paragraphs.First().AppendPicture(p); if (Character.imageName != "Images/mkrr.jpg") //default picture path { File.Delete(path); } //Add statistics: t.Rows[0].Cells[1].Paragraphs.First().Append("Poziom: " + Character.Level).SpacingAfter(7d); t.Rows[1].Cells[1].Paragraphs.First().Append("Klasa: " + Character.Class).SpacingAfter(7d); t.Rows[2].Cells[1].Paragraphs.First().Append("Punkty Życia: " + Character.HP).SpacingAfter(7d); t.Rows[3].Cells[1].Paragraphs.First().Append("Zwinność: " + Character.Agility).SpacingAfter(7d); t.Rows[4].Cells[1].Paragraphs.First().Append("Szybkość: " + Character.Speed).SpacingAfter(7d); t.Rows[5].Cells[1].Paragraphs.First().Append("Wygląd: " + Character.Appearance).SpacingAfter(7d); t.Rows[6].Cells[1].Paragraphs.First().Append("Wprawa: " + Character.Dexterity).SpacingAfter(7d); t.Rows[7].Cells[1].Paragraphs.First().Append("Unik: " + Character.Dodge).SpacingAfter(7d); t.Rows[8].Cells[1].Paragraphs.First().Append("Siła: " + Character.Strength).SpacingAfter(7d); t.Rows[9].Cells[1].Paragraphs.First().Append("Atak Bazowy: " + Character.BaseAttack).SpacingAfter(7d); //Add talents: Int32 Index = 0; for (int i = 0; i < 12; ++i) { switch (i) { case 0: { if (Character.TacticAnalysis > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Analiza Taktyczna: " + new String('*', Character.TacticAnalysis)); Index++; } break; } case 1: { if (Character.Tactics > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Taktyka: " + new String('*', Character.Tactics)); Index++; } break; } case 2: { if (Character.Knowledge > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Wiedza: " + new String('*', Character.Knowledge)); Index++; } break; } case 3: { if (Character.MeleeRange > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Walka Bezp.: " + new String('*', Character.MeleeRange)); Index++; } break; } case 4: { if (Character.ShortRange > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Walka Krótka: " + new String('*', Character.ShortRange)); Index++; } break; } case 5: { if (Character.Sorcery > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Czarnoksięstwo: " + new String('*', Character.Sorcery)); Index++; } break; } case 6: { if (Character.Faith > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Wiara: " + new String('*', Character.Faith)); Index++; } break; } case 7: { if (Character.Symbolics > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Symbolika: " + new String('*', Character.Symbolics)); Index++; } break; } case 8: { if (Character.PassiveIncome > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Pasywny Przychód: " + new String('*', Character.PassiveIncome)); Index++; } break; } case 9: { if (Character.WeaponMastery > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Mistrzostwo Bronii: " + new String('*', Character.WeaponMastery)); Index++; } break; } case 10: { if (Character.SpellMastery > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Mistrzostwo Magii: " + new String('*', Character.SpellMastery)); Index++; } break; } case 11: { if (Character.RavenAgility > 0) { t.Rows[Index].Cells[2].Paragraphs.First().Append("Krucza Zwinność: " + new String('*', Character.RavenAgility)); Index++; } break; } } } //Insert the table doc.InsertTable(t); //Insert an empty line doc.InsertParagraph(Environment.NewLine); //Create Table with 3 columns and enough rows to hold all skills, equipment and items Int32 rowsRequired = Character.Equipment.Count > Character.Skills.Count ? (Character.Equipment.Count > Character.ItemCount ? Character.Equipment.Count : Character.ItemCount) : (Character.Skills.Count > Character.ItemCount ? Character.Skills.Count : Character.ItemCount); rowsRequired = rowsRequired < 2 ? 2 : rowsRequired; Table tableBottom = doc.AddTable(rowsRequired + 1, 3); //first row is a header row tableBottom.Alignment = Alignment.center; Border tableBottomBorder = new Border(Xceed.Document.NET.BorderStyle.Tcbs_none, 0, 0, Color.Black); tableBottom.SetBorder(TableBorderType.Bottom, tableBottomBorder); tableBottom.SetBorder(TableBorderType.InsideH, tableBottomBorder); tableBottom.SetBorder(TableBorderType.InsideV, tableBottomBorder); tableBottom.SetBorder(TableBorderType.Left, tableBottomBorder); tableBottom.SetBorder(TableBorderType.Right, tableBottomBorder); tableBottom.SetBorder(TableBorderType.Top, tableBottomBorder); tableBottom.SetWidths(new float[] { 150f, 150, 150f }); //Merge cells in the columns tableBottom.MergeCellsInColumn(0, 1, rowsRequired); tableBottom.MergeCellsInColumn(1, 1, rowsRequired); tableBottom.MergeCellsInColumn(2, 1, rowsRequired); //Create Headers For The Bottom Table string skillsHeader = "Umiejętności" + Environment.NewLine; string equipmentHeader = "Ekwipunek" + Environment.NewLine; string itemsHeader = "Przedmioty" + Environment.NewLine; //Formatting The Headers Formatting bottomTableHeaderFormat = new Formatting(); bottomTableHeaderFormat.FontFamily = new Xceed.Document.NET.Font("Calibri"); bottomTableHeaderFormat.Size = 14D; bottomTableHeaderFormat.FontColor = Color.Black; bottomTableHeaderFormat.UnderlineColor = Color.Black; //Insert the headers tableBottom.Rows[0].Cells[0].InsertParagraph(skillsHeader, false, bottomTableHeaderFormat).Bold(); tableBottom.Rows[0].Cells[1].InsertParagraph(equipmentHeader, false, bottomTableHeaderFormat).Bold(); tableBottom.Rows[0].Cells[2].InsertParagraph(itemsHeader, false, bottomTableHeaderFormat).Bold(); //List all skills foreach (Skill skill in Character.Skills) { String line = "- " + Skill.listSkill(skill); tableBottom.Rows[1].Cells[0].Paragraphs.First().Append(line); Index++; } //List all equipment foreach (Equipment item in Character.Equipment) { String line = "- " + Equipment.listBuffs(item); tableBottom.Rows[1].Cells[1].Paragraphs.First().Append(line); Index++; } //List all items if (Character.Cash > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- " + Character.Cash + " zł" + Environment.NewLine); } if (Character.Oasis > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Oasis: " + Character.Oasis + Environment.NewLine); } if (Character.Monster > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Monster: " + Character.Monster + Environment.NewLine); } if (Character.Doritos > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Doritos: " + Character.Doritos + Environment.NewLine); } if (Character.Coke > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Coke: " + Character.Coke + Environment.NewLine); } if (Character.ColaOriginal > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Cola Original: " + Character.ColaOriginal + Environment.NewLine); } if (Character.Crawford > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Crawford & Tilley: " + Character.Crawford + Environment.NewLine); } if (Character.HotDog > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- HotDog: " + Character.HotDog + Environment.NewLine); } if (Character.Brownie > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Brownie: " + Character.Brownie + Environment.NewLine); } if (Character.WhitePotion > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- White Potion: " + Character.WhitePotion + Environment.NewLine); } if (Character.YellowPotion > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Yellow Potion: " + Character.YellowPotion + Environment.NewLine); } if (Character.Maltesers > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Maltesers: " + Character.Maltesers + Environment.NewLine); } if (Character.RedPotion > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Red Potion: " + Character.RedPotion + Environment.NewLine); } if (Character.GreenPotion > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Green Potion: " + Character.GreenPotion + Environment.NewLine); } if (Character.MauvePotion > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Mauve Potion: " + Character.MauvePotion + Environment.NewLine); } if (Character.DairyMilk > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Dairy Milk: " + Character.DairyMilk + Environment.NewLine); } if (Character.Gfuel > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- GFuel: " + Character.Gfuel + Environment.NewLine); } if (Character.Coffee > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Coffee: " + Character.Coffee + Environment.NewLine); } if (Character.Dobrowianka > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Dobrowianka: " + Character.Dobrowianka + Environment.NewLine); } if (Character.MtnDew > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Mtn Dew: " + Character.MtnDew + Environment.NewLine); } if (Character.DrPepper > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Dr Pepper: " + Character.DrPepper + Environment.NewLine); } if (Character.HoolaHoops > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Hoola Hoops: " + Character.HoolaHoops + Environment.NewLine); } if (Character.BarrCreamSoda > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Barr's Cream Soda: " + Character.BarrCreamSoda + Environment.NewLine); } if (Character.StrSeed > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Strength Seed: " + Character.StrSeed + Environment.NewLine); } if (Character.AgiSeed > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Agility Seed: " + Character.AgiSeed + Environment.NewLine); } if (Character.AppSeed > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Appearance Seed: " + Character.AppSeed + Environment.NewLine); } if (Character.ResSeed > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Resilience Seed: " + Character.ResSeed + Environment.NewLine); } if (Character.SpdSeed > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Speed Seed: " + Character.SpdSeed + Environment.NewLine); } if (Character.HpSeed > 0) { tableBottom.Rows[1].Cells[2].Paragraphs.First().Append("- Health Seed: " + Character.HpSeed + Environment.NewLine); } //Insert the table doc.InsertTable(tableBottom); //Save the document to its final form doc.Save(); //Generate and open the document Process.Start("WINWORD.EXE", savePath); }
public void BuildDocument(string[] ScriptItems) { string FullDocFileName = Cappy.FolderName + @"\" + Cappy.Prefix + Cappy.FieldSeperator + Cappy.GetSaveTime() + Cappy.FieldSeperator + Cappy.DocExtension; using (DocX document = DocX.Create(FullDocFileName)) { foreach (string ScriptItem in ScriptItems) { if (ScriptItem != null) { // instantiate some // TODO: this loop contains alot of copy paste and hackiness because im tired and shit, please clean it up string[] Fields = ScriptItem.Split(';'); string ButtonAction = String.Empty; string ButtonClicked = String.Empty; string WindowText = String.Empty; string FullFileName = String.Empty; string FocusFileName = String.Empty; if (Fields.Length == 5) { ButtonAction = Fields[0]; ButtonClicked = Fields[1]; WindowText = Fields[2]; FullFileName = Fields[3]; FocusFileName = Fields[4]; } else if (Fields.Length == 3) { ButtonAction = Fields[0]; ButtonClicked = Fields[1]; FullFileName = Fields[2]; } string ParagraphText; if (Fields.Length == 5) { // because alot of things in windows have weird window names, or you perform more advanced actions on them then click, let's define some things to make our documents nicer if (!String.IsNullOrEmpty(WindowText)) { ParagraphText = ButtonAction + " " + WindowText; } else { // if we can't determine what was clicked, resort to this. ParagraphText = ButtonAction + " << FILL IN MISSING TEXT >>"; } // create our paragraph to work with Paragraph p = document.InsertParagraph(); // get bitmaps of the desired images System.Drawing.Image FullCaptureImage = GetImage(FullFileName); System.Drawing.Image FocusCaptureImage = GetImage(FocusFileName); // instantiate memory streams for writing our bitmaps to MemoryStream FullCaptureStream = new MemoryStream(); MemoryStream FocusCaptureStream = new MemoryStream(); // save our bitmaps into the memory stream FullCaptureImage.Save(FullCaptureStream, FullCaptureImage.RawFormat); FocusCaptureImage.Save(FocusCaptureStream, FocusCaptureImage.RawFormat); // set position in memory stream FullCaptureStream.Seek(0, SeekOrigin.Begin); FocusCaptureStream.Seek(0, SeekOrigin.Begin); // create the base image to work with, and add it to our document object for later Xceed.Document.NET.Image FullCapture = document.AddImage(FullCaptureStream); Xceed.Document.NET.Image FocusCapture = document.AddImage(FocusCaptureStream); // convert image to picture usable in a document Picture FullCapturePic = FullCapture.CreatePicture(); Picture FocusCapturePic = FocusCapture.CreatePicture(); // because screenshots will be a constant size, simply set a scalar to our desired resolution. we can also use this for calculating the focus size. const int imgWidth = 512; const int imgHeight = 288; // apply aforementioned scalar FullCapturePic.Width = imgWidth; FullCapturePic.Height = imgHeight; // create focused screenshot size Size focusbbox = new Size(imgWidth, imgHeight); // get the scaled version of focused image Size focusSize = ExpandToBound(FocusCaptureImage.Size, focusbbox); FocusCapturePic.Width = focusSize.Width; FocusCapturePic.Height = focusSize.Height; // insert bullet list var list = document.AddList(listType: ListItemType.Numbered, continueNumbering: true); document.AddListItem(list, ParagraphText, 0, listType: ListItemType.Numbered); // insert images p.InsertListBeforeSelf(list); p.AppendLine().AppendPicture(FullCapturePic); p.AppendLine(); // space the images p.AppendLine().AppendPicture(FocusCapturePic); p.AppendLine(); // leave a space for writing p.InsertPageBreakAfterSelf(); // release unneeded resources FullCaptureImage.Dispose(); FullCaptureStream.Dispose(); FocusCaptureImage.Dispose(); FocusCaptureStream.Dispose(); } if (Fields.Length == 3) { ParagraphText = ButtonAction + " " + ButtonClicked; // create our paragraph to work with Paragraph p = document.InsertParagraph(); // get bitmaps of the desired images System.Drawing.Image FullCaptureImage = GetImage(FullFileName); // instantiate memory streams for writing our bitmaps to MemoryStream FullCaptureStream = new MemoryStream(); // save our bitmaps into the memory stream FullCaptureImage.Save(FullCaptureStream, FullCaptureImage.RawFormat); // set position in memory stream FullCaptureStream.Seek(0, SeekOrigin.Begin); // create the base image to work with, and add it to our document object for later Xceed.Document.NET.Image FullCapture = document.AddImage(FullCaptureStream); // convert image to picture usable in a document Picture FullCapturePic = FullCapture.CreatePicture(); // because screenshots will be a constant size, simply set a scalar to our desired resolution. we can also use this for calculating the focus size. const int imgWidth = 512; const int imgHeight = 288; // apply aforementioned scalar FullCapturePic.Width = imgWidth; FullCapturePic.Height = imgHeight; // insert bullet list var list = document.AddList(listType: ListItemType.Numbered, continueNumbering: true); document.AddListItem(list, ParagraphText, 0, listType: ListItemType.Numbered); // insert images p.InsertListBeforeSelf(list); p.AppendLine().AppendPicture(FullCapturePic); p.AppendLine(); // space the images // leave a space for writing p.InsertPageBreakAfterSelf(); // release unneeded resources FullCaptureImage.Dispose(); FullCaptureStream.Dispose(); } } } document.Save(); } }