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

Program.cs 33KB

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