Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Program.cs 68KB

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