Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Program.cs 36KB

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