Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  243. rd.Up(2);
  244. Novacode.Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  245. // Create a picture (A custom view of an Image).
  246. Picture picture = image.CreatePicture();
  247. picture.Rotation = 10;
  248. picture.SetPictureShape(BasicShapes.cube);
  249. // Insert a new Paragraph into the document.
  250. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  251. title.Alignment = Alignment.center;
  252. // Insert a new Paragraph into the document.
  253. Paragraph p1 = document.InsertParagraph();
  254. // Append content to the Paragraph
  255. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  256. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  257. p1.AppendLine();
  258. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  259. p1.AppendLine();
  260. p1.AppendLine("Can you check this Table of figures for me?");
  261. p1.AppendLine();
  262. // Insert the Table after Paragraph 1.
  263. p1.InsertTableAfterSelf(table);
  264. // Insert a new Paragraph into the document.
  265. Paragraph p2 = document.InsertParagraph();
  266. // Append content to the Paragraph.
  267. p2.AppendLine("Is it correct?");
  268. // Save this document.
  269. document.Save();
  270. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
  271. }
  272. }
  273. private static void AddList()
  274. {
  275. Console.WriteLine("\tAddList()");
  276. using (var document = DocX.Create(@"docs\Lists.docx"))
  277. {
  278. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 2);
  279. document.AddListItem(numberedList, "First sub list item", 1);
  280. document.AddListItem(numberedList, "Second List Item.");
  281. document.AddListItem(numberedList, "Third list item.");
  282. document.AddListItem(numberedList, "Nested item.", 1);
  283. document.AddListItem(numberedList, "Second nested item.", 1);
  284. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  285. document.AddListItem(bulletedList, "Second bullet item");
  286. document.AddListItem(bulletedList, "Sub bullet item", 1);
  287. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  288. document.AddListItem(bulletedList, "Third bullet item");
  289. document.InsertList(numberedList);
  290. document.InsertList(bulletedList);
  291. document.Save();
  292. Console.WriteLine("\tCreated: docs\\Lists.docx");
  293. }
  294. }
  295. private static void HeadersAndFooters()
  296. {
  297. Console.WriteLine("\tHeadersAndFooters()");
  298. // Create a new document.
  299. using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx"))
  300. {
  301. // Add Headers and Footers to this document.
  302. document.AddHeaders();
  303. document.AddFooters();
  304. // Force the first page to have a different Header and Footer.
  305. document.DifferentFirstPage = true;
  306. // Force odd & even pages to have different Headers and Footers.
  307. document.DifferentOddAndEvenPages = true;
  308. // Get the first, odd and even Headers for this document.
  309. Header header_first = document.Headers.first;
  310. Header header_odd = document.Headers.odd;
  311. Header header_even = document.Headers.even;
  312. // Get the first, odd and even Footer for this document.
  313. Footer footer_first = document.Footers.first;
  314. Footer footer_odd = document.Footers.odd;
  315. Footer footer_even = document.Footers.even;
  316. // Insert a Paragraph into the first Header.
  317. Paragraph p0 = header_first.InsertParagraph();
  318. p0.Append("Hello First Header.").Bold();
  319. // Insert a Paragraph into the odd Header.
  320. Paragraph p1 = header_odd.InsertParagraph();
  321. p1.Append("Hello Odd Header.").Bold();
  322. // Insert a Paragraph into the even Header.
  323. Paragraph p2 = header_even.InsertParagraph();
  324. p2.Append("Hello Even Header.").Bold();
  325. // Insert a Paragraph into the first Footer.
  326. Paragraph p3 = footer_first.InsertParagraph();
  327. p3.Append("Hello First Footer.").Bold();
  328. // Insert a Paragraph into the odd Footer.
  329. Paragraph p4 = footer_odd.InsertParagraph();
  330. p4.Append("Hello Odd Footer.").Bold();
  331. // Insert a Paragraph into the even Header.
  332. Paragraph p5 = footer_even.InsertParagraph();
  333. p5.Append("Hello Even Footer.").Bold();
  334. // Insert a Paragraph into the document.
  335. Paragraph p6 = document.InsertParagraph();
  336. p6.AppendLine("Hello First page.");
  337. // Create a second page to show that the first page has its own header and footer.
  338. p6.InsertPageBreakAfterSelf();
  339. // Insert a Paragraph after the page break.
  340. Paragraph p7 = document.InsertParagraph();
  341. p7.AppendLine("Hello Second page.");
  342. // Create a third page to show that even and odd pages have different headers and footers.
  343. p7.InsertPageBreakAfterSelf();
  344. // Insert a Paragraph after the page break.
  345. Paragraph p8 = document.InsertParagraph();
  346. p8.AppendLine("Hello Third page.");
  347. //Insert a next page break, which is a section break combined with a page break
  348. document.InsertSectionPageBreak();
  349. //Insert a paragraph after the "Next" page break
  350. Paragraph p9 = document.InsertParagraph();
  351. p9.Append("Next page section break.");
  352. //Insert a continuous section break
  353. document.InsertSection();
  354. //Create a paragraph in the new section
  355. var p10 = document.InsertParagraph();
  356. p10.Append("Continuous section paragraph.");
  357. // Save all changes to this document.
  358. document.Save();
  359. Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n");
  360. }// Release this document from memory.
  361. }
  362. private static void CreateInvoice()
  363. {
  364. Console.WriteLine("\tCreateInvoice()");
  365. DocX g_document;
  366. try
  367. {
  368. // Store a global reference to the loaded document.
  369. g_document = DocX.Load(@"docs\InvoiceTemplate.docx");
  370. /*
  371. * The template 'InvoiceTemplate.docx' does exist,
  372. * so lets use it to create an invoice for a factitious company
  373. * called "The Happy Builder" and store a global reference it.
  374. */
  375. g_document = CreateInvoiceFromTemplate(DocX.Load(@"docs\InvoiceTemplate.docx"));
  376. // Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
  377. g_document.SaveAs(@"docs\Invoice_The_Happy_Builder.docx");
  378. Console.WriteLine("\tCreated: docs\\Invoice_The_Happy_Builder.docx\n");
  379. }
  380. // The template 'InvoiceTemplate.docx' does not exist, so create it.
  381. catch (FileNotFoundException)
  382. {
  383. // Create and store a global reference to the template 'InvoiceTemplate.docx'.
  384. g_document = CreateInvoiceTemplate();
  385. // Save the template 'InvoiceTemplate.docx'.
  386. g_document.Save();
  387. Console.WriteLine("\tCreated: docs\\InvoiceTemplate.docx");
  388. // The template exists now so re-call CreateInvoice().
  389. CreateInvoice();
  390. }
  391. }
  392. // Create an invoice for a factitious company called "The Happy Builder".
  393. private static DocX CreateInvoiceFromTemplate(DocX template)
  394. {
  395. #region Logo
  396. // A quick glance at the template shows us that the logo Paragraph is in row zero cell 1.
  397. Paragraph logo_paragraph = template.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  398. // Remove the template Picture that is in this Paragraph.
  399. logo_paragraph.Pictures[0].Remove();
  400. // Add the Happy Builders logo to this document.
  401. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  402. rd.Up(2);
  403. Novacode.Image logo = template.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  404. // Insert the Happy Builders logo into this Paragraph.
  405. logo_paragraph.InsertPicture(logo.CreatePicture());
  406. #endregion
  407. #region Set CustomProperty values
  408. // Set the value of the custom property 'company_name'.
  409. template.AddCustomProperty(new CustomProperty("company_name", "The Happy Builder"));
  410. // Set the value of the custom property 'company_slogan'.
  411. template.AddCustomProperty(new CustomProperty("company_slogan", "No job too small"));
  412. // Set the value of the custom properties 'hired_company_address_line_one', 'hired_company_address_line_two' and 'hired_company_address_line_three'.
  413. template.AddCustomProperty(new CustomProperty("hired_company_address_line_one", "The Crooked House,"));
  414. template.AddCustomProperty(new CustomProperty("hired_company_address_line_two", "Dublin,"));
  415. template.AddCustomProperty(new CustomProperty("hired_company_address_line_three", "12345"));
  416. // Set the value of the custom property 'invoice_date'.
  417. template.AddCustomProperty(new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d")));
  418. // Set the value of the custom property 'invoice_number'.
  419. template.AddCustomProperty(new CustomProperty("invoice_number", 1));
  420. // Set the value of the custom property 'hired_company_details_line_one' and 'hired_company_details_line_two'.
  421. template.AddCustomProperty(new CustomProperty("hired_company_details_line_one", "Business Street, Dublin, 12345"));
  422. template.AddCustomProperty(new CustomProperty("hired_company_details_line_two", "Phone: 012-345-6789, Fax: 012-345-6789, e-mail: support@thehappybuilder.com"));
  423. #endregion
  424. /*
  425. * InvoiceTemplate.docx contains a blank Table,
  426. * we want to replace this with a new Table that
  427. * contains all of our invoice data.
  428. */
  429. Table t = template.Tables[1];
  430. Table invoice_table = CreateAndInsertInvoiceTableAfter(t, ref template);
  431. t.Remove();
  432. // Return the template now that it has been modified to hold all of our custom data.
  433. return template;
  434. }
  435. // Create an invoice template.
  436. private static DocX CreateInvoiceTemplate()
  437. {
  438. // Create a new document.
  439. DocX document = DocX.Create(@"docs\InvoiceTemplate.docx");
  440. // Create a table for layout purposes (This table will be invisible).
  441. Table layout_table = document.InsertTable(2, 2);
  442. layout_table.Design = TableDesign.TableNormal;
  443. layout_table.AutoFit = AutoFit.Window;
  444. // Dark formatting
  445. Formatting dark_formatting = new Formatting();
  446. dark_formatting.Bold = true;
  447. dark_formatting.Size = 12;
  448. dark_formatting.FontColor = Color.FromArgb(31, 73, 125);
  449. // Light formatting
  450. Formatting light_formatting = new Formatting();
  451. light_formatting.Italic = true;
  452. light_formatting.Size = 11;
  453. light_formatting.FontColor = Color.FromArgb(79, 129, 189);
  454. #region Company Name
  455. // Get the upper left Paragraph in the layout_table.
  456. Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0];
  457. // Create a custom property called company_name
  458. CustomProperty company_name = new CustomProperty("company_name", "Company Name");
  459. // Insert a field of type doc property (This will display the custom property 'company_name')
  460. layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting);
  461. // Force the next text insert to be on a new line.
  462. upper_left_paragraph.InsertText("\n", false);
  463. #endregion
  464. #region Company Slogan
  465. // Create a custom property called company_slogan
  466. CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here.");
  467. // Insert a field of type doc property (This will display the custom property 'company_slogan')
  468. upper_left_paragraph.InsertDocProperty(company_slogan, f: light_formatting);
  469. #endregion
  470. #region Company Logo
  471. // Get the upper right Paragraph in the layout_table.
  472. Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0];
  473. // Add a template logo image to this document.
  474. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  475. rd.Up(2);
  476. Novacode.Image logo = document.AddImage(rd.Path + @"\images\logo_template.png");
  477. // Insert this template logo into the upper right Paragraph.
  478. upper_right_paragraph.InsertPicture(logo.CreatePicture());
  479. upper_right_paragraph.Alignment = Alignment.right;
  480. #endregion
  481. // Custom properties cannot contain newlines, so the company address must be split into 3 custom properties.
  482. #region Hired Company Address
  483. // Create a custom property called company_address_line_one
  484. CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,");
  485. // Get the lower left Paragraph in the layout_table.
  486. Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0];
  487. lower_left_paragraph.InsertText("TO:\n", false, dark_formatting);
  488. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one')
  489. lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, 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_two = new CustomProperty("hired_company_address_line_two", "City,");
  494. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two')
  495. lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f: light_formatting);
  496. // Force the next text insert to be on a new line.
  497. lower_left_paragraph.InsertText("\n", false);
  498. // Create a custom property called company_address_line_two
  499. CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code");
  500. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three')
  501. lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f: light_formatting);
  502. #endregion
  503. #region Date & Invoice number
  504. // Get the lower right Paragraph from the layout table.
  505. Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0];
  506. CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"));
  507. lower_right_paragraph.InsertText("Date: ", false, dark_formatting);
  508. lower_right_paragraph.InsertDocProperty(invoice_date, f: light_formatting);
  509. CustomProperty invoice_number = new CustomProperty("invoice_number", 1);
  510. lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting);
  511. lower_right_paragraph.InsertText("#", false, light_formatting);
  512. lower_right_paragraph.InsertDocProperty(invoice_number, f: light_formatting);
  513. lower_right_paragraph.Alignment = Alignment.right;
  514. #endregion
  515. // Insert an empty Paragraph between two Tables, so that they do not touch.
  516. document.InsertParagraph(string.Empty, false);
  517. // This table will hold all of the invoice data.
  518. Table invoice_table = document.InsertTable(4, 4);
  519. invoice_table.Design = TableDesign.LightShadingAccent1;
  520. invoice_table.Alignment = Alignment.center;
  521. // A nice thank you Paragraph.
  522. Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting);
  523. thankyou.Alignment = Alignment.center;
  524. #region Hired company details
  525. CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code");
  526. 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");
  527. Paragraph companyDetails = document.InsertParagraph(string.Empty, false);
  528. companyDetails.InsertDocProperty(hired_company_details_line_one, f: light_formatting);
  529. companyDetails.InsertText("\n", false);
  530. companyDetails.InsertDocProperty(hired_company_details_line_two, f: light_formatting);
  531. companyDetails.Alignment = Alignment.center;
  532. #endregion
  533. // Return the document now that it has been created.
  534. return document;
  535. }
  536. private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
  537. {
  538. // Grab data from somewhere (Most likely a database)
  539. DataTable data = GetDataFromDatabase();
  540. /*
  541. * The trick to replacing one Table with another,
  542. * is to insert the new Table after the old one,
  543. * and then remove the old one.
  544. */
  545. Table invoice_table = t.InsertTableAfterSelf(data.Rows.Count + 1, data.Columns.Count);
  546. invoice_table.Design = TableDesign.LightShadingAccent1;
  547. #region Table title
  548. Formatting table_title = new Formatting();
  549. table_title.Bold = true;
  550. invoice_table.Rows[0].Cells[0].Paragraphs[0].InsertText("Description", false, table_title);
  551. invoice_table.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
  552. invoice_table.Rows[0].Cells[1].Paragraphs[0].InsertText("Hours", false, table_title);
  553. invoice_table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
  554. invoice_table.Rows[0].Cells[2].Paragraphs[0].InsertText("Rate", false, table_title);
  555. invoice_table.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
  556. invoice_table.Rows[0].Cells[3].Paragraphs[0].InsertText("Amount", false, table_title);
  557. invoice_table.Rows[0].Cells[3].Paragraphs[0].Alignment = Alignment.center;
  558. #endregion
  559. // Loop through the rows in the Table and insert data from the data source.
  560. for (int row = 1; row < invoice_table.RowCount; row++)
  561. {
  562. for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
  563. {
  564. Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
  565. cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
  566. }
  567. }
  568. // We want to fill in the total by suming the values from the amount column.
  569. Row total = invoice_table.InsertRow();
  570. total.Cells[0].Paragraphs[0].InsertText("Total:", false);
  571. Paragraph total_paragraph = total.Cells[invoice_table.ColumnCount - 1].Paragraphs[0];
  572. /*
  573. * Lots of people are scared of LINQ,
  574. * so I will walk you through this line by line.
  575. *
  576. * invoice_table.Rows is an IEnumerable<Row> (i.e a collection of rows), with LINQ you can query collections.
  577. * .Where(condition) is a filter that you want to apply to the items of this collection.
  578. * My condition is that the index of the row must be greater than 0 and less than RowCount.
  579. * .Select(something) lets you select something from each item in the filtered collection.
  580. * I am selecting the Text value from each row, for example €100, then I am remove the €,
  581. * and then I am parsing the remaining string as a double. This will return a collection of doubles,
  582. * the final thing I do is call .Sum() on this collection which return one double the sum of all the doubles,
  583. * this is the total.
  584. */
  585. double totalCost =
  586. (
  587. invoice_table.Rows
  588. .Where((row, index) => index > 0 && index < invoice_table.RowCount - 1)
  589. .Select(row => double.Parse(row.Cells[row.Cells.Count() - 1].Paragraphs[0].Text.Remove(0, 1)))
  590. ).Sum();
  591. // Insert the total calculated above using LINQ into the total Paragraph.
  592. total_paragraph.InsertText(string.Format("€{0}", totalCost), false);
  593. // Let the tables columns expand to fit its contents.
  594. invoice_table.AutoFit = AutoFit.Contents;
  595. // Center the Table
  596. invoice_table.Alignment = Alignment.center;
  597. // Return the invloce table now that it has been created.
  598. return invoice_table;
  599. }
  600. // You need to rewrite this function to grab data from your data source.
  601. private static DataTable GetDataFromDatabase()
  602. {
  603. DataTable table = new DataTable();
  604. table.Columns.AddRange(new DataColumn[] { new DataColumn("Description"), new DataColumn("Hours"), new DataColumn("Rate"), new DataColumn("Amount") });
  605. table.Rows.Add
  606. (
  607. "Install wooden doors (Kitchen, Sitting room, Dining room & Bedrooms)",
  608. "5",
  609. "€25",
  610. string.Format("€{0}", 5 * 25)
  611. );
  612. table.Rows.Add
  613. (
  614. "Fit stairs",
  615. "20",
  616. "€30",
  617. string.Format("€{0}", 20 * 30)
  618. );
  619. table.Rows.Add
  620. (
  621. "Replace Sitting room window",
  622. "6",
  623. "€50",
  624. string.Format("€{0}", 6 * 50)
  625. );
  626. table.Rows.Add
  627. (
  628. "Build garden shed",
  629. "10",
  630. "€10",
  631. string.Format("€{0}", 10 * 10)
  632. );
  633. table.Rows.Add
  634. (
  635. "Fit new lock on back door",
  636. "0.5",
  637. "€30",
  638. string.Format("€{0}", 0.5 * 30)
  639. );
  640. table.Rows.Add
  641. (
  642. "Tile Kitchen floor",
  643. "24",
  644. "€25",
  645. string.Format("€{0}", 24 * 25)
  646. );
  647. return table;
  648. }
  649. /// <summary>
  650. /// Creates a simple document with the text Hello World.
  651. /// </summary>
  652. static void HelloWorld()
  653. {
  654. Console.WriteLine("\tHelloWorld()");
  655. // Create a new document.
  656. using (DocX document = DocX.Create(@"docs\Hello World.docx"))
  657. {
  658. // Insert a Paragraph into this document.
  659. Paragraph p = document.InsertParagraph();
  660. // Append some text and add formatting.
  661. p.Append("Hello World!^011Hello World!")
  662. .Font(new FontFamily("Times New Roman"))
  663. .FontSize(32)
  664. .Color(Color.Blue)
  665. .Bold();
  666. // Save this document to disk.
  667. document.Save();
  668. Console.WriteLine("\tCreated: docs\\Hello World.docx\n");
  669. }
  670. }
  671. /// <summary>
  672. /// Loads a document 'Input.docx' and writes the text 'Hello World' into the first imbedded Image.
  673. /// This code creates the file 'Output.docx'.
  674. /// </summary>
  675. static void ProgrammaticallyManipulateImbeddedImage()
  676. {
  677. Console.WriteLine("\tProgrammaticallyManipulateImbeddedImage()");
  678. const string str = "Hello World";
  679. // Open the document Input.docx.
  680. using (DocX document = DocX.Load(@"Input.docx"))
  681. {
  682. // Make sure this document has at least one Image.
  683. if (document.Images.Count() > 0)
  684. {
  685. Novacode.Image img = document.Images[0];
  686. // Write "Hello World" into this Image.
  687. Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
  688. /*
  689. * Get the Graphics object for this Bitmap.
  690. * The Graphics object provides functions for drawing.
  691. */
  692. Graphics g = Graphics.FromImage(b);
  693. // Draw the string "Hello World".
  694. g.DrawString
  695. (
  696. str,
  697. new Font("Tahoma", 20),
  698. Brushes.Blue,
  699. new PointF(0, 0)
  700. );
  701. // Save this Bitmap back into the document using a Create\Write stream.
  702. b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
  703. }
  704. else
  705. Console.WriteLine("The provided document contains no Images.");
  706. // Save this document as Output.docx.
  707. document.SaveAs(@"docs\Output.docx");
  708. Console.WriteLine("\tCreated: docs\\Output.docx\n");
  709. }
  710. }
  711. /// <summary>
  712. /// For each of the documents in the folder 'docs\',
  713. /// Replace the string a with the string b,
  714. /// Do this in Parrallel accross many CPU cores.
  715. /// </summary>
  716. static void ReplaceTextParallel()
  717. {
  718. Console.WriteLine("\tReplaceTextParallel()\n");
  719. const string a = "apple";
  720. const string b = "pear";
  721. // Directory containing many .docx documents.
  722. DirectoryInfo di = new DirectoryInfo(@"docs\");
  723. // Loop through each document in this specified direction.
  724. Parallel.ForEach
  725. (
  726. di.GetFiles(),
  727. currentFile =>
  728. {
  729. // Load the document.
  730. using (DocX document = DocX.Load(currentFile.FullName))
  731. {
  732. // Replace text in this document.
  733. document.ReplaceText(a, b);
  734. // Save changes made to this document.
  735. document.Save();
  736. } // Release this document from memory.
  737. }
  738. );
  739. Console.WriteLine("\tCreated: None\n");
  740. }
  741. }
  742. }