選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Program.cs 47KB

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