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> void createword() { try { lstFM = FDXXtbl.GetInfo(); lstp = FDXXtbl.Parcels(lstFM); using (DocX document = DocX.Create(WordPath)) { Addcover(document); //添加封面 document.InsertSectionPageBreak(true); //分节符 Addtoc(document); //添加目录 document.InsertSectionPageBreak(true); //分节符 Addintro(document); //添加概述 Addloc(document); //添加位置分布图 Addfdxx(document); //添加房地信息统计 parcelHelper phelper = new parcelHelper("通湖路699号地块"); //添加各个地块的信息 phelper.insertInfo(document, lstFM, lstp); document.Save(); } Console.WriteLine("创建文档成功!"); } catch (System.Exception ex) { LogHelper.WriteLog(typeof(Program), ex); Console.WriteLine("创建文档失败!请查看日志!"); } }
public void SectionPageBreakLandscapePortraitLandscape() { using (var doc = new DocX()) { doc.Create(); doc.Orientation = PageOrientation.Landscape; doc.AddParagraph().Append("Landscape"); doc.InsertSectionPageBreak(); doc.Orientation = PageOrientation.Portrait; doc.AddParagraph().Append("Portrait"); doc.InsertSectionPageBreak(); doc.Orientation = PageOrientation.Landscape; doc.AddParagraph().Append("Landscape"); Validate(doc); doc.Close(); } }
public void AddSectionHeaderFooter() { using (var doc = new DocX()) { doc.Create(); doc.AddHeaders(); doc.AddFooters(); doc.DefaultHeader.AddParagraph().Append("Header 1"); doc.DefaultFooter.AddParagraph().Append("Footer 1"); doc.InsertSectionPageBreak(); doc.AddHeaders(); doc.AddFooters(); doc.DefaultHeader.AddParagraph().Append("Header 2"); doc.DefaultFooter.AddParagraph().Append("Footer 2"); doc.InsertSectionPageBreak(); doc.AddHeaders(); doc.AddFooters(); doc.DefaultHeader.AddParagraph().Append("Header 3"); doc.DefaultFooter.AddParagraph().Append("Footer 3"); Validate(doc); doc.Close(); } }
public void CreateDocument(string projectPath) { DocumentCreator documentCreator = new DocumentCreator(projectPath); string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); List <Documentation> documentations = documentCreator.GetAllDocuments(); this.doc = DocX.Create(path + @"\" + documentCreator.Title + ".docx"); doc.InsertParagraph($"{documentCreator.Title}", false, new Formatting() { Size = 26, FontColor = baseColor }); doc.InsertSectionPageBreak(true); int capitol = 1; foreach (Documentation documentation in documentations) { doc.InsertParagraph($"{capitol} - {documentation.Title.Replace(documentCreator.Title,"").Trim('.')}", false, new Formatting() { Size = 22 }); doc.InsertParagraph(" ", false, new Formatting() { Size = 40 }); int subCapitol = 1; foreach (KeyValuePair <string, Assembly> assembly in documentation.Pages.OrderBy(x => x.Value.Members.OrderBy(y => y.Priority).First().Priority)) { Paragraph paragraph = doc.InsertParagraph($"{capitol}.{subCapitol} - {assembly.Value.Members.First().Name}", false, new Formatting() { Size = 20 }); paragraph.IndentationBefore = 0.2f; paragraph = doc.InsertParagraph($"Namespace: {assembly.Value.Name}", false, new Formatting() { Size = 14, FontColor = Color.DarkGray }); paragraph.IndentationBefore = 0.4f; foreach (AMember member in assembly.Value.Members.OrderBy(x => x.Priority)) { WriteMember(member, false); } doc.InsertParagraph(" ", false, new Formatting() { Size = 24 }); subCapitol++; } if (capitol < documentations.Count) { doc.InsertSectionPageBreak(true); } capitol++; } doc.Save(); }
public static void GerarTabelaAreaDeEstagio(this DocX document, List <AreaEstagioCurso> areas, int IdArea) { int rows = areas.Count(); Table t = document.AddTable(rows, 2); Formatting format = new Formatting(); format.Bold = true; t.Paragraphs.ForEach(x => x.FontSize(12)); t.Paragraphs.ForEach(x => x.Font("Arial")); t.Alignment = Alignment.center; t.AutoFit = AutoFit.ColumnWidth; for (int i = 0; i <= (int)TableBorderType.InsideV; i++) { t.SetBorder((TableBorderType)i, new Border()); } for (int i = 1; i <= rows; i++) { int pos = i - 1; if (i % 7 == 0) { document.InsertSectionPageBreak(); } t.Rows[pos].Cells[1].Paragraphs[0].InsertText(areas[pos].Nome); if (areas[pos].Identificador == IdArea) { t.Rows[pos].Cells[0].Paragraphs[0].InsertText("X", false, format); } } document.InsertTable(t); }
private static void WriteUnitTestGroup(UnitTestGroupViewModel group, DocX doc) { Paragraph p; p = doc.InsertParagraph(); p.StyleName = "Heading1"; p.InsertText(group.TestId); p = doc.InsertParagraph(); p.StyleName = "Normal"; p.Italic(); p.Append(string.Format("{0}", group.ParentPath)); foreach (UnitTestObjectViewModel item in group.UnitTestObjects) { if (item is UnitTestGroupViewModel) { DocXExporter.WriteUnitTestGroup(item as UnitTestGroupViewModel, doc); } else if (item is UnitTestViewModel) { DocXExporter.WriteUnitTest(item as UnitTestViewModel, doc); } else { throw new ArgumentException("Unknown unit test object"); } doc.InsertSectionPageBreak(); } }
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); } }
/// <summary> /// Create a document and insert Sections into it. /// </summary> public static void InsertSections() { Console.WriteLine("\tInsertSections()"); // Create a document. using (DocX document = DocX.Create(SectionSample.SectionSampleOutputDirectory + @"InsertSections.docx")) { document.PageLayout.Orientation = Orientation.Portrait; // Add a title document.InsertParagraph("Inserting sections").FontSize(15d).SpacingAfter(50d).Alignment = Alignment.center; // Add 2 paragraphs document.InsertParagraph("This is the first paragraph."); document.InsertParagraph("This is the second paragraph."); // Add a paragraph and a section break. document.InsertSection(); // Add a new paragraph document.InsertParagraph("This is the third paragraph, in a new section."); // Add a paragraph and a page break. document.InsertSectionPageBreak(); document.PageLayout.Orientation = Orientation.Landscape; document.InsertParagraph("This is the fourth paragraph, in a new section."); document.InsertSectionPageBreak(); // document.PageLayout.Orientation = Orientation.Portrait; var sections = document.GetSections(); // Add a paragraph to display the result of sections. var p = document.InsertParagraph("This document contains ").Append(sections.Count.ToString()).Append(" Sections.\n"); p.SpacingBefore(40d); // Display the paragraphs count per section from this document. for (int i = 0; i < sections.Count; ++i) { var section = sections[i]; var paragraphs = section.SectionParagraphs; var nonEmptyParagraphs = paragraphs.Where(x => !string.IsNullOrEmpty(x.Text)); p.Append("Section ").Append((i + 1).ToString()).Append(" has ").Append(nonEmptyParagraphs.Count().ToString()).Append(" non-empty paragraphs.\n"); } document.Save(); Console.WriteLine("\tCreated: InsertSections.docx\n"); } }
public static void CreateDoc(string destFileName, List <CategoryModel> dbCategories, List <GuestModel> guests) { // Create a document in memory: DocX doc = DocX.Create(destFileName); GuestModel choix = Calculation.CalculateJojoscarChoice(guests); Paragraph header = doc.InsertParagraph(); header.Alignment = Alignment.center; header.Append("Le choix des Jojoscar pour la 14ème soirée des JOJOSCAR\r\n").Color(Color.DarkRed).FontSize(16).Bold(); AddChoixInDoc(choix, dbCategories, doc); doc.InsertSectionPageBreak(); List <GuestModel> statistics = Calculation.CalculateStats(guests); AddStatistics(statistics, choix, dbCategories, doc); doc.InsertSectionPageBreak(); foreach (GuestModel guest in guests) { header = doc.InsertParagraph(); header.Alignment = Alignment.center; header.Append("Vos choix pour la 14ème soirée des JOJOSCAR\r\n").Color(Color.DarkRed).FontSize(16).Bold(); header.Append(guest.FirstName + " " + guest.LastName + " - " + guest.AccessCode + (guest.Penality ? " - Pénalité " + Calculation.PENALITY + " points" : "")).FontSize(16).Bold(); AddVotesInDoc(guest, dbCategories, doc); } // Save to the output directory: try { doc.Save(); // Open in Word Process.Start("WINWORD.EXE", destFileName); } catch { } // CGe }
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(); } }
public void SectionPageBreak() { using (var doc = new DocX()) { doc.Create(); doc.AddParagraph().Append("Page 1"); doc.InsertSectionPageBreak(); doc.AddParagraph().Append("Page 2"); doc.InsertSectionPageBreak(); doc.AddParagraph().Append("Page 3"); Validate(doc); doc.Close(); } }
public static void ExportConfigAsDocX(string fileName, XmlConfigFileViewModel xmlConfigFile) { DocX doc = DocX.Create(fileName); doc.AddFooters(); doc.Footers.even.InsertParagraph(xmlConfigFile.FileName); doc.Footers.odd.InsertParagraph(xmlConfigFile.FileName); Paragraph p = doc.InsertParagraph(); p = doc.InsertParagraph(); p.StyleName = "Title"; p.InsertText("Acma Configuration"); p = doc.InsertParagraph(); p.StyleName = "Heading1"; p.InsertText("Description"); p = doc.InsertParagraph(xmlConfigFile.Description); doc.InsertSectionPageBreak(); p = doc.InsertParagraph(); p.StyleName = "Heading1"; p.InsertText("Class Constructors"); foreach (var classConstructor in xmlConfigFile.Constructors) { p = doc.InsertParagraph(); p.StyleName = "Heading2"; p.InsertText(classConstructor.Name); DocXExporter.WriteConstructorObject(classConstructor.Constructors, doc); doc.InsertSectionPageBreak(); } doc.Save(); }
public static void ExportUnitTestAsDocX(string fileName, UnitTestFileViewModel unitTestFile) { DocX doc = DocX.Create(fileName); doc.AddFooters(); doc.Footers.even.InsertParagraph(unitTestFile.FileName); doc.Footers.odd.InsertParagraph(unitTestFile.FileName); Paragraph p = doc.InsertParagraph(); p = doc.InsertParagraph(); p.StyleName = "Title"; p.InsertText("Acma Unit Test Definitions"); doc.InsertSectionPageBreak(); foreach (var unitTest in unitTestFile.UnitTestObjects) { if (unitTest is UnitTestGroupViewModel) { DocXExporter.WriteUnitTestGroup(unitTest as UnitTestGroupViewModel, doc); } else if (unitTest is UnitTestViewModel) { DocXExporter.WriteUnitTest(unitTest as UnitTestViewModel, doc); } else { throw new ArgumentException("Unknown unit test object"); } doc.InsertSectionPageBreak(); } doc.Save(); }
/// <summary> /// 插入某个宗地的所有信息(宗地图、平面分布图、鸟瞰图、分层分户平面图、场地涉外管线布置图) /// </summary> /// <param name="document"></param> public void insertInfo(DocX document, List <FDXXtbl> lstFM, List <Parcelmodel> p) { try { document.InsertSectionPageBreak(); //分页符 var h1 = document.InsertParagraph(Name); h1.StyleName = "Heading1"; insertZDT(document); //宗地图 insertZPMFBT(document); //总平面分布图 insertNKT(document); //鸟瞰图 insertFCFH(document, lstFM, p); //分层分户平面图 insertGXT(document); //场地涉外管线布置图 } catch (System.Exception ex) { LogHelper.WriteLog(typeof(parcelHelper), ex); } }
/// <summary> /// Add a Table of content to a document. /// </summary> public static void InsertTableOfContent() { Console.WriteLine("\tInsertTableOfContent()"); // Creates a document using (DocX document = DocX.Create(TableOfContentSample.TableOfContentSampleOutputDirectory + @"InsertTableOfContent.docx")) { // Add a title document.InsertParagraph("Insert Table of content").FontSize(15d).SpacingAfter(50d).Alignment = Alignment.center; // Insert a table of content with a page break. document.InsertTableOfContents("Teams", TableOfContentsSwitches.O | TableOfContentsSwitches.U | TableOfContentsSwitches.Z | TableOfContentsSwitches.H); document.InsertSectionPageBreak(); // Create a paragraph and fill it in method AddTeams(). var p = document.InsertParagraph(); var rosters = TableOfContentSample.AddTeams(p); document.InsertParagraph(rosters); document.Save(); Console.WriteLine("\tCreated: InsertTableOfContent.docx\n"); } }
private void StartTest_Copy_Click(object sender, RoutedEventArgs e) { string pathDocument = AppDomain.CurrentDomain.BaseDirectory + "Отчет " + FIOLABEL.Content + ".docx"; // создаём документ DocX document = DocX.Create(pathDocument); Xceed.Document.NET.Paragraph paragraph = document.InsertParagraph(); // выравниваем параграф по правой стороне paragraph.Alignment = Alignment.center; // добавляем отдельную строку со своим форматированием paragraph.AppendLine("Служба персонала").Bold().Font("Times New Roman").FontSize(14); paragraph.AppendLine("ООО \"Эрнис\"").Bold().Font("Times New Roman").FontSize(14); paragraph.AppendLine("ПРОТОКОЛ ТЕСТИРОВАНИЯ").Bold().Font("Times New Roman").FontSize(14); Xceed.Document.NET.Paragraph paragraph2 = document.InsertParagraph(); paragraph2.Font("Times New Roman"); paragraph2.FontSize(14); paragraph2.Alignment = Alignment.left; paragraph2.AppendLine("Фамилия: " + _loginPage.SerName.Text).Font("Times New Roman").FontSize(14); paragraph2.AppendLine("Имя: " + _loginPage.Name.Text).Font("Times New Roman").FontSize(14); paragraph2.AppendLine("Отчество: " + _loginPage.ser2.Text).Font("Times New Roman").FontSize(14); paragraph2.AppendLine(); paragraph2.AppendLine("Всего вопросов: " + scrambled.Count()).Font("Times New Roman").FontSize(14); paragraph2.AppendLine("Правильных ответов: " + rightanswes + " (" + (Math.Truncate((double)rightanswes * 100 / (double)scrambled.Count())) + "%)").Font("Times New Roman").FontSize(14); Xceed.Document.NET.Paragraph paragraph3 = document.InsertParagraph().Font("Times New Roman").FontSize(14); paragraph3.Alignment = Alignment.right; paragraph3.Font("Times New Roman"); paragraph3.FontSize(14); paragraph3.AppendLine(); DateTime time = DateTime.Today; if (time.Month < 10) { paragraph3.AppendLine("Дата: " + time.Day + ".0" + time.Month + "." + time.Year).Font("Times New Roman").FontSize(14); } else { paragraph3.AppendLine("Дата: " + time.Day + "." + time.Month + "." + time.Year).Font("Times New Roman").FontSize(14); } paragraph3.AppendLine("ФИО контролирующего:___________________________________").Font("Times New Roman").FontSize(14); paragraph3.AppendLine("Подпись тестируемого:__________________________________").Font("Times New Roman").FontSize(14); paragraph3.InsertPageBreakAfterSelf(); document.InsertSectionPageBreak(); Xceed.Document.NET.Paragraph paragraph4 = document.InsertParagraph(); paragraph4.Alignment = Alignment.left; paragraph4.AppendLine("Неверные ответы:").Font("Times New Roman").FontSize(14).Alignment = Alignment.center; paragraph4.AppendLine().Alignment = Alignment.left;; foreach (FailedQuestion failed in otchet) { paragraph4.AppendLine(failed.text).Font("Times New Roman").FontSize(14); paragraph4.AppendLine("Ответ тестируемого:").Font("Times New Roman").FontSize(14); foreach (Answer answer in failed.FailedAnswers) { paragraph4.AppendLine("-" + answer.text).Font("Times New Roman").FontSize(14); } paragraph4.AppendLine("Правильный ответ:").Font("Times New Roman").FontSize(14); foreach (Answer answer in failed.CorrectAnswers) { paragraph4.AppendLine("-" + answer.text).Font("Times New Roman").FontSize(14); } paragraph4.AppendLine(); } paragraph4.AppendLine("Верные ответы:").Font("Times New Roman").FontSize(14).Alignment = Alignment.center;; paragraph4.AppendLine().Alignment = Alignment.left;; foreach (Question failed in otchet2) { paragraph4.AppendLine(failed.text).Font("Times New Roman").FontSize(14); paragraph4.AppendLine("Ответ тестируемого:").Font("Times New Roman").FontSize(14); foreach (Answer answer in failed.answers.Where(x => x.right == true)) { paragraph4.AppendLine("-" + answer.text).Font("Times New Roman").FontSize(14); } paragraph4.AppendLine(); } // сохраняем документ document.Save(); Process.Start(AppDomain.CurrentDomain.BaseDirectory + "Отчет " + FIOLABEL.Content + ".docx"); }
public void CreateTable() { try { if (root == null) { RefillTree(); } if (root == null) { return; } CurrentRow = 1; if (!Directory.Exists(TableSampleOutputDirectory)) { Directory.CreateDirectory(TableSampleOutputDirectory); } using (DocX document = DocX.Create(TableSampleOutputDirectory + SavedName)) { document.AddHeaders(); // Get the default Header. Header header = document.Headers.Odd; // Insert a Paragraph into the Header. Paragraph p0 = header.InsertParagraph(); p0.Direction = Direction.RightToLeft; p0.Alignment = Alignment.right; // Appemd place holders for PageNumber and PageCount into the Header. // Word will replace these with the correct value for each Page. p0.Append("صفحه ("); p0.AppendPageNumber(PageNumberFormat.normal); p0.Append(")"); int cntChildren = root.Children.Count; foreach (var child in root.Children) { #region new page var par = document.InsertParagraph(child.Category.Title).FontSize(FirstPargFontSize).SpacingAfter(50d); par.Alignment = Alignment.left; par.Direction = Direction.RightToLeft; var columnWidths = new float[child.Height + 3 >= 4 ? child.Height + 3 : 4]; //root.Height; columnWidths[columnWidths.Length - 4] = ColWidthsSize[0]; //"عنوان" columnWidths[columnWidths.Length - 3] = ColWidthsSize[1]; //"داخلی" columnWidths[columnWidths.Length - 2] = ColWidthsSize[2]; //"مستقیم" columnWidths[columnWidths.Length - 1] = ColWidthsSize[3]; //"اسامی" var t = document.InsertTable(1, columnWidths.Length); t.SetDirection(Direction.RightToLeft); t.SetWidths(columnWidths); t.Design = TableDesign.TableNormal; t.AutoFit = AutoFit.Contents; var row = t.Rows.First(); foreach (var cell in row.Cells) { cell.FillColor = Color.LightGray; } // Fill in the columns of the first row in the table. row.Cells[0].Paragraphs.First().Append("عنوان").Alignment = Alignment.center; row.Cells[row.Cells.Count - 3].Paragraphs.First().Append("داخلی").Alignment = Alignment.center; row.Cells[row.Cells.Count - 2].Paragraphs.First().Append("مستقیم").Alignment = Alignment.center; row.Cells[row.Cells.Count - 1].Paragraphs.First().Append("اسامی").Alignment = Alignment.center; if (row.Cells.Count - 4 > 0) { row.MergeCells(0, row.Cells.Count - 4); } // Add rows in the table. for (int i = 0; i < child.CntTotalRows; i++) { var newRow = t.InsertRow(); // Fill in the columns of the new rows. for (int j = 0; j < newRow.Cells.Count; ++j) { var newCell = newRow.Cells[j]; //newCell.Paragraphs.First().Append("$EMPTY"); newCell.SetDirection(Direction.RightToLeft); newCell.VerticalAlignment = VerticalAlignment.Center; } } // Set a blank border for the table's top/bottom borders. var blankBorder = new Border(Xceed.Words.NET.BorderStyle.Tcbs_single, BorderSize.one, 0, Color.Black); t.SetBorder(TableBorderType.Bottom, blankBorder); t.SetBorder(TableBorderType.Top, blankBorder); t.SetBorder(TableBorderType.Left, blankBorder); t.SetBorder(TableBorderType.Right, blankBorder); t.SetBorder(TableBorderType.InsideH, blankBorder); t.SetBorder(TableBorderType.InsideV, blankBorder); #endregion CurrentRow = 1; FillTableRecursivelyHelper(document, t, child, CurrentRow, 0); if (cntChildren > 1) { document.InsertSectionPageBreak(); } cntChildren--; } document.Save(); } } catch { } }
private static void HeadersAndFooters() { Console.WriteLine("\tHeadersAndFooters()"); // Create a new document. using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx")) { // Add Headers and Footers to this document. 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; // Get the first, odd and even Headers for this document. Header header_first = document.Headers.first; Header header_odd = document.Headers.odd; Header header_even = document.Headers.even; // Get the first, odd and even Footer for this document. Footer footer_first = document.Footers.first; Footer footer_odd = document.Footers.odd; Footer footer_even = document.Footers.even; // Insert a Paragraph into the first Header. Paragraph p0 = header_first.InsertParagraph(); p0.Append("Hello First Header.").Bold(); // Insert a Paragraph into the odd Header. Paragraph p1 = header_odd.InsertParagraph(); p1.Append("Hello Odd Header.").Bold(); // Insert a Paragraph into the even Header. Paragraph p2 = header_even.InsertParagraph(); p2.Append("Hello Even Header.").Bold(); // Insert a Paragraph into the first Footer. Paragraph p3 = footer_first.InsertParagraph(); p3.Append("Hello First Footer.").Bold(); // Insert a Paragraph into the odd Footer. Paragraph p4 = footer_odd.InsertParagraph(); p4.Append("Hello Odd Footer.").Bold(); // Insert a Paragraph into the even Header. Paragraph p5 = footer_even.InsertParagraph(); p5.Append("Hello Even Footer.").Bold(); // Insert a Paragraph into the document. Paragraph p6 = document.InsertParagraph(); p6.AppendLine("Hello First page."); // Create a second page to show that the first page has its own header and footer. p6.InsertPageBreakAfterSelf(); // Insert a Paragraph after the page break. Paragraph p7 = document.InsertParagraph(); p7.AppendLine("Hello Second page."); // Create a third page to show that even and odd pages have different headers and footers. p7.InsertPageBreakAfterSelf(); // Insert a Paragraph after the page break. Paragraph p8 = document.InsertParagraph(); p8.AppendLine("Hello Third page."); //Insert a next page break, which is a section break combined with a page break document.InsertSectionPageBreak(); //Insert a paragraph after the "Next" page break Paragraph p9 = document.InsertParagraph(); p9.Append("Next page section break."); //Insert a continuous section break document.InsertSection(); //Create a paragraph in the new section var p10 = document.InsertParagraph(); p10.Append("Continuous section paragraph."); // Save all changes to this document. document.Save(); Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n"); }// Release this document from memory. }
private void BuildItems(IList <WordDocItemDef> items, DocX document, Paragraph p = null) { foreach (var item in items) { var tableDef = item as WordTableDef; if (tableDef != null && tableDef.Sections.Count >= 0 && tableDef.GetColCount() >= 0) { BuildTable(tableDef, document); } else if (item is WordParagraphDef) { var paraDef = (WordParagraphDef)item; var oldStyle = MergeStyle(paraDef.Style); try { // var format = GetFormatting(); var para = AppendParagraph(document /*.InsertParagraph()*/); foreach (var paraItem in paraDef.Items) { if (paraItem is WordContentItemDef) { AddParagraphContent(para, (WordContentItemDef)paraItem); } else if (paraItem is WordRepeatSectionDef) { var repeatSection = (WordRepeatSectionDef)paraItem; if (repeatSection.ResetDatas) { var args = new DataSetResetEventArgs { DataSet = repeatSection.Datas }; OnBeforeDataSetReset(args); repeatSection.Datas.Reset(); OnAfterDataSetReset(args); } while (!repeatSection.Datas.Eof()) { BuildItems(repeatSection.Items, document, para); repeatSection.Datas.Next(); } } else if (paraItem is WordSectionDef) { BuildItems(((WordSectionDef)paraItem).Items, document, para); } } } finally { SetStyle(oldStyle); } } else if (item is WordRepeatSectionDef) { var repeatSection = (WordRepeatSectionDef)item; var oldStyle = MergeStyle(item.Style); try { if (repeatSection.ResetDatas) { var args = new DataSetResetEventArgs { DataSet = repeatSection.Datas }; OnBeforeDataSetReset(args); repeatSection.Datas.Reset(); OnAfterDataSetReset(args); } while (!repeatSection.Datas.Eof()) { BuildItems(repeatSection.Items, document, p); repeatSection.Datas.Next(); } } finally { SetStyle(oldStyle); } } else if (item is WordSectionDef) { BuildItems(((WordSectionDef)item).Items, document, p); } else if (item is PageBreak) { var pageBreak = (PageBreak)item; int step; if (!_pageBreakSteps.TryGetValue(pageBreak, out step)) { step = pageBreak.Step; _pageBreakSteps[pageBreak] = step; } step--; if (step <= 0) { document.InsertSectionPageBreak(); _pageBreakSteps[pageBreak] = pageBreak.Step; } } else if (item is WordContentItemDef) { if (p == null) { p = AppendParagraph(document); } AddParagraphContent(p, (WordContentItemDef)item); } } }
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 void AddHeaderPortraitThenLandscape() { using (var doc = new DocX()) { doc.Create(); doc.AddHeaders(); var table = doc.DefaultHeader.AddTable(3); table.WidthType = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Auto; for (int i = 0; i < 3; i++) { var row = table.AddRow(); row.SetBorders(Units.HalfPt, BorderValue.Single); if (i == 0) { row.SetShading(ShadingPattern.Clear, "E7E6E6"); row.HeaderRow = true; } for (int j = 0; j < 3; j++) { row.Cells[j].Paragraphs[0].Append($"Cell {(j + 1)}"); } } doc.InsertSectionPageBreak(); doc.Orientation = PageOrientation.Landscape; // default is to link previous header // but if the orientation changes, the table will // only be the width of the portrait page // in order to have a new width you have to unlink // the header to the previous doc.AddHeaders(); // and recreate the header table = doc.DefaultHeader.AddTable(3); table.WidthType = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Auto; for (int i = 0; i < 3; i++) { var row = table.AddRow(); row.SetBorders(Units.HalfPt, BorderValue.Single); if (i == 0) { row.SetShading(ShadingPattern.Clear, "E7E6E6"); row.HeaderRow = true; } for (int j = 0; j < 3; j++) { row.Cells[j].Paragraphs[0].Append($"Cell {(j + 1)}"); } } Validate(doc); //doc.SaveAs(System.IO.Path.Combine(TempDirectory, "AddHeaderPortraitThenLandscape.docx")); doc.Close(); } }
protected void Unnamed_Click(object sender, EventArgs e) { const int yeH = 266; const int yeW = 472; const double eventPhotoScalePercentage = 0.7; // /100 using (var _db = new Kronika106.Models.Kronika106DBContext()) { contentList = (from EventComments comment in _db.Forum //(comment.EventId.ToLower() == trueEvetId && ((forumType == ForumType.Event && comment.IsEvent) || (forumType == ForumType.EventPhotoGallery && comment.IsPhoto && comment.ThumbPath.Contains(photoName)))) orderby comment.ID ascending select new PageContent { ID = comment.ID, CreatedUTC = comment.CreatedUTC, EventId = comment.EventId, RootID = comment.RootID, ThumbPath = comment.ThumbPath, ScoutNickName = comment.ApplicationUser.ScoutNickName, NickName = comment.ApplicationUser.NickName, Comment = comment.Comment, IsVideo = comment.IsVideo, IsEvent = comment.IsEvent, IsPhoto = comment.IsPhoto, UserID = comment.ApplicationUser.Id, UserName = comment.ApplicationUser.UserName /*, VideoPosition= comment.VideoPosition */ }).ToList(); } if (contentList == null || contentList.Count == 0) { return; } string now = DateTime.Now.ToString("yyyyMMddHHmmss"); string pthAppData = Server.MapPath("..\\App_Data"); string pthAllPhotos = Server.MapPath("..\\AllPhotos"); DirectoryInfo dAllPhotosInfo = new DirectoryInfo(pthAllPhotos); List <string> lstDocFiles = new List <string>(); foreach (var dYear in dAllPhotosInfo.GetDirectories()) { //rok //DateTime.Now.ToString("yyyyMMddHHmmss") string fileName = $"kronika106_{dYear.Name}_{now}.docx"; string fileFullPath = System.IO.Path.Combine(pthAppData, fileName); doc = DocX.Create(fileFullPath); doc.InsertSection(); doc.InsertParagraph(dYear.Name, false, formatYear).Heading(HeadingType.Heading1).SpacingAfter(25d).Alignment = Alignment.center; var yImage = doc.AddImage(Path.Combine(dYear.FullName, GlobalConstants.fnRokFotka)); var pYImageYear = doc.InsertParagraph(); pYImageYear.AppendPicture(yImage.CreatePicture(yeH, yeW)).SpacingAfter(20d).Alignment = Alignment.center; var yPopisPath = Path.Combine(dYear.FullName, GlobalConstants.fnRokPopis); if (System.IO.File.Exists(yPopisPath)) { doc.InsertParagraph(System.IO.File.ReadAllText(yPopisPath), false, formatText).SpacingAfter(20d).Alignment = Alignment.both; } doc.InsertSectionPageBreak(); //toto rozdelit na zanostatny paragraf pre obrazok a pre text foreach (var dAkcia in dYear.GetDirectories()) { doc.InsertParagraph(dAkcia.Name, false, formatAkcia).Heading(HeadingType.Heading2).SpacingAfter(15d).Alignment = Alignment.center; string eventImagePath = Path.Combine(dAkcia.FullName, GlobalConstants.fnAkciaFotka); if (File.Exists(eventImagePath)) { var pImageEvent = doc.InsertParagraph(); var yImageEvent = doc.AddImage(eventImagePath); pImageEvent.AppendPicture(yImageEvent.CreatePicture(yeH, yeW)).SpacingAfter(15d).Alignment = Alignment.center; } string eventDescriptionPath = Path.Combine(dAkcia.FullName, GlobalConstants.fnAkciaPopis); if (File.Exists(eventDescriptionPath)) { doc.InsertParagraph(File.ReadAllText(eventDescriptionPath), false, formatText).SpacingAfter(15d).Alignment = Alignment.both; } string dbEventId = dAkcia.FullName.Replace(pthAllPhotos, "").TrimStart('\\').Replace("\\", "/"); commentTree(dbEventId, null, ref doc, ForumType.Event); //precitat fotky: foreach (var ePhoto in dAkcia.GetFiles("*.jpg")) { //vynechame uvodny obrazok if (ePhoto.Name.Equals(GlobalConstants.fnAkciaFotka)) { continue; } var pPhotoEvent = doc.InsertParagraph(); var yPhotoEvent = doc.AddImage(ePhoto.FullName); var pct = yPhotoEvent.CreatePicture(); pct.Width = (int)Math.Round(pct.Width * eventPhotoScalePercentage, 0); pct.Height = (int)Math.Round(pct.Height * eventPhotoScalePercentage, 0); pPhotoEvent.AppendPicture(pct).SpacingAfter(5d).SpacingBefore(8d).Alignment = Alignment.center; //tu najst podla nazvu akcie a fotky komnetare a doplmnit -usera commentTree(dbEventId, ePhoto.Name, ref doc, ForumType.EventPhotoGallery); } doc.InsertSectionPageBreak(); } doc.Save(); lstDocFiles.Add(fileFullPath); } string zipFileName = Path.Combine(pthAppData, $"Kronika2Word_{now}.zip"); createZipFile(zipFileName, lstDocFiles); //mama zip zmazeme foreach (var file in lstDocFiles) { System.IO.File.Delete(file); } //upload na klienta FileInfo fInfo = new FileInfo(zipFileName); Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=" + fInfo.Name); Response.AddHeader("Content-Length", fInfo.Length.ToString()); Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; Response.Flush(); Response.TransmitFile(fInfo.FullName); Response.End(); foreach (var file in lstDocFiles) { System.IO.File.Delete(file); } }