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 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Novacode;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Drawing.Imaging;
  9. using System.Threading.Tasks;
  10. using System.Data;
  11. namespace Examples
  12. {
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. // In the development...
  18. ChartInTheDevelopment();
  19. // Easy
  20. Console.WriteLine("\nRunning Easy Examples");
  21. HelloWorld();
  22. RightToLeft();
  23. Indentation();
  24. HeadersAndFooters();
  25. HyperlinksImagesTables();
  26. Equations();
  27. // Intermediate
  28. Console.WriteLine("\nRunning Intermediate Examples");
  29. CreateInvoice();
  30. // Advanced
  31. Console.WriteLine("\nRunning Advanced Examples");
  32. ProgrammaticallyManipulateImbeddedImage();
  33. ReplaceTextParallel();
  34. Console.WriteLine("\nPress any key to exit.");
  35. Console.ReadKey();
  36. }
  37. private class ChartData
  38. {
  39. public String Mounth { get; set; }
  40. public Double Money { get; set; }
  41. }
  42. private static void ChartInTheDevelopment()
  43. {
  44. // Create new document.
  45. using (DocX document = DocX.Create(@"docs\Chart.docx"))
  46. {
  47. // Create chart.
  48. Chart c = new Chart();
  49. c.AddLegend(ChartLegendPosition.Bottom, false);
  50. // Create data.
  51. List<ChartData> company1 = new List<ChartData>();
  52. company1.Add(new ChartData() { Mounth = "January", Money = 100 });
  53. company1.Add(new ChartData() { Mounth = "February", Money = 120 });
  54. company1.Add(new ChartData() { Mounth = "March", Money = 140 });
  55. List<ChartData> company2 = new List<ChartData>();
  56. company2.Add(new ChartData() { Mounth = "January", Money = 80 });
  57. company2.Add(new ChartData() { Mounth = "February", Money = 160 });
  58. company2.Add(new ChartData() { Mounth = "March", Money = 130 });
  59. // Create and add series
  60. Series s1 = new Series("Microsoft");
  61. s1.Color = Color.GreenYellow;
  62. s1.Bind(company1, "Mounth", "Money");
  63. c.AddSeries(s1);
  64. Series s2 = new Series("Apple");
  65. s2.Bind(company2, "Mounth", "Money");
  66. c.AddSeries(s2);
  67. // Insert chart into document
  68. document.InsertParagraph("Diagram").FontSize(20);
  69. document.InsertParagraph("BeforeText");
  70. document.InsertChartInTheDevelopment(c);
  71. document.InsertParagraph("AfterText");
  72. document.Save();
  73. }
  74. }
  75. /// <summary>
  76. /// Create a document with two equations.
  77. /// </summary>
  78. private static void Equations()
  79. {
  80. Console.WriteLine("\nEquations()");
  81. // Create a new document.
  82. using (DocX document = DocX.Create(@"docs\Equations.docx"))
  83. {
  84. // Insert first Equation in this document.
  85. Paragraph pEquation1 = document.InsertEquation("x = y+z");
  86. // Insert second Equation in this document and add formatting.
  87. Paragraph pEquation2 = document.InsertEquation("x = (y+z)/t").FontSize(18).Color(Color.Blue);
  88. // Save this document to disk.
  89. document.Save();
  90. Console.WriteLine("\tCreated: docs\\Equations.docx\n");
  91. }
  92. }
  93. /// <summary>
  94. /// Create a document with a Paragraph whos first line is indented.
  95. /// </summary>
  96. private static void Indentation()
  97. {
  98. Console.WriteLine("\tIndentation()");
  99. // Create a new document.
  100. using (DocX document = DocX.Create(@"docs\Indentation.docx"))
  101. {
  102. // Create a new Paragraph.
  103. Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  104. // Indent only the first line of the Paragraph.
  105. p.IndentationFirstLine = 1.0f;
  106. // Save all changes made to this document.
  107. document.Save();
  108. Console.WriteLine("\tCreated: docs\\Indentation.docx\n");
  109. }
  110. }
  111. /// <summary>
  112. /// Create a document that with RightToLeft text flow.
  113. /// </summary>
  114. private static void RightToLeft()
  115. {
  116. Console.WriteLine("\tRightToLeft()");
  117. // Create a new document.
  118. using (DocX document = DocX.Create(@"docs\RightToLeft.docx"))
  119. {
  120. // Create a new Paragraph with the text "Hello World".
  121. Paragraph p = document.InsertParagraph("Hello World.");
  122. // Make this Paragraph flow right to left. Default is left to right.
  123. p.Direction = Direction.RightToLeft;
  124. // You don't need to manually set the text direction foreach Paragraph, you can just call this function.
  125. document.SetDirection(Direction.RightToLeft);
  126. // Save all changes made to this document.
  127. document.Save();
  128. Console.WriteLine("\tCreated: docs\\RightToLeft.docx\n");
  129. }
  130. }
  131. /// <summary>
  132. /// Creates a document with a Hyperlink, an Image and a Table.
  133. /// </summary>
  134. private static void HyperlinksImagesTables()
  135. {
  136. Console.WriteLine("\tHyperlinksImagesTables()");
  137. // Create a document.
  138. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx"))
  139. {
  140. // Add a hyperlink into the document.
  141. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  142. // Add a Table into the document.
  143. Table table = document.AddTable(2, 2);
  144. table.Design = TableDesign.ColorfulGridAccent2;
  145. table.Alignment = Alignment.center;
  146. table.Rows[0].Cells[0].Paragraphs[0].Append("3");
  147. table.Rows[0].Cells[1].Paragraphs[0].Append("1");
  148. table.Rows[1].Cells[0].Paragraphs[0].Append("4");
  149. table.Rows[1].Cells[1].Paragraphs[0].Append("1");
  150. // Add an image into the document.
  151. Novacode.Image image = document.AddImage(@"images\logo_template.png");
  152. // Create a picture (A custom view of an Image).
  153. Picture picture = image.CreatePicture();
  154. picture.Rotation = 10;
  155. picture.SetPictureShape(BasicShapes.cube);
  156. // Insert a new Paragraph into the document.
  157. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  158. title.Alignment = Alignment.center;
  159. // Insert a new Paragraph into the document.
  160. Paragraph p1 = document.InsertParagraph();
  161. // Append content to the Paragraph
  162. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  163. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  164. p1.AppendLine();
  165. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  166. p1.AppendLine();
  167. p1.AppendLine("Can you check this Table of figures for me?");
  168. p1.AppendLine();
  169. // Insert the Table after Paragraph 1.
  170. p1.InsertTableAfterSelf(table);
  171. // Insert a new Paragraph into the document.
  172. Paragraph p2 = document.InsertParagraph();
  173. // Append content to the Paragraph.
  174. p2.AppendLine("Is it correct?");
  175. // Save this document.
  176. document.Save();
  177. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
  178. }
  179. }
  180. private static void HeadersAndFooters()
  181. {
  182. Console.WriteLine("\tHeadersAndFooters()");
  183. // Create a new document.
  184. using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx"))
  185. {
  186. // Add Headers and Footers to this document.
  187. document.AddHeaders();
  188. document.AddFooters();
  189. // Force the first page to have a different Header and Footer.
  190. document.DifferentFirstPage = true;
  191. // Force odd & even pages to have different Headers and Footers.
  192. document.DifferentOddAndEvenPages = true;
  193. // Get the first, odd and even Headers for this document.
  194. Header header_first = document.Headers.first;
  195. Header header_odd = document.Headers.odd;
  196. Header header_even = document.Headers.even;
  197. // Get the first, odd and even Footer for this document.
  198. Footer footer_first = document.Footers.first;
  199. Footer footer_odd = document.Footers.odd;
  200. Footer footer_even = document.Footers.even;
  201. // Insert a Paragraph into the first Header.
  202. Paragraph p0 = header_first.InsertParagraph();
  203. p0.Append("Hello First Header.").Bold();
  204. // Insert a Paragraph into the odd Header.
  205. Paragraph p1 = header_odd.InsertParagraph();
  206. p1.Append("Hello Odd Header.").Bold();
  207. // Insert a Paragraph into the even Header.
  208. Paragraph p2 = header_even.InsertParagraph();
  209. p2.Append("Hello Even Header.").Bold();
  210. // Insert a Paragraph into the first Footer.
  211. Paragraph p3 = footer_first.InsertParagraph();
  212. p3.Append("Hello First Footer.").Bold();
  213. // Insert a Paragraph into the odd Footer.
  214. Paragraph p4 = footer_odd.InsertParagraph();
  215. p4.Append("Hello Odd Footer.").Bold();
  216. // Insert a Paragraph into the even Header.
  217. Paragraph p5 = footer_even.InsertParagraph();
  218. p5.Append("Hello Even Footer.").Bold();
  219. // Insert a Paragraph into the document.
  220. Paragraph p6 = document.InsertParagraph();
  221. p6.AppendLine("Hello First page.");
  222. // Create a second page to show that the first page has its own header and footer.
  223. p6.InsertPageBreakAfterSelf();
  224. // Insert a Paragraph after the page break.
  225. Paragraph p7 = document.InsertParagraph();
  226. p7.AppendLine("Hello Second page.");
  227. // Create a third page to show that even and odd pages have different headers and footers.
  228. p7.InsertPageBreakAfterSelf();
  229. // Insert a Paragraph after the page break.
  230. Paragraph p8 = document.InsertParagraph();
  231. p8.AppendLine("Hello Third page.");
  232. // Save all changes to this document.
  233. document.Save();
  234. Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n");
  235. }// Release this document from memory.
  236. }
  237. private static void CreateInvoice()
  238. {
  239. Console.WriteLine("\tCreateInvoice()");
  240. DocX g_document;
  241. try
  242. {
  243. // Store a global reference to the loaded document.
  244. g_document = DocX.Load(@"docs\InvoiceTemplate.docx");
  245. /*
  246. * The template 'InvoiceTemplate.docx' does exist,
  247. * so lets use it to create an invoice for a factitious company
  248. * called "The Happy Builder" and store a global reference it.
  249. */
  250. g_document = CreateInvoiceFromTemplate(DocX.Load(@"docs\InvoiceTemplate.docx"));
  251. // Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
  252. g_document.SaveAs(@"docs\Invoice_The_Happy_Builder.docx");
  253. Console.WriteLine("\tCreated: docs\\Invoice_The_Happy_Builder.docx\n");
  254. }
  255. // The template 'InvoiceTemplate.docx' does not exist, so create it.
  256. catch (FileNotFoundException)
  257. {
  258. // Create and store a global reference to the template 'InvoiceTemplate.docx'.
  259. g_document = CreateInvoiceTemplate();
  260. // Save the template 'InvoiceTemplate.docx'.
  261. g_document.Save();
  262. Console.WriteLine("\tCreated: docs\\InvoiceTemplate.docx");
  263. // The template exists now so re-call CreateInvoice().
  264. CreateInvoice();
  265. }
  266. }
  267. // Create an invoice for a factitious company called "The Happy Builder".
  268. private static DocX CreateInvoiceFromTemplate(DocX template)
  269. {
  270. #region Logo
  271. // A quick glance at the template shows us that the logo Paragraph is in row zero cell 1.
  272. Paragraph logo_paragraph = template.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  273. // Remove the template Picture that is in this Paragraph.
  274. logo_paragraph.Pictures[0].Remove();
  275. // Add the Happy Builders logo to this document.
  276. Novacode.Image logo = template.AddImage(@"images\logo_the_happy_builder.png");
  277. // Insert the Happy Builders logo into this Paragraph.
  278. logo_paragraph.InsertPicture(logo.CreatePicture());
  279. #endregion
  280. #region Set CustomProperty values
  281. // Set the value of the custom property 'company_name'.
  282. template.AddCustomProperty(new CustomProperty("company_name", "The Happy Builder"));
  283. // Set the value of the custom property 'company_slogan'.
  284. template.AddCustomProperty(new CustomProperty("company_slogan", "No job too small"));
  285. // Set the value of the custom properties 'hired_company_address_line_one', 'hired_company_address_line_two' and 'hired_company_address_line_three'.
  286. template.AddCustomProperty(new CustomProperty("hired_company_address_line_one", "The Crooked House,"));
  287. template.AddCustomProperty(new CustomProperty("hired_company_address_line_two", "Dublin,"));
  288. template.AddCustomProperty(new CustomProperty("hired_company_address_line_three", "12345"));
  289. // Set the value of the custom property 'invoice_date'.
  290. template.AddCustomProperty(new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d")));
  291. // Set the value of the custom property 'invoice_number'.
  292. template.AddCustomProperty(new CustomProperty("invoice_number", 1));
  293. // Set the value of the custom property 'hired_company_details_line_one' and 'hired_company_details_line_two'.
  294. template.AddCustomProperty(new CustomProperty("hired_company_details_line_one", "Business Street, Dublin, 12345"));
  295. template.AddCustomProperty(new CustomProperty("hired_company_details_line_two", "Phone: 012-345-6789, Fax: 012-345-6789, e-mail: support@thehappybuilder.com"));
  296. #endregion
  297. /*
  298. * InvoiceTemplate.docx contains a blank Table,
  299. * we want to replace this with a new Table that
  300. * contains all of our invoice data.
  301. */
  302. Table t = template.Tables[1];
  303. Table invoice_table = CreateAndInsertInvoiceTableAfter(t, ref template);
  304. t.Remove();
  305. // Return the template now that it has been modified to hold all of our custom data.
  306. return template;
  307. }
  308. // Create an invoice template.
  309. private static DocX CreateInvoiceTemplate()
  310. {
  311. // Create a new document.
  312. DocX document = DocX.Create(@"docs\InvoiceTemplate.docx");
  313. // Create a table for layout purposes (This table will be invisible).
  314. Table layout_table = document.InsertTable(2, 2);
  315. layout_table.Design = TableDesign.TableNormal;
  316. layout_table.AutoFit = AutoFit.Window;
  317. // Dark formatting
  318. Formatting dark_formatting = new Formatting();
  319. dark_formatting.Bold = true;
  320. dark_formatting.Size = 12;
  321. dark_formatting.FontColor = Color.FromArgb(31, 73, 125);
  322. // Light formatting
  323. Formatting light_formatting = new Formatting();
  324. light_formatting.Italic = true;
  325. light_formatting.Size = 11;
  326. light_formatting.FontColor = Color.FromArgb(79, 129, 189);
  327. #region Company Name
  328. // Get the upper left Paragraph in the layout_table.
  329. Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0];
  330. // Create a custom property called company_name
  331. CustomProperty company_name = new CustomProperty("company_name", "Company Name");
  332. // Insert a field of type doc property (This will display the custom property 'company_name')
  333. layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting);
  334. // Force the next text insert to be on a new line.
  335. upper_left_paragraph.InsertText("\n", false);
  336. #endregion
  337. #region Company Slogan
  338. // Create a custom property called company_slogan
  339. CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here.");
  340. // Insert a field of type doc property (This will display the custom property 'company_slogan')
  341. upper_left_paragraph.InsertDocProperty(company_slogan, f: light_formatting);
  342. #endregion
  343. #region Company Logo
  344. // Get the upper right Paragraph in the layout_table.
  345. Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0];
  346. // Add a template logo image to this document.
  347. Novacode.Image logo = document.AddImage(@"images\logo_template.png");
  348. // Insert this template logo into the upper right Paragraph.
  349. upper_right_paragraph.InsertPicture(logo.CreatePicture());
  350. upper_right_paragraph.Alignment = Alignment.right;
  351. #endregion
  352. // Custom properties cannot contain newlines, so the company address must be split into 3 custom properties.
  353. #region Hired Company Address
  354. // Create a custom property called company_address_line_one
  355. CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,");
  356. // Get the lower left Paragraph in the layout_table.
  357. Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0];
  358. lower_left_paragraph.InsertText("TO:\n", false, dark_formatting);
  359. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one')
  360. lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, f: light_formatting);
  361. // Force the next text insert to be on a new line.
  362. lower_left_paragraph.InsertText("\n", false);
  363. // Create a custom property called company_address_line_two
  364. CustomProperty hired_company_address_line_two = new CustomProperty("hired_company_address_line_two", "City,");
  365. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two')
  366. lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f: light_formatting);
  367. // Force the next text insert to be on a new line.
  368. lower_left_paragraph.InsertText("\n", false);
  369. // Create a custom property called company_address_line_two
  370. CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code");
  371. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three')
  372. lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f: light_formatting);
  373. #endregion
  374. #region Date & Invoice number
  375. // Get the lower right Paragraph from the layout table.
  376. Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0];
  377. CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"));
  378. lower_right_paragraph.InsertText("Date: ", false, dark_formatting);
  379. lower_right_paragraph.InsertDocProperty(invoice_date, f: light_formatting);
  380. CustomProperty invoice_number = new CustomProperty("invoice_number", 1);
  381. lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting);
  382. lower_right_paragraph.InsertText("#", false, light_formatting);
  383. lower_right_paragraph.InsertDocProperty(invoice_number, f: light_formatting);
  384. lower_right_paragraph.Alignment = Alignment.right;
  385. #endregion
  386. // Insert an empty Paragraph between two Tables, so that they do not touch.
  387. document.InsertParagraph(string.Empty, false);
  388. // This table will hold all of the invoice data.
  389. Table invoice_table = document.InsertTable(4, 4);
  390. invoice_table.Design = TableDesign.LightShadingAccent1;
  391. invoice_table.Alignment = Alignment.center;
  392. // A nice thank you Paragraph.
  393. Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting);
  394. thankyou.Alignment = Alignment.center;
  395. #region Hired company details
  396. CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code");
  397. 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");
  398. Paragraph companyDetails = document.InsertParagraph(string.Empty, false);
  399. companyDetails.InsertDocProperty(hired_company_details_line_one, f: light_formatting);
  400. companyDetails.InsertText("\n", false);
  401. companyDetails.InsertDocProperty(hired_company_details_line_two, f: light_formatting);
  402. companyDetails.Alignment = Alignment.center;
  403. #endregion
  404. // Return the document now that it has been created.
  405. return document;
  406. }
  407. private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
  408. {
  409. // Grab data from somewhere (Most likely a database)
  410. DataTable data = GetDataFromDatabase();
  411. /*
  412. * The trick to replacing one Table with another,
  413. * is to insert the new Table after the old one,
  414. * and then remove the old one.
  415. */
  416. Table invoice_table = t.InsertTableAfterSelf(data.Rows.Count + 1, data.Columns.Count);
  417. invoice_table.Design = TableDesign.LightShadingAccent1;
  418. #region Table title
  419. Formatting table_title = new Formatting();
  420. table_title.Bold = true;
  421. invoice_table.Rows[0].Cells[0].Paragraphs[0].InsertText("Description", false, table_title);
  422. invoice_table.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
  423. invoice_table.Rows[0].Cells[1].Paragraphs[0].InsertText("Hours", false, table_title);
  424. invoice_table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
  425. invoice_table.Rows[0].Cells[2].Paragraphs[0].InsertText("Rate", false, table_title);
  426. invoice_table.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
  427. invoice_table.Rows[0].Cells[3].Paragraphs[0].InsertText("Amount", false, table_title);
  428. invoice_table.Rows[0].Cells[3].Paragraphs[0].Alignment = Alignment.center;
  429. #endregion
  430. // Loop through the rows in the Table and insert data from the data source.
  431. for (int row = 1; row < invoice_table.RowCount; row++)
  432. {
  433. for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
  434. {
  435. Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
  436. cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
  437. }
  438. }
  439. // We want to fill in the total by suming the values from the amount coloumn.
  440. Row total = invoice_table.InsertRow();
  441. total.Cells[0].Paragraphs[0].InsertText("Total:", false);
  442. Paragraph total_paragraph = total.Cells[invoice_table.ColumnCount - 1].Paragraphs[0];
  443. /*
  444. * Lots of people are scared of LINQ,
  445. * so I will walk you through this line by line.
  446. *
  447. * invoice_table.Rows is an IEnumerable<Row> (i.e a collection of rows), with LINQ you can query collections.
  448. * .Where(condition) is a filter that you want to apply to the items of this collection.
  449. * My condition is that the index of the row must be greater than 0 and less than RowCount.
  450. * .Select(something) lets you select something from each item in the filtered collection.
  451. * I am selecting the Text value from each row, for example €100, then I am remove the €,
  452. * and then I am parsing the remaining string as a double. This will return a collection of doubles,
  453. * the final thing I do is call .Sum() on this collection which return one double the sum of all the doubles,
  454. * this is the total.
  455. */
  456. double totalCost =
  457. (
  458. invoice_table.Rows
  459. .Where((row, index) => index > 0 && index < invoice_table.RowCount - 1)
  460. .Select(row => double.Parse(row.Cells[row.Cells.Count() - 1].Paragraphs[0].Text.Remove(0, 1)))
  461. ).Sum();
  462. // Insert the total calculated above using LINQ into the total Paragraph.
  463. total_paragraph.InsertText(string.Format("€{0}", totalCost), false);
  464. // Let the tables coloumns expand to fit its contents.
  465. invoice_table.AutoFit = AutoFit.Contents;
  466. // Center the Table
  467. invoice_table.Alignment = Alignment.center;
  468. // Return the invloce table now that it has been created.
  469. return invoice_table;
  470. }
  471. // You need to rewrite this function to grab data from your data source.
  472. private static DataTable GetDataFromDatabase()
  473. {
  474. DataTable table = new DataTable();
  475. table.Columns.AddRange(new DataColumn[] { new DataColumn("Description"), new DataColumn("Hours"), new DataColumn("Rate"), new DataColumn("Amount") });
  476. table.Rows.Add
  477. (
  478. "Install wooden doors (Kitchen, Sitting room, Dining room & Bedrooms)",
  479. "5",
  480. "€25",
  481. string.Format("€{0}", 5 * 25)
  482. );
  483. table.Rows.Add
  484. (
  485. "Fit stairs",
  486. "20",
  487. "€30",
  488. string.Format("€{0}", 20 * 30)
  489. );
  490. table.Rows.Add
  491. (
  492. "Replace Sitting room window",
  493. "6",
  494. "€50",
  495. string.Format("€{0}", 6 * 50)
  496. );
  497. table.Rows.Add
  498. (
  499. "Build garden shed",
  500. "10",
  501. "€10",
  502. string.Format("€{0}", 10 * 10)
  503. );
  504. table.Rows.Add
  505. (
  506. "Fit new lock on back door",
  507. "0.5",
  508. "€30",
  509. string.Format("€{0}", 0.5 * 30)
  510. );
  511. table.Rows.Add
  512. (
  513. "Tile Kitchen floor",
  514. "24",
  515. "€25",
  516. string.Format("€{0}", 24 * 25)
  517. );
  518. return table;
  519. }
  520. /// <summary>
  521. /// Creates a simple document with the text Hello World.
  522. /// </summary>
  523. static void HelloWorld()
  524. {
  525. Console.WriteLine("\tHelloWorld()");
  526. // Create a new document.
  527. using (DocX document = DocX.Create(@"docs\Hello World.docx"))
  528. {
  529. // Insert a Paragraph into this document.
  530. Paragraph p = document.InsertParagraph();
  531. // Append some text and add formatting.
  532. p.Append("Hello World")
  533. .Font(new FontFamily("Times New Roman"))
  534. .FontSize(32)
  535. .Color(Color.Blue)
  536. .Bold();
  537. // Save this document to disk.
  538. document.Save();
  539. Console.WriteLine("\tCreated: docs\\Hello World.docx\n");
  540. }
  541. }
  542. /// <summary>
  543. /// Loads a document 'Input.docx' and writes the text 'Hello World' into the first imbedded Image.
  544. /// This code creates the file 'Output.docx'.
  545. /// </summary>
  546. static void ProgrammaticallyManipulateImbeddedImage()
  547. {
  548. Console.WriteLine("\tProgrammaticallyManipulateImbeddedImage()");
  549. const string str = "Hello World";
  550. // Open the document Input.docx.
  551. using (DocX document = DocX.Load(@"Input.docx"))
  552. {
  553. // Make sure this document has at least one Image.
  554. if (document.Images.Count() > 0)
  555. {
  556. Novacode.Image img = document.Images[0];
  557. // Write "Hello World" into this Image.
  558. Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
  559. /*
  560. * Get the Graphics object for this Bitmap.
  561. * The Graphics object provides functions for drawing.
  562. */
  563. Graphics g = Graphics.FromImage(b);
  564. // Draw the string "Hello World".
  565. g.DrawString
  566. (
  567. str,
  568. new Font("Tahoma", 20),
  569. Brushes.Blue,
  570. new PointF(0, 0)
  571. );
  572. // Save this Bitmap back into the document using a Create\Write stream.
  573. b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
  574. }
  575. else
  576. Console.WriteLine("The provided document contains no Images.");
  577. // Save this document as Output.docx.
  578. document.SaveAs(@"docs\Output.docx");
  579. Console.WriteLine("\tCreated: docs\\Output.docx\n");
  580. }
  581. }
  582. /// <summary>
  583. /// For each of the documents in the folder 'docs\',
  584. /// Replace the string a with the string b,
  585. /// Do this in Parrallel accross many CPU cores.
  586. /// </summary>
  587. static void ReplaceTextParallel()
  588. {
  589. Console.WriteLine("\tReplaceTextParallel()\n");
  590. const string a = "apple";
  591. const string b = "pear";
  592. // Directory containing many .docx documents.
  593. DirectoryInfo di = new DirectoryInfo(@"docs\");
  594. // Loop through each document in this specified direction.
  595. Parallel.ForEach
  596. (
  597. di.GetFiles(),
  598. currentFile =>
  599. {
  600. // Load the document.
  601. using (DocX document = DocX.Load(currentFile.FullName))
  602. {
  603. // Replace text in this document.
  604. document.ReplaceText(a, b);
  605. // Save changes made to this document.
  606. document.Save();
  607. } // Release this document from memory.
  608. }
  609. );
  610. Console.WriteLine("\tCreated: None\n");
  611. }
  612. }
  613. }