Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

Program.cs 38KB

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