Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Program.cs 63KB

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