Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Program.cs 67KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using Novacode;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Drawing;
  13. using System.ComponentModel;
  14. using System.IO;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Xml.Linq;
  18. namespace Examples
  19. {
  20. class Program
  21. {
  22. static void Main(string[] args)
  23. {
  24. Setup();
  25. // Easy
  26. Console.WriteLine("\nRunning Easy Examples");
  27. HelloWorld();
  28. RightToLeft();
  29. Indentation();
  30. HeadersAndFooters();
  31. HyperlinksImagesTables();
  32. AddList();
  33. Equations();
  34. Bookmarks();
  35. BarChart();
  36. PieChart();
  37. LineChart();
  38. Chart3D();
  39. DocumentMargins();
  40. // Intermediate
  41. Console.WriteLine("\nRunning Intermediate Examples");
  42. CreateInvoice();
  43. HyperlinksImagesTablesWithLists();
  44. HeadersAndFootersWithImagesAndTables();
  45. HeadersAndFootersWithImagesAndTablesUsingInsertPicture();
  46. DocumentsWithListsFontChange();
  47. DocumentHeading();
  48. // Advanced
  49. Console.WriteLine("\nRunning Advanced Examples");
  50. ProgrammaticallyManipulateImbeddedImage();
  51. ReplaceTextParallel();
  52. Console.WriteLine("\nPress any key to exit.");
  53. Console.ReadKey();
  54. }
  55. private static void Setup()
  56. {
  57. if (!Directory.Exists("docs"))
  58. {
  59. Directory.CreateDirectory("docs");
  60. }
  61. }
  62. #region Charts
  63. private class ChartData
  64. {
  65. public String Mounth { get; set; }
  66. public Double Money { get; set; }
  67. public static List<ChartData> CreateCompanyList1()
  68. {
  69. List<ChartData> company1 = new List<ChartData>();
  70. company1.Add(new ChartData() { Mounth = "January", Money = 100 });
  71. company1.Add(new ChartData() { Mounth = "February", Money = 120 });
  72. company1.Add(new ChartData() { Mounth = "March", Money = 140 });
  73. return company1;
  74. }
  75. public static List<ChartData> CreateCompanyList2()
  76. {
  77. List<ChartData> company2 = new List<ChartData>();
  78. company2.Add(new ChartData() { Mounth = "January", Money = 80 });
  79. company2.Add(new ChartData() { Mounth = "February", Money = 160 });
  80. company2.Add(new ChartData() { Mounth = "March", Money = 130 });
  81. return company2;
  82. }
  83. }
  84. private static void BarChart()
  85. {
  86. // Create new document.
  87. using (DocX document = DocX.Create(@"docs\BarChart.docx"))
  88. {
  89. // Create chart.
  90. BarChart c = new BarChart();
  91. c.BarDirection = BarDirection.Column;
  92. c.BarGrouping = BarGrouping.Standard;
  93. c.GapWidth = 400;
  94. c.AddLegend(ChartLegendPosition.Bottom, false);
  95. // Create data.
  96. List<ChartData> company1 = ChartData.CreateCompanyList1();
  97. List<ChartData> company2 = ChartData.CreateCompanyList2();
  98. // Create and add series
  99. Series s1 = new Series("Microsoft");
  100. s1.Color = Color.GreenYellow;
  101. s1.Bind(company1, "Mounth", "Money");
  102. c.AddSeries(s1);
  103. Series s2 = new Series("Apple");
  104. s2.Bind(company2, "Mounth", "Money");
  105. c.AddSeries(s2);
  106. // Insert chart into document
  107. document.InsertParagraph("Diagram").FontSize(20);
  108. document.InsertChart(c);
  109. document.Save();
  110. }
  111. }
  112. private static void PieChart()
  113. {
  114. // Create new document.
  115. using (DocX document = DocX.Create(@"docs\PieChart.docx"))
  116. {
  117. // Create chart.
  118. PieChart c = new PieChart();
  119. c.AddLegend(ChartLegendPosition.Bottom, false);
  120. // Create data.
  121. List<ChartData> company2 = ChartData.CreateCompanyList2();
  122. // Create and add series
  123. Series s = new Series("Apple");
  124. s.Bind(company2, "Mounth", "Money");
  125. c.AddSeries(s);
  126. // Insert chart into document
  127. document.InsertParagraph("Diagram").FontSize(20);
  128. document.InsertChart(c);
  129. document.Save();
  130. }
  131. }
  132. private static void LineChart()
  133. {
  134. // Create new document.
  135. using (DocX document = DocX.Create(@"docs\LineChart.docx"))
  136. {
  137. // Create chart.
  138. LineChart c = new LineChart();
  139. c.AddLegend(ChartLegendPosition.Bottom, false);
  140. // Create data.
  141. List<ChartData> company1 = ChartData.CreateCompanyList1();
  142. List<ChartData> company2 = ChartData.CreateCompanyList2();
  143. // Create and add series
  144. Series s1 = new Series("Microsoft");
  145. s1.Color = Color.GreenYellow;
  146. s1.Bind(company1, "Mounth", "Money");
  147. c.AddSeries(s1);
  148. Series s2 = new Series("Apple");
  149. s2.Bind(company2, "Mounth", "Money");
  150. c.AddSeries(s2);
  151. // Insert chart into document
  152. document.InsertParagraph("Diagram").FontSize(20);
  153. document.InsertChart(c);
  154. document.Save();
  155. }
  156. }
  157. private static void Chart3D()
  158. {
  159. // Create new document.
  160. using (DocX document = DocX.Create(@"docs\3DChart.docx"))
  161. {
  162. // Create chart.
  163. BarChart c = new BarChart();
  164. c.View3D = true;
  165. // Create data.
  166. List<ChartData> company1 = ChartData.CreateCompanyList1();
  167. // Create and add series
  168. Series s = new Series("Microsoft");
  169. s.Color = Color.GreenYellow;
  170. s.Bind(company1, "Mounth", "Money");
  171. c.AddSeries(s);
  172. // Insert chart into document
  173. document.InsertParagraph("3D Diagram").FontSize(20);
  174. document.InsertChart(c);
  175. document.Save();
  176. }
  177. }
  178. #endregion
  179. /// <summary>
  180. /// Create a document with two equations.
  181. /// </summary>
  182. private static void Equations()
  183. {
  184. Console.WriteLine("\nEquations()");
  185. // Create a new document.
  186. using (DocX document = DocX.Create(@"docs\Equations.docx"))
  187. {
  188. // Insert first Equation in this document.
  189. Paragraph pEquation1 = document.InsertEquation("x = y+z");
  190. // Insert second Equation in this document and add formatting.
  191. Paragraph pEquation2 = document.InsertEquation("x = (y+z)/t").FontSize(18).Color(Color.Blue);
  192. // Save this document to disk.
  193. document.Save();
  194. Console.WriteLine("\tCreated: docs\\Equations.docx\n");
  195. }
  196. }
  197. public static void DocumentHeading()
  198. {
  199. Console.WriteLine("\nDocumentHeading()");
  200. using (DocX document = DocX.Create(@"docs\DocumentHeading.docx"))
  201. {
  202. foreach (HeadingType heading in (HeadingType[])Enum.GetValues(typeof(HeadingType)))
  203. {
  204. string text = string.Format("{0} - The quick brown fox jumps over the lazy dog", heading.EnumDescription());
  205. Paragraph p = document.InsertParagraph();
  206. p.AppendLine(text).Heading(heading);
  207. }
  208. document.Save();
  209. Console.WriteLine("\tCreated: docs\\DocumentHeading.docx\n");
  210. }
  211. }
  212. private static void Bookmarks()
  213. {
  214. Console.WriteLine("\nBookmarks()");
  215. using (var document = DocX.Create(@"docs\Bookmarks.docx"))
  216. {
  217. var paragraph = document.InsertBookmark("firstBookmark");
  218. var paragraph2 = document.InsertParagraph("This is a paragraph which contains a ");
  219. paragraph2.AppendBookmark("secondBookmark");
  220. paragraph2.Append("bookmark");
  221. paragraph2.InsertAtBookmark("handy ", "secondBookmark");
  222. document.Save();
  223. Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n");
  224. }
  225. }
  226. /// <summary>
  227. /// Create a document with a Paragraph whos first line is indented.
  228. /// </summary>
  229. private static void Indentation()
  230. {
  231. Console.WriteLine("\tIndentation()");
  232. // Create a new document.
  233. using (DocX document = DocX.Create(@"docs\Indentation.docx"))
  234. {
  235. // Create a new Paragraph.
  236. Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  237. // Indent only the first line of the Paragraph.
  238. p.IndentationFirstLine = 1.0f;
  239. // Save all changes made to this document.
  240. document.Save();
  241. Console.WriteLine("\tCreated: docs\\Indentation.docx\n");
  242. }
  243. }
  244. /// <summary>
  245. /// Create a document that with RightToLeft text flow.
  246. /// </summary>
  247. private static void RightToLeft()
  248. {
  249. Console.WriteLine("\tRightToLeft()");
  250. // Create a new document.
  251. using (DocX document = DocX.Create(@"docs\RightToLeft.docx"))
  252. {
  253. // Create a new Paragraph with the text "Hello World".
  254. Paragraph p = document.InsertParagraph("Hello World.");
  255. // Make this Paragraph flow right to left. Default is left to right.
  256. p.Direction = Direction.RightToLeft;
  257. // You don't need to manually set the text direction foreach Paragraph, you can just call this function.
  258. document.SetDirection(Direction.RightToLeft);
  259. // Save all changes made to this document.
  260. document.Save();
  261. Console.WriteLine("\tCreated: docs\\RightToLeft.docx\n");
  262. }
  263. }
  264. /// <summary>
  265. /// Creates a document with a Hyperlink, an Image and a Table.
  266. /// </summary>
  267. private static void HyperlinksImagesTables()
  268. {
  269. Console.WriteLine("\tHyperlinksImagesTables()");
  270. // Create a document.
  271. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx"))
  272. {
  273. // Add a hyperlink into the document.
  274. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  275. // Add a Table into the document.
  276. Table table = document.AddTable(2, 2);
  277. table.Design = TableDesign.ColorfulGridAccent2;
  278. table.Alignment = Alignment.center;
  279. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  280. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  281. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  282. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  283. Row newRow = table.InsertRow(table.Rows[1]);
  284. newRow.ReplaceText("4", "5");
  285. // Add an image into the document.
  286. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  287. rd.Up(2);
  288. Novacode.Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  289. // Create a picture (A custom view of an Image).
  290. Picture picture = image.CreatePicture();
  291. picture.Rotation = 10;
  292. picture.SetPictureShape(BasicShapes.cube);
  293. // Insert a new Paragraph into the document.
  294. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  295. title.Alignment = Alignment.center;
  296. // Insert a new Paragraph into the document.
  297. Paragraph p1 = document.InsertParagraph();
  298. // Append content to the Paragraph
  299. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  300. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  301. p1.AppendLine();
  302. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  303. p1.AppendLine();
  304. p1.AppendLine("Can you check this Table of figures for me?");
  305. p1.AppendLine();
  306. // Insert the Table after Paragraph 1.
  307. p1.InsertTableAfterSelf(table);
  308. // Insert a new Paragraph into the document.
  309. Paragraph p2 = document.InsertParagraph();
  310. // Append content to the Paragraph.
  311. p2.AppendLine("Is it correct?");
  312. // Save this document.
  313. document.Save();
  314. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
  315. }
  316. }
  317. private static void HyperlinksImagesTablesWithLists()
  318. {
  319. Console.WriteLine("\tHyperlinksImagesTablesWithLists()");
  320. // Create a document.
  321. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTablesWithLists.docx"))
  322. {
  323. // Add a hyperlink into the document.
  324. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  325. // created numbered lists
  326. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
  327. document.AddListItem(numberedList, "First sub list item", 1);
  328. document.AddListItem(numberedList, "Second List Item.");
  329. document.AddListItem(numberedList, "Third list item.");
  330. document.AddListItem(numberedList, "Nested item.", 1);
  331. document.AddListItem(numberedList, "Second nested item.", 1);
  332. // created bulleted lists
  333. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  334. document.AddListItem(bulletedList, "Second bullet item");
  335. document.AddListItem(bulletedList, "Sub bullet item", 1);
  336. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  337. document.AddListItem(bulletedList, "Third bullet item");
  338. // Add a Table into the document.
  339. Table table = document.AddTable(2, 2);
  340. table.Design = TableDesign.ColorfulGridAccent2;
  341. table.Alignment = Alignment.center;
  342. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  343. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  344. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  345. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  346. Row newRow = table.InsertRow(table.Rows[1]);
  347. newRow.ReplaceText("4", "5");
  348. // Add an image into the document.
  349. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  350. rd.Up(2);
  351. Novacode.Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  352. // Create a picture (A custom view of an Image).
  353. Picture picture = image.CreatePicture();
  354. picture.Rotation = 10;
  355. picture.SetPictureShape(BasicShapes.cube);
  356. // Insert a new Paragraph into the document.
  357. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  358. title.Alignment = Alignment.center;
  359. // Insert a new Paragraph into the document.
  360. Paragraph p1 = document.InsertParagraph();
  361. // Append content to the Paragraph
  362. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  363. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  364. p1.AppendLine();
  365. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  366. p1.AppendLine();
  367. p1.AppendLine("Can you check this Table of figures for me?");
  368. p1.AppendLine();
  369. // Insert the Table after Paragraph 1.
  370. p1.InsertTableAfterSelf(table);
  371. // Insert a new Paragraph into the document.
  372. Paragraph p2 = document.InsertParagraph();
  373. // Append content to the Paragraph.
  374. p2.AppendLine("Is it correct?");
  375. p2.AppendLine();
  376. p2.AppendLine("Adding bullet list below: ");
  377. document.InsertList(bulletedList);
  378. // Adding another paragraph to add table and bullet list after it
  379. Paragraph p3 = document.InsertParagraph();
  380. p3.AppendLine();
  381. p3.AppendLine("Adding another table...");
  382. // Adding another table
  383. Table table1 = document.AddTable(2, 2);
  384. table1.Design = TableDesign.ColorfulGridAccent2;
  385. table1.Alignment = Alignment.center;
  386. table1.Rows[0].Cells[0].Paragraphs[0].Append("1");
  387. table1.Rows[0].Cells[1].Paragraphs[0].Append("2");
  388. table1.Rows[1].Cells[0].Paragraphs[0].Append("3");
  389. table1.Rows[1].Cells[1].Paragraphs[0].Append("4");
  390. Paragraph p4 = document.InsertParagraph();
  391. p4.InsertTableBeforeSelf(table1);
  392. p4.AppendLine();
  393. // Insert numbered list after table
  394. Paragraph p5 = document.InsertParagraph();
  395. p5.AppendLine("Adding numbered list below: ");
  396. p5.AppendLine();
  397. document.InsertList(numberedList);
  398. // Save this document.
  399. document.Save();
  400. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTablesWithLists.docx\n");
  401. }
  402. }
  403. private static void DocumentMargins()
  404. {
  405. Console.WriteLine("\tDocumentMargins()");
  406. // Create a document.
  407. using (DocX document = DocX.Create(@"docs\DocumentMargins.docx"))
  408. {
  409. // Create a float var that contains doc Margins properties.
  410. float leftMargin = document.MarginLeft;
  411. float rightMargin = document.MarginRight;
  412. float topMargin = document.MarginTop;
  413. float bottomMargin = document.MarginBottom;
  414. // Modify using your own vars.
  415. leftMargin = 95F;
  416. rightMargin = 45F;
  417. topMargin = 50F;
  418. bottomMargin = 180F;
  419. // Or simply work the margins by setting the property directly.
  420. document.MarginLeft = leftMargin;
  421. document.MarginRight = rightMargin;
  422. document.MarginTop = topMargin;
  423. document.MarginBottom = bottomMargin;
  424. // created bulleted lists
  425. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  426. document.AddListItem(bulletedList, "Second bullet item");
  427. document.AddListItem(bulletedList, "Sub bullet item", 1);
  428. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  429. document.AddListItem(bulletedList, "Third bullet item");
  430. document.InsertList(bulletedList);
  431. // Save this document.
  432. document.Save();
  433. Console.WriteLine("\tCreated: docs\\DocumentMargins.docx\n");
  434. }
  435. }
  436. private static void DocumentsWithListsFontChange()
  437. {
  438. Console.WriteLine("\tDocumentsWithListsFontChange()");
  439. // Create a document.
  440. using (DocX document = DocX.Create(@"docs\DocumentsWithListsFontChange.docx"))
  441. {
  442. foreach ( FontFamily oneFontFamily in FontFamily.Families ) {
  443. System.Drawing.FontFamily fontFamily = oneFontFamily;
  444. double fontSize = 15;
  445. // created numbered lists
  446. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
  447. document.AddListItem(numberedList, "First sub list item", 1);
  448. document.AddListItem(numberedList, "Second List Item.");
  449. document.AddListItem(numberedList, "Third list item.");
  450. document.AddListItem(numberedList, "Nested item.", 1);
  451. document.AddListItem(numberedList, "Second nested item.", 1);
  452. // created bulleted lists
  453. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  454. document.AddListItem(bulletedList, "Second bullet item");
  455. document.AddListItem(bulletedList, "Sub bullet item", 1);
  456. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  457. document.AddListItem(bulletedList, "Third bullet item");
  458. document.InsertList(bulletedList);
  459. document.InsertList(numberedList, fontFamily, fontSize);
  460. }
  461. // Save this document.
  462. document.Save();
  463. Console.WriteLine("\tCreated: docs\\DocumentsWithListsFontChange.docx\n");
  464. }
  465. }
  466. private static void AddList()
  467. {
  468. Console.WriteLine("\tAddList()");
  469. using (var document = DocX.Create(@"docs\Lists.docx"))
  470. {
  471. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 2);
  472. document.AddListItem(numberedList, "First sub list item", 1);
  473. document.AddListItem(numberedList, "Second List Item.");
  474. document.AddListItem(numberedList, "Third list item.");
  475. document.AddListItem(numberedList, "Nested item.", 1);
  476. document.AddListItem(numberedList, "Second nested item.", 1);
  477. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  478. document.AddListItem(bulletedList, "Second bullet item");
  479. document.AddListItem(bulletedList, "Sub bullet item", 1);
  480. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  481. document.AddListItem(bulletedList, "Third bullet item");
  482. document.InsertList(numberedList);
  483. document.InsertList(bulletedList);
  484. document.Save();
  485. Console.WriteLine("\tCreated: docs\\Lists.docx");
  486. }
  487. }
  488. private static void HeadersAndFooters()
  489. {
  490. Console.WriteLine("\tHeadersAndFooters()");
  491. // Create a new document.
  492. using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx"))
  493. {
  494. // Add Headers and Footers to this document.
  495. document.AddHeaders();
  496. document.AddFooters();
  497. // Force the first page to have a different Header and Footer.
  498. document.DifferentFirstPage = true;
  499. // Force odd & even pages to have different Headers and Footers.
  500. document.DifferentOddAndEvenPages = true;
  501. // Get the first, odd and even Headers for this document.
  502. Header header_first = document.Headers.first;
  503. Header header_odd = document.Headers.odd;
  504. Header header_even = document.Headers.even;
  505. // Get the first, odd and even Footer for this document.
  506. Footer footer_first = document.Footers.first;
  507. Footer footer_odd = document.Footers.odd;
  508. Footer footer_even = document.Footers.even;
  509. // Insert a Paragraph into the first Header.
  510. Paragraph p0 = header_first.InsertParagraph();
  511. p0.Append("Hello First Header.").Bold();
  512. // Insert a Paragraph into the odd Header.
  513. Paragraph p1 = header_odd.InsertParagraph();
  514. p1.Append("Hello Odd Header.").Bold();
  515. // Insert a Paragraph into the even Header.
  516. Paragraph p2 = header_even.InsertParagraph();
  517. p2.Append("Hello Even Header.").Bold();
  518. // Insert a Paragraph into the first Footer.
  519. Paragraph p3 = footer_first.InsertParagraph();
  520. p3.Append("Hello First Footer.").Bold();
  521. // Insert a Paragraph into the odd Footer.
  522. Paragraph p4 = footer_odd.InsertParagraph();
  523. p4.Append("Hello Odd Footer.").Bold();
  524. // Insert a Paragraph into the even Header.
  525. Paragraph p5 = footer_even.InsertParagraph();
  526. p5.Append("Hello Even Footer.").Bold();
  527. // Insert a Paragraph into the document.
  528. Paragraph p6 = document.InsertParagraph();
  529. p6.AppendLine("Hello First page.");
  530. // Create a second page to show that the first page has its own header and footer.
  531. p6.InsertPageBreakAfterSelf();
  532. // Insert a Paragraph after the page break.
  533. Paragraph p7 = document.InsertParagraph();
  534. p7.AppendLine("Hello Second page.");
  535. // Create a third page to show that even and odd pages have different headers and footers.
  536. p7.InsertPageBreakAfterSelf();
  537. // Insert a Paragraph after the page break.
  538. Paragraph p8 = document.InsertParagraph();
  539. p8.AppendLine("Hello Third page.");
  540. //Insert a next page break, which is a section break combined with a page break
  541. document.InsertSectionPageBreak();
  542. //Insert a paragraph after the "Next" page break
  543. Paragraph p9 = document.InsertParagraph();
  544. p9.Append("Next page section break.");
  545. //Insert a continuous section break
  546. document.InsertSection();
  547. //Create a paragraph in the new section
  548. var p10 = document.InsertParagraph();
  549. p10.Append("Continuous section paragraph.");
  550. // Save all changes to this document.
  551. document.Save();
  552. Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n");
  553. }// Release this document from memory.
  554. }
  555. private static void HeadersAndFootersWithImagesAndTables()
  556. {
  557. Console.WriteLine("\tHeadersAndFootersWithImagesAndTables()");
  558. // Create a new document.
  559. using (DocX document = DocX.Create(@"docs\HeadersAndFootersWithImagesAndTables.docx"))
  560. {
  561. // Add a template logo image to this document.
  562. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  563. rd.Up(2);
  564. Novacode.Image logo = document.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  565. // Add Headers and Footers to this document.
  566. document.AddHeaders();
  567. document.AddFooters();
  568. // Force the first page to have a different Header and Footer.
  569. document.DifferentFirstPage = true;
  570. // Force odd & even pages to have different Headers and Footers.
  571. document.DifferentOddAndEvenPages = true;
  572. // Get the first, odd and even Headers for this document.
  573. Header header_first = document.Headers.first;
  574. Header header_odd = document.Headers.odd;
  575. Header header_even = document.Headers.even;
  576. // Get the first, odd and even Footer for this document.
  577. Footer footer_first = document.Footers.first;
  578. Footer footer_odd = document.Footers.odd;
  579. Footer footer_even = document.Footers.even;
  580. // Insert a Paragraph into the first Header.
  581. Paragraph p0 = header_first.InsertParagraph();
  582. p0.Append("Hello First Header.").Bold();
  583. // Insert a Paragraph into the odd Header.
  584. Paragraph p1 = header_odd.InsertParagraph();
  585. p1.Append("Hello Odd Header.").Bold();
  586. // Insert a Paragraph into the even Header.
  587. Paragraph p2 = header_even.InsertParagraph();
  588. p2.Append("Hello Even Header.").Bold();
  589. // Insert a Paragraph into the first Footer.
  590. Paragraph p3 = footer_first.InsertParagraph();
  591. p3.Append("Hello First Footer.").Bold();
  592. // Insert a Paragraph into the odd Footer.
  593. Paragraph p4 = footer_odd.InsertParagraph();
  594. p4.Append("Hello Odd Footer.").Bold();
  595. // Insert a Paragraph into the even Header.
  596. Paragraph p5 = footer_even.InsertParagraph();
  597. p5.Append("Hello Even Footer.").Bold();
  598. // Insert a Paragraph into the document.
  599. Paragraph p6 = document.InsertParagraph();
  600. p6.AppendLine("Hello First page.");
  601. // Create a second page to show that the first page has its own header and footer.
  602. p6.InsertPageBreakAfterSelf();
  603. // Insert a Paragraph after the page break.
  604. Paragraph p7 = document.InsertParagraph();
  605. p7.AppendLine("Hello Second page.");
  606. // Create a third page to show that even and odd pages have different headers and footers.
  607. p7.InsertPageBreakAfterSelf();
  608. // Insert a Paragraph after the page break.
  609. Paragraph p8 = document.InsertParagraph();
  610. p8.AppendLine("Hello Third page.");
  611. //Insert a next page break, which is a section break combined with a page break
  612. document.InsertSectionPageBreak();
  613. //Insert a paragraph after the "Next" page break
  614. Paragraph p9 = document.InsertParagraph();
  615. p9.Append("Next page section break.");
  616. //Insert a continuous section break
  617. document.InsertSection();
  618. //Create a paragraph in the new section
  619. var p10 = document.InsertParagraph();
  620. p10.Append("Continuous section paragraph.");
  621. // Inserting logo into footer and header into Tables
  622. #region Company Logo in Header in Table
  623. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  624. Table header_first_table = header_first.InsertTable(1, 2);
  625. header_first_table.Design = TableDesign.TableGrid;
  626. header_first_table.AutoFit = AutoFit.Window;
  627. // Get the upper right Paragraph in the layout_table.
  628. Paragraph upperRightParagraph = header_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  629. // Insert this template logo into the upper right Paragraph of Table.
  630. upperRightParagraph.AppendPicture(logo.CreatePicture());
  631. upperRightParagraph.Alignment = Alignment.right;
  632. // Get the upper left Paragraph in the layout_table.
  633. Paragraph upperLeftParagraphFirstTable = header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  634. upperLeftParagraphFirstTable.Append("Company Name - DocX Corporation");
  635. #endregion
  636. #region Company Logo in Header in Invisible Table
  637. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  638. Table header_second_table = header_odd.InsertTable(1, 2);
  639. header_second_table.Design = TableDesign.None;
  640. header_second_table.AutoFit = AutoFit.Window;
  641. // Get the upper right Paragraph in the layout_table.
  642. Paragraph upperRightParagraphSecondTable = header_second_table.Rows[0].Cells[1].Paragraphs[0];
  643. // Insert this template logo into the upper right Paragraph of Table.
  644. upperRightParagraphSecondTable.AppendPicture(logo.CreatePicture());
  645. upperRightParagraphSecondTable.Alignment = Alignment.right;
  646. // Get the upper left Paragraph in the layout_table.
  647. Paragraph upperLeftParagraphSecondTable = header_second_table.Rows[0].Cells[0].Paragraphs[0];
  648. upperLeftParagraphSecondTable.Append("Company Name - DocX Corporation");
  649. #endregion
  650. #region Company Logo in Footer in Table
  651. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  652. Table footer_first_table = footer_first.InsertTable(1, 2);
  653. footer_first_table.Design = TableDesign.TableGrid;
  654. footer_first_table.AutoFit = AutoFit.Window;
  655. // Get the upper right Paragraph in the layout_table.
  656. Paragraph upperRightParagraphFooterParagraph = footer_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  657. // Insert this template logo into the upper right Paragraph of Table.
  658. upperRightParagraphFooterParagraph.AppendPicture(logo.CreatePicture());
  659. upperRightParagraphFooterParagraph.Alignment = Alignment.right;
  660. // Get the upper left Paragraph in the layout_table.
  661. Paragraph upperLeftParagraphFirstTableFooter = footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  662. upperLeftParagraphFirstTableFooter.Append("Company Name - DocX Corporation");
  663. #endregion
  664. #region Company Logo in Header in Invisible Table
  665. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  666. Table footer_second_table = footer_odd.InsertTable(1, 2);
  667. footer_second_table.Design = TableDesign.None;
  668. footer_second_table.AutoFit = AutoFit.Window;
  669. // Get the upper right Paragraph in the layout_table.
  670. Paragraph upperRightParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[1].Paragraphs[0];
  671. // Insert this template logo into the upper right Paragraph of Table.
  672. upperRightParagraphSecondTableFooter.AppendPicture(logo.CreatePicture());
  673. upperRightParagraphSecondTableFooter.Alignment = Alignment.right;
  674. // Get the upper left Paragraph in the layout_table.
  675. Paragraph upperLeftParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[0].Paragraphs[0];
  676. upperLeftParagraphSecondTableFooter.Append("Company Name - DocX Corporation");
  677. #endregion
  678. // Save all changes to this document.
  679. document.Save();
  680. Console.WriteLine("\tCreated: docs\\HeadersAndFootersWithImagesAndTables.docx\n");
  681. }// Release this document from memory.
  682. }
  683. private static void HeadersAndFootersWithImagesAndTablesUsingInsertPicture()
  684. {
  685. Console.WriteLine("\tHeadersAndFootersWithImagesAndTablesUsingInsertPicture()");
  686. // Create a new document.
  687. using (DocX document = DocX.Create(@"docs\HeadersAndFootersWithImagesAndTablesUsingInsertPicture.docx"))
  688. {
  689. // Add a template logo image to this document.
  690. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  691. rd.Up(2);
  692. Novacode.Image logo = document.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  693. // Add Headers and Footers to this document.
  694. document.AddHeaders();
  695. document.AddFooters();
  696. // Force the first page to have a different Header and Footer.
  697. document.DifferentFirstPage = true;
  698. // Force odd & even pages to have different Headers and Footers.
  699. document.DifferentOddAndEvenPages = true;
  700. // Get the first, odd and even Headers for this document.
  701. Header header_first = document.Headers.first;
  702. Header header_odd = document.Headers.odd;
  703. Header header_even = document.Headers.even;
  704. // Get the first, odd and even Footer for this document.
  705. Footer footer_first = document.Footers.first;
  706. Footer footer_odd = document.Footers.odd;
  707. Footer footer_even = document.Footers.even;
  708. // Insert a Paragraph into the first Header.
  709. Paragraph p0 = header_first.InsertParagraph();
  710. p0.Append("Hello First Header.").Bold();
  711. // Insert a Paragraph into the odd Header.
  712. Paragraph p1 = header_odd.InsertParagraph();
  713. p1.Append("Hello Odd Header.").Bold();
  714. // Insert a Paragraph into the even Header.
  715. Paragraph p2 = header_even.InsertParagraph();
  716. p2.Append("Hello Even Header.").Bold();
  717. // Insert a Paragraph into the first Footer.
  718. Paragraph p3 = footer_first.InsertParagraph();
  719. p3.Append("Hello First Footer.").Bold();
  720. // Insert a Paragraph into the odd Footer.
  721. Paragraph p4 = footer_odd.InsertParagraph();
  722. p4.Append("Hello Odd Footer.").Bold();
  723. // Insert a Paragraph into the even Header.
  724. Paragraph p5 = footer_even.InsertParagraph();
  725. p5.Append("Hello Even Footer.").Bold();
  726. // Insert a Paragraph into the document.
  727. Paragraph p6 = document.InsertParagraph();
  728. p6.AppendLine("Hello First page.");
  729. // Create a second page to show that the first page has its own header and footer.
  730. p6.InsertPageBreakAfterSelf();
  731. // Insert a Paragraph after the page break.
  732. Paragraph p7 = document.InsertParagraph();
  733. p7.AppendLine("Hello Second page.");
  734. // Create a third page to show that even and odd pages have different headers and footers.
  735. p7.InsertPageBreakAfterSelf();
  736. // Insert a Paragraph after the page break.
  737. Paragraph p8 = document.InsertParagraph();
  738. p8.AppendLine("Hello Third page.");
  739. //Insert a next page break, which is a section break combined with a page break
  740. document.InsertSectionPageBreak();
  741. //Insert a paragraph after the "Next" page break
  742. Paragraph p9 = document.InsertParagraph();
  743. p9.Append("Next page section break.");
  744. //Insert a continuous section break
  745. document.InsertSection();
  746. //Create a paragraph in the new section
  747. var p10 = document.InsertParagraph();
  748. p10.Append("Continuous section paragraph.");
  749. // Inserting logo into footer and header into Tables
  750. #region Company Logo in Header in Table
  751. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  752. Table header_first_table = header_first.InsertTable(1, 2);
  753. header_first_table.Design = TableDesign.TableGrid;
  754. header_first_table.AutoFit = AutoFit.Window;
  755. // Get the upper right Paragraph in the layout_table.
  756. Paragraph upperRightParagraph = header_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  757. // Insert this template logo into the upper right Paragraph of Table.
  758. upperRightParagraph.InsertPicture(logo.CreatePicture());
  759. upperRightParagraph.Alignment = Alignment.right;
  760. // Get the upper left Paragraph in the layout_table.
  761. Paragraph upperLeftParagraphFirstTable = header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  762. upperLeftParagraphFirstTable.Append("Company Name - DocX Corporation");
  763. #endregion
  764. #region Company Logo in Header in Invisible Table
  765. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  766. Table header_second_table = header_odd.InsertTable(1, 2);
  767. header_second_table.Design = TableDesign.None;
  768. header_second_table.AutoFit = AutoFit.Window;
  769. // Get the upper right Paragraph in the layout_table.
  770. Paragraph upperRightParagraphSecondTable = header_second_table.Rows[0].Cells[1].Paragraphs[0];
  771. // Insert this template logo into the upper right Paragraph of Table.
  772. upperRightParagraphSecondTable.InsertPicture(logo.CreatePicture());
  773. upperRightParagraphSecondTable.Alignment = Alignment.right;
  774. // Get the upper left Paragraph in the layout_table.
  775. Paragraph upperLeftParagraphSecondTable = header_second_table.Rows[0].Cells[0].Paragraphs[0];
  776. upperLeftParagraphSecondTable.Append("Company Name - DocX Corporation");
  777. #endregion
  778. #region Company Logo in Footer in Table
  779. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  780. Table footer_first_table = footer_first.InsertTable(1, 2);
  781. footer_first_table.Design = TableDesign.TableGrid;
  782. footer_first_table.AutoFit = AutoFit.Window;
  783. // Get the upper right Paragraph in the layout_table.
  784. Paragraph upperRightParagraphFooterParagraph = footer_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  785. // Insert this template logo into the upper right Paragraph of Table.
  786. upperRightParagraphFooterParagraph.InsertPicture(logo.CreatePicture());
  787. upperRightParagraphFooterParagraph.Alignment = Alignment.right;
  788. // Get the upper left Paragraph in the layout_table.
  789. Paragraph upperLeftParagraphFirstTableFooter = footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  790. upperLeftParagraphFirstTableFooter.Append("Company Name - DocX Corporation");
  791. #endregion
  792. #region Company Logo in Header in Invisible Table
  793. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  794. Table footer_second_table = footer_odd.InsertTable(1, 2);
  795. footer_second_table.Design = TableDesign.None;
  796. footer_second_table.AutoFit = AutoFit.Window;
  797. // Get the upper right Paragraph in the layout_table.
  798. Paragraph upperRightParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[1].Paragraphs[0];
  799. // Insert this template logo into the upper right Paragraph of Table.
  800. upperRightParagraphSecondTableFooter.InsertPicture(logo.CreatePicture());
  801. upperRightParagraphSecondTableFooter.Alignment = Alignment.right;
  802. // Get the upper left Paragraph in the layout_table.
  803. Paragraph upperLeftParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[0].Paragraphs[0];
  804. upperLeftParagraphSecondTableFooter.Append("Company Name - DocX Corporation");
  805. #endregion
  806. // Save all changes to this document.
  807. document.Save();
  808. Console.WriteLine("\tCreated: docs\\HeadersAndFootersWithImagesAndTablesUsingInsertPicture.docx\n");
  809. }// Release this document from memory.
  810. }
  811. private static void CreateInvoice()
  812. {
  813. Console.WriteLine("\tCreateInvoice()");
  814. DocX g_document;
  815. try
  816. {
  817. // Store a global reference to the loaded document.
  818. g_document = DocX.Load(@"docs\InvoiceTemplate.docx");
  819. /*
  820. * The template 'InvoiceTemplate.docx' does exist,
  821. * so lets use it to create an invoice for a factitious company
  822. * called "The Happy Builder" and store a global reference it.
  823. */
  824. g_document = CreateInvoiceFromTemplate(DocX.Load(@"docs\InvoiceTemplate.docx"));
  825. // Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
  826. g_document.SaveAs(@"docs\Invoice_The_Happy_Builder.docx");
  827. Console.WriteLine("\tCreated: docs\\Invoice_The_Happy_Builder.docx\n");
  828. }
  829. // The template 'InvoiceTemplate.docx' does not exist, so create it.
  830. catch (FileNotFoundException)
  831. {
  832. // Create and store a global reference to the template 'InvoiceTemplate.docx'.
  833. g_document = CreateInvoiceTemplate();
  834. // Save the template 'InvoiceTemplate.docx'.
  835. g_document.Save();
  836. Console.WriteLine("\tCreated: docs\\InvoiceTemplate.docx");
  837. // The template exists now so re-call CreateInvoice().
  838. CreateInvoice();
  839. }
  840. }
  841. // Create an invoice for a factitious company called "The Happy Builder".
  842. private static DocX CreateInvoiceFromTemplate(DocX template)
  843. {
  844. #region Logo
  845. // A quick glance at the template shows us that the logo Paragraph is in row zero cell 1.
  846. Paragraph logo_paragraph = template.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  847. // Remove the template Picture that is in this Paragraph.
  848. logo_paragraph.Pictures[0].Remove();
  849. // Add the Happy Builders logo to this document.
  850. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  851. rd.Up(2);
  852. Novacode.Image logo = template.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  853. // Insert the Happy Builders logo into this Paragraph.
  854. logo_paragraph.InsertPicture(logo.CreatePicture());
  855. #endregion
  856. #region Set CustomProperty values
  857. // Set the value of the custom property 'company_name'.
  858. template.AddCustomProperty(new CustomProperty("company_name", "The Happy Builder"));
  859. // Set the value of the custom property 'company_slogan'.
  860. template.AddCustomProperty(new CustomProperty("company_slogan", "No job too small"));
  861. // Set the value of the custom properties 'hired_company_address_line_one', 'hired_company_address_line_two' and 'hired_company_address_line_three'.
  862. template.AddCustomProperty(new CustomProperty("hired_company_address_line_one", "The Crooked House,"));
  863. template.AddCustomProperty(new CustomProperty("hired_company_address_line_two", "Dublin,"));
  864. template.AddCustomProperty(new CustomProperty("hired_company_address_line_three", "12345"));
  865. // Set the value of the custom property 'invoice_date'.
  866. template.AddCustomProperty(new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d")));
  867. // Set the value of the custom property 'invoice_number'.
  868. template.AddCustomProperty(new CustomProperty("invoice_number", 1));
  869. // Set the value of the custom property 'hired_company_details_line_one' and 'hired_company_details_line_two'.
  870. template.AddCustomProperty(new CustomProperty("hired_company_details_line_one", "Business Street, Dublin, 12345"));
  871. template.AddCustomProperty(new CustomProperty("hired_company_details_line_two", "Phone: 012-345-6789, Fax: 012-345-6789, e-mail: support@thehappybuilder.com"));
  872. #endregion
  873. /*
  874. * InvoiceTemplate.docx contains a blank Table,
  875. * we want to replace this with a new Table that
  876. * contains all of our invoice data.
  877. */
  878. Table t = template.Tables[1];
  879. Table invoice_table = CreateAndInsertInvoiceTableAfter(t, ref template);
  880. t.Remove();
  881. // Return the template now that it has been modified to hold all of our custom data.
  882. return template;
  883. }
  884. // Create an invoice template.
  885. private static DocX CreateInvoiceTemplate()
  886. {
  887. // Create a new document.
  888. DocX document = DocX.Create(@"docs\InvoiceTemplate.docx");
  889. // Create a table for layout purposes (This table will be invisible).
  890. Table layout_table = document.InsertTable(2, 2);
  891. layout_table.Design = TableDesign.TableNormal;
  892. layout_table.AutoFit = AutoFit.Window;
  893. // Dark formatting
  894. Formatting dark_formatting = new Formatting();
  895. dark_formatting.Bold = true;
  896. dark_formatting.Size = 12;
  897. dark_formatting.FontColor = Color.FromArgb(31, 73, 125);
  898. // Light formatting
  899. Formatting light_formatting = new Formatting();
  900. light_formatting.Italic = true;
  901. light_formatting.Size = 11;
  902. light_formatting.FontColor = Color.FromArgb(79, 129, 189);
  903. #region Company Name
  904. // Get the upper left Paragraph in the layout_table.
  905. Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0];
  906. // Create a custom property called company_name
  907. CustomProperty company_name = new CustomProperty("company_name", "Company Name");
  908. // Insert a field of type doc property (This will display the custom property 'company_name')
  909. layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting);
  910. // Force the next text insert to be on a new line.
  911. upper_left_paragraph.InsertText("\n", false);
  912. #endregion
  913. #region Company Slogan
  914. // Create a custom property called company_slogan
  915. CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here.");
  916. // Insert a field of type doc property (This will display the custom property 'company_slogan')
  917. upper_left_paragraph.InsertDocProperty(company_slogan, f: light_formatting);
  918. #endregion
  919. #region Company Logo
  920. // Get the upper right Paragraph in the layout_table.
  921. Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0];
  922. // Add a template logo image to this document.
  923. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  924. rd.Up(2);
  925. Novacode.Image logo = document.AddImage(rd.Path + @"\images\logo_template.png");
  926. // Insert this template logo into the upper right Paragraph.
  927. upper_right_paragraph.InsertPicture(logo.CreatePicture());
  928. upper_right_paragraph.Alignment = Alignment.right;
  929. #endregion
  930. // Custom properties cannot contain newlines, so the company address must be split into 3 custom properties.
  931. #region Hired Company Address
  932. // Create a custom property called company_address_line_one
  933. CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,");
  934. // Get the lower left Paragraph in the layout_table.
  935. Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0];
  936. lower_left_paragraph.InsertText("TO:\n", false, dark_formatting);
  937. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one')
  938. lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, f: light_formatting);
  939. // Force the next text insert to be on a new line.
  940. lower_left_paragraph.InsertText("\n", false);
  941. // Create a custom property called company_address_line_two
  942. CustomProperty hired_company_address_line_two = new CustomProperty("hired_company_address_line_two", "City,");
  943. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two')
  944. lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f: light_formatting);
  945. // Force the next text insert to be on a new line.
  946. lower_left_paragraph.InsertText("\n", false);
  947. // Create a custom property called company_address_line_two
  948. CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code");
  949. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three')
  950. lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f: light_formatting);
  951. #endregion
  952. #region Date & Invoice number
  953. // Get the lower right Paragraph from the layout table.
  954. Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0];
  955. CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"));
  956. lower_right_paragraph.InsertText("Date: ", false, dark_formatting);
  957. lower_right_paragraph.InsertDocProperty(invoice_date, f: light_formatting);
  958. CustomProperty invoice_number = new CustomProperty("invoice_number", 1);
  959. lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting);
  960. lower_right_paragraph.InsertText("#", false, light_formatting);
  961. lower_right_paragraph.InsertDocProperty(invoice_number, f: light_formatting);
  962. lower_right_paragraph.Alignment = Alignment.right;
  963. #endregion
  964. // Insert an empty Paragraph between two Tables, so that they do not touch.
  965. document.InsertParagraph(string.Empty, false);
  966. // This table will hold all of the invoice data.
  967. Table invoice_table = document.InsertTable(4, 4);
  968. invoice_table.Design = TableDesign.LightShadingAccent1;
  969. invoice_table.Alignment = Alignment.center;
  970. // A nice thank you Paragraph.
  971. Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting);
  972. thankyou.Alignment = Alignment.center;
  973. #region Hired company details
  974. CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code");
  975. CustomProperty hired_company_details_line_two = new CustomProperty("hired_company_details_line_two", "Phone: 000-000-0000, Fax: 000-000-0000, e-mail: support@companyname.com");
  976. Paragraph companyDetails = document.InsertParagraph(string.Empty, false);
  977. companyDetails.InsertDocProperty(hired_company_details_line_one, f: light_formatting);
  978. companyDetails.InsertText("\n", false);
  979. companyDetails.InsertDocProperty(hired_company_details_line_two, f: light_formatting);
  980. companyDetails.Alignment = Alignment.center;
  981. #endregion
  982. // Return the document now that it has been created.
  983. return document;
  984. }
  985. private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
  986. {
  987. // Grab data from somewhere (Most likely a database)
  988. DataTable data = GetDataFromDatabase();
  989. /*
  990. * The trick to replacing one Table with another,
  991. * is to insert the new Table after the old one,
  992. * and then remove the old one.
  993. */
  994. Table invoice_table = t.InsertTableAfterSelf(data.Rows.Count + 1, data.Columns.Count);
  995. invoice_table.Design = TableDesign.LightShadingAccent1;
  996. #region Table title
  997. Formatting table_title = new Formatting();
  998. table_title.Bold = true;
  999. invoice_table.Rows[0].Cells[0].Paragraphs[0].InsertText("Description", false, table_title);
  1000. invoice_table.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
  1001. invoice_table.Rows[0].Cells[1].Paragraphs[0].InsertText("Hours", false, table_title);
  1002. invoice_table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
  1003. invoice_table.Rows[0].Cells[2].Paragraphs[0].InsertText("Rate", false, table_title);
  1004. invoice_table.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
  1005. invoice_table.Rows[0].Cells[3].Paragraphs[0].InsertText("Amount", false, table_title);
  1006. invoice_table.Rows[0].Cells[3].Paragraphs[0].Alignment = Alignment.center;
  1007. #endregion
  1008. // Loop through the rows in the Table and insert data from the data source.
  1009. for (int row = 1; row < invoice_table.RowCount; row++)
  1010. {
  1011. for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
  1012. {
  1013. Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
  1014. cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
  1015. }
  1016. }
  1017. // We want to fill in the total by suming the values from the amount column.
  1018. Row total = invoice_table.InsertRow();
  1019. total.Cells[0].Paragraphs[0].InsertText("Total:", false);
  1020. Paragraph total_paragraph = total.Cells[invoice_table.ColumnCount - 1].Paragraphs[0];
  1021. /*
  1022. * Lots of people are scared of LINQ,
  1023. * so I will walk you through this line by line.
  1024. *
  1025. * invoice_table.Rows is an IEnumerable<Row> (i.e a collection of rows), with LINQ you can query collections.
  1026. * .Where(condition) is a filter that you want to apply to the items of this collection.
  1027. * My condition is that the index of the row must be greater than 0 and less than RowCount.
  1028. * .Select(something) lets you select something from each item in the filtered collection.
  1029. * I am selecting the Text value from each row, for example €100, then I am remove the €,
  1030. * and then I am parsing the remaining string as a double. This will return a collection of doubles,
  1031. * the final thing I do is call .Sum() on this collection which return one double the sum of all the doubles,
  1032. * this is the total.
  1033. */
  1034. double totalCost =
  1035. (
  1036. invoice_table.Rows
  1037. .Where((row, index) => index > 0 && index < invoice_table.RowCount - 1)
  1038. .Select(row => double.Parse(row.Cells[row.Cells.Count() - 1].Paragraphs[0].Text.Remove(0, 1)))
  1039. ).Sum();
  1040. // Insert the total calculated above using LINQ into the total Paragraph.
  1041. total_paragraph.InsertText(string.Format("€{0}", totalCost), false);
  1042. // Let the tables columns expand to fit its contents.
  1043. invoice_table.AutoFit = AutoFit.Contents;
  1044. // Center the Table
  1045. invoice_table.Alignment = Alignment.center;
  1046. // Return the invloce table now that it has been created.
  1047. return invoice_table;
  1048. }
  1049. // You need to rewrite this function to grab data from your data source.
  1050. private static DataTable GetDataFromDatabase()
  1051. {
  1052. DataTable table = new DataTable();
  1053. table.Columns.AddRange(new DataColumn[] { new DataColumn("Description"), new DataColumn("Hours"), new DataColumn("Rate"), new DataColumn("Amount") });
  1054. table.Rows.Add
  1055. (
  1056. "Install wooden doors (Kitchen, Sitting room, Dining room & Bedrooms)",
  1057. "5",
  1058. "€25",
  1059. string.Format("€{0}", 5 * 25)
  1060. );
  1061. table.Rows.Add
  1062. (
  1063. "Fit stairs",
  1064. "20",
  1065. "€30",
  1066. string.Format("€{0}", 20 * 30)
  1067. );
  1068. table.Rows.Add
  1069. (
  1070. "Replace Sitting room window",
  1071. "6",
  1072. "€50",
  1073. string.Format("€{0}", 6 * 50)
  1074. );
  1075. table.Rows.Add
  1076. (
  1077. "Build garden shed",
  1078. "10",
  1079. "€10",
  1080. string.Format("€{0}", 10 * 10)
  1081. );
  1082. table.Rows.Add
  1083. (
  1084. "Fit new lock on back door",
  1085. "0.5",
  1086. "€30",
  1087. string.Format("€{0}", 0.5 * 30)
  1088. );
  1089. table.Rows.Add
  1090. (
  1091. "Tile Kitchen floor",
  1092. "24",
  1093. "€25",
  1094. string.Format("€{0}", 24 * 25)
  1095. );
  1096. return table;
  1097. }
  1098. /// <summary>
  1099. /// Creates a simple document with the text Hello World.
  1100. /// </summary>
  1101. static void HelloWorld()
  1102. {
  1103. Console.WriteLine("\tHelloWorld()");
  1104. // Create a new document.
  1105. using (DocX document = DocX.Create(@"docs\Hello World.docx"))
  1106. {
  1107. // Insert a Paragraph into this document.
  1108. Paragraph p = document.InsertParagraph();
  1109. // Append some text and add formatting.
  1110. p.Append("Hello World!^011Hello World!")
  1111. .Font(new FontFamily("Times New Roman"))
  1112. .FontSize(32)
  1113. .Color(Color.Blue)
  1114. .Bold();
  1115. // Save this document to disk.
  1116. document.Save();
  1117. Console.WriteLine("\tCreated: docs\\Hello World.docx\n");
  1118. }
  1119. }
  1120. /// <summary>
  1121. /// Loads a document 'Input.docx' and writes the text 'Hello World' into the first imbedded Image.
  1122. /// This code creates the file 'Output.docx'.
  1123. /// </summary>
  1124. static void ProgrammaticallyManipulateImbeddedImage()
  1125. {
  1126. Console.WriteLine("\tProgrammaticallyManipulateImbeddedImage()");
  1127. const string str = "Hello World";
  1128. // Open the document Input.docx.
  1129. using (DocX document = DocX.Load(@"Input.docx"))
  1130. {
  1131. // Make sure this document has at least one Image.
  1132. if (document.Images.Count() > 0)
  1133. {
  1134. Novacode.Image img = document.Images[0];
  1135. // Write "Hello World" into this Image.
  1136. Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
  1137. /*
  1138. * Get the Graphics object for this Bitmap.
  1139. * The Graphics object provides functions for drawing.
  1140. */
  1141. Graphics g = Graphics.FromImage(b);
  1142. // Draw the string "Hello World".
  1143. g.DrawString
  1144. (
  1145. str,
  1146. new Font("Tahoma", 20),
  1147. Brushes.Blue,
  1148. new PointF(0, 0)
  1149. );
  1150. // Save this Bitmap back into the document using a Create\Write stream.
  1151. b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
  1152. }
  1153. else
  1154. Console.WriteLine("The provided document contains no Images.");
  1155. // Save this document as Output.docx.
  1156. document.SaveAs(@"docs\Output.docx");
  1157. Console.WriteLine("\tCreated: docs\\Output.docx\n");
  1158. }
  1159. }
  1160. /// <summary>
  1161. /// For each of the documents in the folder 'docs\',
  1162. /// Replace the string a with the string b,
  1163. /// Do this in Parrallel accross many CPU cores.
  1164. /// </summary>
  1165. static void ReplaceTextParallel()
  1166. {
  1167. Console.WriteLine("\tReplaceTextParallel()\n");
  1168. const string a = "apple";
  1169. const string b = "pear";
  1170. // Directory containing many .docx documents.
  1171. DirectoryInfo di = new DirectoryInfo(@"docs\");
  1172. // Loop through each document in this specified direction.
  1173. Parallel.ForEach
  1174. (
  1175. di.GetFiles(),
  1176. currentFile =>
  1177. {
  1178. // Load the document.
  1179. using (DocX document = DocX.Load(currentFile.FullName))
  1180. {
  1181. // Replace text in this document.
  1182. document.ReplaceText(a, b);
  1183. // Save changes made to this document.
  1184. document.Save();
  1185. } // Release this document from memory.
  1186. }
  1187. );
  1188. Console.WriteLine("\tCreated: None\n");
  1189. }
  1190. }
  1191. }