Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Program.cs 70KB

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