您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Program.cs 35KB

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