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

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