Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Program.cs 30KB

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