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

Program.cs 56KB

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