選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Program.cs 32KB

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