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

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