You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Program.cs 31KB

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