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 72KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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. using Image = Novacode.Image;
  11. namespace Examples
  12. {
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. Setup();
  18. // Easy
  19. Console.WriteLine("\nRunning Easy Examples");
  20. HelloWorld();
  21. HelloWorldKeepLinesTogether();
  22. HelloWorldKeepWithNext();
  23. RightToLeft();
  24. Indentation();
  25. HeadersAndFooters();
  26. HyperlinksImagesTables();
  27. AddList();
  28. Equations();
  29. Bookmarks();
  30. BarChart();
  31. PieChart();
  32. LineChart();
  33. Chart3D();
  34. DocumentMargins();
  35. CreateTableWithTextDirection();
  36. AddToc();
  37. AddTocByReference();
  38. // Intermediate
  39. Console.WriteLine("\nRunning Intermediate Examples");
  40. CreateInvoice();
  41. HyperlinksImagesTablesWithLists();
  42. HeadersAndFootersWithImagesAndTables();
  43. HeadersAndFootersWithImagesAndTablesUsingInsertPicture();
  44. DocumentsWithListsFontChange();
  45. DocumentHeading();
  46. // Advanced
  47. Console.WriteLine("\nRunning Advanced Examples");
  48. ProgrammaticallyManipulateImbeddedImage();
  49. ReplaceTextParallel();
  50. Console.WriteLine("\nPress any key to exit.");
  51. Console.ReadKey();
  52. }
  53. private static void Setup()
  54. {
  55. if (!Directory.Exists("docs"))
  56. {
  57. Directory.CreateDirectory("docs");
  58. }
  59. }
  60. #region Charts
  61. private class ChartData
  62. {
  63. public String Mounth { get; set; }
  64. public Double Money { get; set; }
  65. public static List<ChartData> CreateCompanyList1()
  66. {
  67. List<ChartData> company1 = new List<ChartData>();
  68. company1.Add(new ChartData() { Mounth = "January", Money = 100 });
  69. company1.Add(new ChartData() { Mounth = "February", Money = 120 });
  70. company1.Add(new ChartData() { Mounth = "March", Money = 140 });
  71. return company1;
  72. }
  73. public static List<ChartData> CreateCompanyList2()
  74. {
  75. List<ChartData> company2 = new List<ChartData>();
  76. company2.Add(new ChartData() { Mounth = "January", Money = 80 });
  77. company2.Add(new ChartData() { Mounth = "February", Money = 160 });
  78. company2.Add(new ChartData() { Mounth = "March", Money = 130 });
  79. return company2;
  80. }
  81. }
  82. private static void BarChart()
  83. {
  84. Console.WriteLine("\tBarChart()");
  85. // Create new document.
  86. using (DocX document = DocX.Create(@"docs\BarChart.docx"))
  87. {
  88. // Create chart.
  89. BarChart c = new BarChart();
  90. c.BarDirection = BarDirection.Column;
  91. c.BarGrouping = BarGrouping.Standard;
  92. c.GapWidth = 400;
  93. c.AddLegend(ChartLegendPosition.Bottom, false);
  94. // Create data.
  95. List<ChartData> company1 = ChartData.CreateCompanyList1();
  96. List<ChartData> company2 = ChartData.CreateCompanyList2();
  97. // Create and add series
  98. Series s1 = new Series("Microsoft");
  99. s1.Color = Color.GreenYellow;
  100. s1.Bind(company1, "Mounth", "Money");
  101. c.AddSeries(s1);
  102. Series s2 = new Series("Apple");
  103. s2.Bind(company2, "Mounth", "Money");
  104. c.AddSeries(s2);
  105. // Insert chart into document
  106. document.InsertParagraph("Diagram").FontSize(20);
  107. document.InsertChart(c);
  108. document.Save();
  109. }
  110. Console.WriteLine("\tCreated: docs\\BarChart.docx\n");
  111. }
  112. private static void PieChart()
  113. {
  114. Console.WriteLine("\tPieChart()");
  115. // Create new document.
  116. using (DocX document = DocX.Create(@"docs\PieChart.docx"))
  117. {
  118. // Create chart.
  119. PieChart c = new PieChart();
  120. c.AddLegend(ChartLegendPosition.Bottom, false);
  121. // Create data.
  122. List<ChartData> company2 = ChartData.CreateCompanyList2();
  123. // Create and add series
  124. Series s = new Series("Apple");
  125. s.Bind(company2, "Mounth", "Money");
  126. c.AddSeries(s);
  127. // Insert chart into document
  128. document.InsertParagraph("Diagram").FontSize(20);
  129. document.InsertChart(c);
  130. document.Save();
  131. }
  132. Console.WriteLine("\tCreated: docs\\PieChart.docx\n");
  133. }
  134. private static void LineChart()
  135. {
  136. Console.WriteLine("\tLineChart()");
  137. // Create new document.
  138. using (DocX document = DocX.Create(@"docs\LineChart.docx"))
  139. {
  140. // Create chart.
  141. LineChart c = new LineChart();
  142. c.AddLegend(ChartLegendPosition.Bottom, false);
  143. // Create data.
  144. List<ChartData> company1 = ChartData.CreateCompanyList1();
  145. List<ChartData> company2 = ChartData.CreateCompanyList2();
  146. // Create and add series
  147. Series s1 = new Series("Microsoft");
  148. s1.Color = Color.GreenYellow;
  149. s1.Bind(company1, "Mounth", "Money");
  150. c.AddSeries(s1);
  151. Series s2 = new Series("Apple");
  152. s2.Bind(company2, "Mounth", "Money");
  153. c.AddSeries(s2);
  154. // Insert chart into document
  155. document.InsertParagraph("Diagram").FontSize(20);
  156. document.InsertChart(c);
  157. document.Save();
  158. }
  159. Console.WriteLine("\tCreated: docs\\LineChart.docx\n");
  160. }
  161. private static void Chart3D()
  162. {
  163. Console.WriteLine("\tChart3D()");
  164. // Create new document.
  165. using (DocX document = DocX.Create(@"docs\3DChart.docx"))
  166. {
  167. // Create chart.
  168. BarChart c = new BarChart();
  169. c.View3D = true;
  170. // Create data.
  171. List<ChartData> company1 = ChartData.CreateCompanyList1();
  172. // Create and add series
  173. Series s = new Series("Microsoft");
  174. s.Color = Color.GreenYellow;
  175. s.Bind(company1, "Mounth", "Money");
  176. c.AddSeries(s);
  177. // Insert chart into document
  178. document.InsertParagraph("3D Diagram").FontSize(20);
  179. document.InsertChart(c);
  180. document.Save();
  181. }
  182. Console.WriteLine("\tCreated: docs\\3DChart.docx\n");
  183. }
  184. #endregion
  185. /// <summary>
  186. /// Create a document with two equations.
  187. /// </summary>
  188. private static void Equations()
  189. {
  190. Console.WriteLine("\tEquations()");
  191. // Create a new document.
  192. using (DocX document = DocX.Create(@"docs\Equations.docx"))
  193. {
  194. // Insert first Equation in this document.
  195. Paragraph pEquation1 = document.InsertEquation("x = y+z");
  196. // Insert second Equation in this document and add formatting.
  197. Paragraph pEquation2 = document.InsertEquation("x = (y+z)/t").FontSize(18).Color(Color.Blue);
  198. // Save this document to disk.
  199. document.Save();
  200. Console.WriteLine("\tCreated: docs\\Equations.docx\n");
  201. }
  202. }
  203. public static void DocumentHeading()
  204. {
  205. Console.WriteLine("\tDocumentHeading()");
  206. using (DocX document = DocX.Create(@"docs\DocumentHeading.docx"))
  207. {
  208. foreach (HeadingType heading in (HeadingType[])Enum.GetValues(typeof(HeadingType)))
  209. {
  210. string text = string.Format("{0} - The quick brown fox jumps over the lazy dog", heading.EnumDescription());
  211. Paragraph p = document.InsertParagraph();
  212. p.AppendLine(text).Heading(heading);
  213. }
  214. document.Save();
  215. Console.WriteLine("\tCreated: docs\\DocumentHeading.docx\n");
  216. }
  217. }
  218. private static void Bookmarks()
  219. {
  220. Console.WriteLine("\tBookmarks()");
  221. using (var document = DocX.Create(@"docs\Bookmarks.docx"))
  222. {
  223. var paragraph = document.InsertBookmark("firstBookmark");
  224. var paragraph2 = document.InsertParagraph("This is a paragraph which contains a ");
  225. paragraph2.AppendBookmark("secondBookmark");
  226. paragraph2.Append("bookmark");
  227. paragraph2.InsertAtBookmark("handy ", "secondBookmark");
  228. document.Save();
  229. Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n");
  230. }
  231. }
  232. /// <summary>
  233. /// Create a document with a Paragraph whos first line is indented.
  234. /// </summary>
  235. private static void Indentation()
  236. {
  237. Console.WriteLine("\tIndentation()");
  238. // Create a new document.
  239. using (DocX document = DocX.Create(@"docs\Indentation.docx"))
  240. {
  241. // Create a new Paragraph.
  242. Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  243. // Indent only the first line of the Paragraph.
  244. p.IndentationFirstLine = 1.0f;
  245. // Save all changes made to this document.
  246. document.Save();
  247. Console.WriteLine("\tCreated: docs\\Indentation.docx\n");
  248. }
  249. }
  250. /// <summary>
  251. /// Create a document that with RightToLeft text flow.
  252. /// </summary>
  253. private static void RightToLeft()
  254. {
  255. Console.WriteLine("\tRightToLeft()");
  256. // Create a new document.
  257. using (DocX document = DocX.Create(@"docs\RightToLeft.docx"))
  258. {
  259. // Create a new Paragraph with the text "Hello World".
  260. Paragraph p = document.InsertParagraph("Hello World.");
  261. // Make this Paragraph flow right to left. Default is left to right.
  262. p.Direction = Direction.RightToLeft;
  263. // You don't need to manually set the text direction foreach Paragraph, you can just call this function.
  264. document.SetDirection(Direction.RightToLeft);
  265. // Save all changes made to this document.
  266. document.Save();
  267. Console.WriteLine("\tCreated: docs\\RightToLeft.docx\n");
  268. }
  269. }
  270. /// <summary>
  271. /// Creates a document with a Hyperlink, an Image and a Table.
  272. /// </summary>
  273. private static void HyperlinksImagesTables()
  274. {
  275. Console.WriteLine("\tHyperlinksImagesTables()");
  276. // Create a document.
  277. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx"))
  278. {
  279. // Add a hyperlink into the document.
  280. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  281. // Add a Table into the document.
  282. Table table = document.AddTable(2, 2);
  283. table.Design = TableDesign.ColorfulGridAccent2;
  284. table.Alignment = Alignment.center;
  285. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  286. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  287. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  288. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  289. Row newRow = table.InsertRow(table.Rows[1]);
  290. newRow.ReplaceText("4", "5");
  291. // Add an image into the document.
  292. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  293. rd.Up(2);
  294. Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  295. // Create a picture (A custom view of an Image).
  296. Picture picture = image.CreatePicture();
  297. picture.Rotation = 10;
  298. picture.SetPictureShape(BasicShapes.cube);
  299. // Insert a new Paragraph into the document.
  300. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  301. title.Alignment = Alignment.center;
  302. // Insert a new Paragraph into the document.
  303. Paragraph p1 = document.InsertParagraph();
  304. // Append content to the Paragraph
  305. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  306. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  307. p1.AppendLine();
  308. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  309. p1.AppendLine();
  310. p1.AppendLine("Can you check this Table of figures for me?");
  311. p1.AppendLine();
  312. // Insert the Table after Paragraph 1.
  313. p1.InsertTableAfterSelf(table);
  314. // Insert a new Paragraph into the document.
  315. Paragraph p2 = document.InsertParagraph();
  316. // Append content to the Paragraph.
  317. p2.AppendLine("Is it correct?");
  318. // Save this document.
  319. document.Save();
  320. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
  321. }
  322. }
  323. private static void HyperlinksImagesTablesWithLists()
  324. {
  325. Console.WriteLine("\tHyperlinksImagesTablesWithLists()");
  326. // Create a document.
  327. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTablesWithLists.docx"))
  328. {
  329. // Add a hyperlink into the document.
  330. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  331. // created numbered lists
  332. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
  333. document.AddListItem(numberedList, "First sub list item", 1);
  334. document.AddListItem(numberedList, "Second List Item.");
  335. document.AddListItem(numberedList, "Third list item.");
  336. document.AddListItem(numberedList, "Nested item.", 1);
  337. document.AddListItem(numberedList, "Second nested item.", 1);
  338. // created bulleted lists
  339. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  340. document.AddListItem(bulletedList, "Second bullet item");
  341. document.AddListItem(bulletedList, "Sub bullet item", 1);
  342. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  343. document.AddListItem(bulletedList, "Third bullet item");
  344. // Add a Table into the document.
  345. Table table = document.AddTable(2, 2);
  346. table.Design = TableDesign.ColorfulGridAccent2;
  347. table.Alignment = Alignment.center;
  348. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  349. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  350. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  351. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  352. Row newRow = table.InsertRow(table.Rows[1]);
  353. newRow.ReplaceText("4", "5");
  354. // Add an image into the document.
  355. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  356. rd.Up(2);
  357. Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  358. // Create a picture (A custom view of an Image).
  359. Picture picture = image.CreatePicture();
  360. picture.Rotation = 10;
  361. picture.SetPictureShape(BasicShapes.cube);
  362. // Insert a new Paragraph into the document.
  363. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  364. title.Alignment = Alignment.center;
  365. // Insert a new Paragraph into the document.
  366. Paragraph p1 = document.InsertParagraph();
  367. // Append content to the Paragraph
  368. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  369. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  370. p1.AppendLine();
  371. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  372. p1.AppendLine();
  373. p1.AppendLine("Can you check this Table of figures for me?");
  374. p1.AppendLine();
  375. // Insert the Table after Paragraph 1.
  376. p1.InsertTableAfterSelf(table);
  377. // Insert a new Paragraph into the document.
  378. Paragraph p2 = document.InsertParagraph();
  379. // Append content to the Paragraph.
  380. p2.AppendLine("Is it correct?");
  381. p2.AppendLine();
  382. p2.AppendLine("Adding bullet list below: ");
  383. document.InsertList(bulletedList);
  384. // Adding another paragraph to add table and bullet list after it
  385. Paragraph p3 = document.InsertParagraph();
  386. p3.AppendLine();
  387. p3.AppendLine("Adding another table...");
  388. // Adding another table
  389. Table table1 = document.AddTable(2, 2);
  390. table1.Design = TableDesign.ColorfulGridAccent2;
  391. table1.Alignment = Alignment.center;
  392. table1.Rows[0].Cells[0].Paragraphs[0].Append("1");
  393. table1.Rows[0].Cells[1].Paragraphs[0].Append("2");
  394. table1.Rows[1].Cells[0].Paragraphs[0].Append("3");
  395. table1.Rows[1].Cells[1].Paragraphs[0].Append("4");
  396. Paragraph p4 = document.InsertParagraph();
  397. p4.InsertTableBeforeSelf(table1);
  398. p4.AppendLine();
  399. // Insert numbered list after table
  400. Paragraph p5 = document.InsertParagraph();
  401. p5.AppendLine("Adding numbered list below: ");
  402. p5.AppendLine();
  403. document.InsertList(numberedList);
  404. // Save this document.
  405. document.Save();
  406. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTablesWithLists.docx\n");
  407. }
  408. }
  409. private static void DocumentMargins()
  410. {
  411. Console.WriteLine("\tDocumentMargins()");
  412. // Create a document.
  413. using (DocX document = DocX.Create(@"docs\DocumentMargins.docx"))
  414. {
  415. // Create a float var that contains doc Margins properties.
  416. float leftMargin = document.MarginLeft;
  417. float rightMargin = document.MarginRight;
  418. float topMargin = document.MarginTop;
  419. float bottomMargin = document.MarginBottom;
  420. // Modify using your own vars.
  421. leftMargin = 95F;
  422. rightMargin = 45F;
  423. topMargin = 50F;
  424. bottomMargin = 180F;
  425. // Or simply work the margins by setting the property directly.
  426. document.MarginLeft = leftMargin;
  427. document.MarginRight = rightMargin;
  428. document.MarginTop = topMargin;
  429. document.MarginBottom = bottomMargin;
  430. // created bulleted lists
  431. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  432. document.AddListItem(bulletedList, "Second bullet item");
  433. document.AddListItem(bulletedList, "Sub bullet item", 1);
  434. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  435. document.AddListItem(bulletedList, "Third bullet item");
  436. document.InsertList(bulletedList);
  437. // Save this document.
  438. document.Save();
  439. Console.WriteLine("\tCreated: docs\\DocumentMargins.docx\n");
  440. }
  441. }
  442. private static void DocumentsWithListsFontChange()
  443. {
  444. Console.WriteLine("\tDocumentsWithListsFontChange()");
  445. // Create a document.
  446. using (DocX document = DocX.Create(@"docs\DocumentsWithListsFontChange.docx"))
  447. {
  448. foreach ( FontFamily oneFontFamily in FontFamily.Families ) {
  449. FontFamily fontFamily = oneFontFamily;
  450. double fontSize = 15;
  451. // created numbered lists
  452. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
  453. document.AddListItem(numberedList, "First sub list item", 1);
  454. document.AddListItem(numberedList, "Second List Item.");
  455. document.AddListItem(numberedList, "Third list item.");
  456. document.AddListItem(numberedList, "Nested item.", 1);
  457. document.AddListItem(numberedList, "Second nested item.", 1);
  458. // created bulleted lists
  459. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  460. document.AddListItem(bulletedList, "Second bullet item");
  461. document.AddListItem(bulletedList, "Sub bullet item", 1);
  462. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  463. document.AddListItem(bulletedList, "Third bullet item");
  464. document.InsertList(bulletedList);
  465. document.InsertList(numberedList, fontFamily, fontSize);
  466. }
  467. // Save this document.
  468. document.Save();
  469. Console.WriteLine("\tCreated: docs\\DocumentsWithListsFontChange.docx\n");
  470. }
  471. }
  472. private static void AddList()
  473. {
  474. Console.WriteLine("\tAddList()");
  475. using (var document = DocX.Create(@"docs\Lists.docx"))
  476. {
  477. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 2);
  478. document.AddListItem(numberedList, "First sub list item", 1);
  479. document.AddListItem(numberedList, "Second List Item.");
  480. document.AddListItem(numberedList, "Third list item.");
  481. document.AddListItem(numberedList, "Nested item.", 1);
  482. document.AddListItem(numberedList, "Second nested item.", 1);
  483. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  484. document.AddListItem(bulletedList, "Second bullet item");
  485. document.AddListItem(bulletedList, "Sub bullet item", 1);
  486. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  487. document.AddListItem(bulletedList, "Third bullet item");
  488. document.InsertList(numberedList);
  489. document.InsertList(bulletedList);
  490. document.Save();
  491. Console.WriteLine("\tCreated: docs\\Lists.docx");
  492. }
  493. }
  494. private static void HeadersAndFooters()
  495. {
  496. Console.WriteLine("\tHeadersAndFooters()");
  497. // Create a new document.
  498. using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx"))
  499. {
  500. // Add Headers and Footers to this document.
  501. document.AddHeaders();
  502. document.AddFooters();
  503. // Force the first page to have a different Header and Footer.
  504. document.DifferentFirstPage = true;
  505. // Force odd & even pages to have different Headers and Footers.
  506. document.DifferentOddAndEvenPages = true;
  507. // Get the first, odd and even Headers for this document.
  508. Header header_first = document.Headers.first;
  509. Header header_odd = document.Headers.odd;
  510. Header header_even = document.Headers.even;
  511. // Get the first, odd and even Footer for this document.
  512. Footer footer_first = document.Footers.first;
  513. Footer footer_odd = document.Footers.odd;
  514. Footer footer_even = document.Footers.even;
  515. // Insert a Paragraph into the first Header.
  516. Paragraph p0 = header_first.InsertParagraph();
  517. p0.Append("Hello First Header.").Bold();
  518. // Insert a Paragraph into the odd Header.
  519. Paragraph p1 = header_odd.InsertParagraph();
  520. p1.Append("Hello Odd Header.").Bold();
  521. // Insert a Paragraph into the even Header.
  522. Paragraph p2 = header_even.InsertParagraph();
  523. p2.Append("Hello Even Header.").Bold();
  524. // Insert a Paragraph into the first Footer.
  525. Paragraph p3 = footer_first.InsertParagraph();
  526. p3.Append("Hello First Footer.").Bold();
  527. // Insert a Paragraph into the odd Footer.
  528. Paragraph p4 = footer_odd.InsertParagraph();
  529. p4.Append("Hello Odd Footer.").Bold();
  530. // Insert a Paragraph into the even Header.
  531. Paragraph p5 = footer_even.InsertParagraph();
  532. p5.Append("Hello Even Footer.").Bold();
  533. // Insert a Paragraph into the document.
  534. Paragraph p6 = document.InsertParagraph();
  535. p6.AppendLine("Hello First page.");
  536. // Create a second page to show that the first page has its own header and footer.
  537. p6.InsertPageBreakAfterSelf();
  538. // Insert a Paragraph after the page break.
  539. Paragraph p7 = document.InsertParagraph();
  540. p7.AppendLine("Hello Second page.");
  541. // Create a third page to show that even and odd pages have different headers and footers.
  542. p7.InsertPageBreakAfterSelf();
  543. // Insert a Paragraph after the page break.
  544. Paragraph p8 = document.InsertParagraph();
  545. p8.AppendLine("Hello Third page.");
  546. //Insert a next page break, which is a section break combined with a page break
  547. document.InsertSectionPageBreak();
  548. //Insert a paragraph after the "Next" page break
  549. Paragraph p9 = document.InsertParagraph();
  550. p9.Append("Next page section break.");
  551. //Insert a continuous section break
  552. document.InsertSection();
  553. //Create a paragraph in the new section
  554. var p10 = document.InsertParagraph();
  555. p10.Append("Continuous section paragraph.");
  556. // Save all changes to this document.
  557. document.Save();
  558. Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n");
  559. }// Release this document from memory.
  560. }
  561. private static void HeadersAndFootersWithImagesAndTables()
  562. {
  563. Console.WriteLine("\tHeadersAndFootersWithImagesAndTables()");
  564. // Create a new document.
  565. using (DocX document = DocX.Create(@"docs\HeadersAndFootersWithImagesAndTables.docx"))
  566. {
  567. // Add a template logo image to this document.
  568. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  569. rd.Up(2);
  570. Image logo = document.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  571. // Add Headers and Footers to this document.
  572. document.AddHeaders();
  573. document.AddFooters();
  574. // Force the first page to have a different Header and Footer.
  575. document.DifferentFirstPage = true;
  576. // Force odd & even pages to have different Headers and Footers.
  577. document.DifferentOddAndEvenPages = true;
  578. // Get the first, odd and even Headers for this document.
  579. Header header_first = document.Headers.first;
  580. Header header_odd = document.Headers.odd;
  581. Header header_even = document.Headers.even;
  582. // Get the first, odd and even Footer for this document.
  583. Footer footer_first = document.Footers.first;
  584. Footer footer_odd = document.Footers.odd;
  585. Footer footer_even = document.Footers.even;
  586. // Insert a Paragraph into the first Header.
  587. Paragraph p0 = header_first.InsertParagraph();
  588. p0.Append("Hello First Header.").Bold();
  589. // Insert a Paragraph into the odd Header.
  590. Paragraph p1 = header_odd.InsertParagraph();
  591. p1.Append("Hello Odd Header.").Bold();
  592. // Insert a Paragraph into the even Header.
  593. Paragraph p2 = header_even.InsertParagraph();
  594. p2.Append("Hello Even Header.").Bold();
  595. // Insert a Paragraph into the first Footer.
  596. Paragraph p3 = footer_first.InsertParagraph();
  597. p3.Append("Hello First Footer.").Bold();
  598. // Insert a Paragraph into the odd Footer.
  599. Paragraph p4 = footer_odd.InsertParagraph();
  600. p4.Append("Hello Odd Footer.").Bold();
  601. // Insert a Paragraph into the even Header.
  602. Paragraph p5 = footer_even.InsertParagraph();
  603. p5.Append("Hello Even Footer.").Bold();
  604. // Insert a Paragraph into the document.
  605. Paragraph p6 = document.InsertParagraph();
  606. p6.AppendLine("Hello First page.");
  607. // Create a second page to show that the first page has its own header and footer.
  608. p6.InsertPageBreakAfterSelf();
  609. // Insert a Paragraph after the page break.
  610. Paragraph p7 = document.InsertParagraph();
  611. p7.AppendLine("Hello Second page.");
  612. // Create a third page to show that even and odd pages have different headers and footers.
  613. p7.InsertPageBreakAfterSelf();
  614. // Insert a Paragraph after the page break.
  615. Paragraph p8 = document.InsertParagraph();
  616. p8.AppendLine("Hello Third page.");
  617. //Insert a next page break, which is a section break combined with a page break
  618. document.InsertSectionPageBreak();
  619. //Insert a paragraph after the "Next" page break
  620. Paragraph p9 = document.InsertParagraph();
  621. p9.Append("Next page section break.");
  622. //Insert a continuous section break
  623. document.InsertSection();
  624. //Create a paragraph in the new section
  625. var p10 = document.InsertParagraph();
  626. p10.Append("Continuous section paragraph.");
  627. // Inserting logo into footer and header into Tables
  628. #region Company Logo in Header in Table
  629. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  630. Table header_first_table = header_first.InsertTable(1, 2);
  631. header_first_table.Design = TableDesign.TableGrid;
  632. header_first_table.AutoFit = AutoFit.Window;
  633. // Get the upper right Paragraph in the layout_table.
  634. Paragraph upperRightParagraph = header_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  635. // Insert this template logo into the upper right Paragraph of Table.
  636. upperRightParagraph.AppendPicture(logo.CreatePicture());
  637. upperRightParagraph.Alignment = Alignment.right;
  638. // Get the upper left Paragraph in the layout_table.
  639. Paragraph upperLeftParagraphFirstTable = header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  640. upperLeftParagraphFirstTable.Append("Company Name - DocX Corporation");
  641. #endregion
  642. #region Company Logo in Header in Invisible Table
  643. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  644. Table header_second_table = header_odd.InsertTable(1, 2);
  645. header_second_table.Design = TableDesign.None;
  646. header_second_table.AutoFit = AutoFit.Window;
  647. // Get the upper right Paragraph in the layout_table.
  648. Paragraph upperRightParagraphSecondTable = header_second_table.Rows[0].Cells[1].Paragraphs[0];
  649. // Insert this template logo into the upper right Paragraph of Table.
  650. upperRightParagraphSecondTable.AppendPicture(logo.CreatePicture());
  651. upperRightParagraphSecondTable.Alignment = Alignment.right;
  652. // Get the upper left Paragraph in the layout_table.
  653. Paragraph upperLeftParagraphSecondTable = header_second_table.Rows[0].Cells[0].Paragraphs[0];
  654. upperLeftParagraphSecondTable.Append("Company Name - DocX Corporation");
  655. #endregion
  656. #region Company Logo in Footer in Table
  657. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  658. Table footer_first_table = footer_first.InsertTable(1, 2);
  659. footer_first_table.Design = TableDesign.TableGrid;
  660. footer_first_table.AutoFit = AutoFit.Window;
  661. // Get the upper right Paragraph in the layout_table.
  662. Paragraph upperRightParagraphFooterParagraph = footer_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  663. // Insert this template logo into the upper right Paragraph of Table.
  664. upperRightParagraphFooterParagraph.AppendPicture(logo.CreatePicture());
  665. upperRightParagraphFooterParagraph.Alignment = Alignment.right;
  666. // Get the upper left Paragraph in the layout_table.
  667. Paragraph upperLeftParagraphFirstTableFooter = footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  668. upperLeftParagraphFirstTableFooter.Append("Company Name - DocX Corporation");
  669. #endregion
  670. #region Company Logo in Header in Invisible Table
  671. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  672. Table footer_second_table = footer_odd.InsertTable(1, 2);
  673. footer_second_table.Design = TableDesign.None;
  674. footer_second_table.AutoFit = AutoFit.Window;
  675. // Get the upper right Paragraph in the layout_table.
  676. Paragraph upperRightParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[1].Paragraphs[0];
  677. // Insert this template logo into the upper right Paragraph of Table.
  678. upperRightParagraphSecondTableFooter.AppendPicture(logo.CreatePicture());
  679. upperRightParagraphSecondTableFooter.Alignment = Alignment.right;
  680. // Get the upper left Paragraph in the layout_table.
  681. Paragraph upperLeftParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[0].Paragraphs[0];
  682. upperLeftParagraphSecondTableFooter.Append("Company Name - DocX Corporation");
  683. #endregion
  684. // Save all changes to this document.
  685. document.Save();
  686. Console.WriteLine("\tCreated: docs\\HeadersAndFootersWithImagesAndTables.docx\n");
  687. }// Release this document from memory.
  688. }
  689. private static void HeadersAndFootersWithImagesAndTablesUsingInsertPicture()
  690. {
  691. Console.WriteLine("\tHeadersAndFootersWithImagesAndTablesUsingInsertPicture()");
  692. // Create a new document.
  693. using (DocX document = DocX.Create(@"docs\HeadersAndFootersWithImagesAndTablesUsingInsertPicture.docx"))
  694. {
  695. // Add a template logo image to this document.
  696. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  697. rd.Up(2);
  698. Image logo = document.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  699. // Add Headers and Footers to this document.
  700. document.AddHeaders();
  701. document.AddFooters();
  702. // Force the first page to have a different Header and Footer.
  703. document.DifferentFirstPage = true;
  704. // Force odd & even pages to have different Headers and Footers.
  705. document.DifferentOddAndEvenPages = true;
  706. // Get the first, odd and even Headers for this document.
  707. Header header_first = document.Headers.first;
  708. Header header_odd = document.Headers.odd;
  709. Header header_even = document.Headers.even;
  710. // Get the first, odd and even Footer for this document.
  711. Footer footer_first = document.Footers.first;
  712. Footer footer_odd = document.Footers.odd;
  713. Footer footer_even = document.Footers.even;
  714. // Insert a Paragraph into the first Header.
  715. Paragraph p0 = header_first.InsertParagraph();
  716. p0.Append("Hello First Header.").Bold();
  717. // Insert a Paragraph into the odd Header.
  718. Paragraph p1 = header_odd.InsertParagraph();
  719. p1.Append("Hello Odd Header.").Bold();
  720. // Insert a Paragraph into the even Header.
  721. Paragraph p2 = header_even.InsertParagraph();
  722. p2.Append("Hello Even Header.").Bold();
  723. // Insert a Paragraph into the first Footer.
  724. Paragraph p3 = footer_first.InsertParagraph();
  725. p3.Append("Hello First Footer.").Bold();
  726. // Insert a Paragraph into the odd Footer.
  727. Paragraph p4 = footer_odd.InsertParagraph();
  728. p4.Append("Hello Odd Footer.").Bold();
  729. // Insert a Paragraph into the even Header.
  730. Paragraph p5 = footer_even.InsertParagraph();
  731. p5.Append("Hello Even Footer.").Bold();
  732. // Insert a Paragraph into the document.
  733. Paragraph p6 = document.InsertParagraph();
  734. p6.AppendLine("Hello First page.");
  735. // Create a second page to show that the first page has its own header and footer.
  736. p6.InsertPageBreakAfterSelf();
  737. // Insert a Paragraph after the page break.
  738. Paragraph p7 = document.InsertParagraph();
  739. p7.AppendLine("Hello Second page.");
  740. // Create a third page to show that even and odd pages have different headers and footers.
  741. p7.InsertPageBreakAfterSelf();
  742. // Insert a Paragraph after the page break.
  743. Paragraph p8 = document.InsertParagraph();
  744. p8.AppendLine("Hello Third page.");
  745. //Insert a next page break, which is a section break combined with a page break
  746. document.InsertSectionPageBreak();
  747. //Insert a paragraph after the "Next" page break
  748. Paragraph p9 = document.InsertParagraph();
  749. p9.Append("Next page section break.");
  750. //Insert a continuous section break
  751. document.InsertSection();
  752. //Create a paragraph in the new section
  753. var p10 = document.InsertParagraph();
  754. p10.Append("Continuous section paragraph.");
  755. // Inserting logo into footer and header into Tables
  756. #region Company Logo in Header in Table
  757. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  758. Table header_first_table = header_first.InsertTable(1, 2);
  759. header_first_table.Design = TableDesign.TableGrid;
  760. header_first_table.AutoFit = AutoFit.Window;
  761. // Get the upper right Paragraph in the layout_table.
  762. Paragraph upperRightParagraph = header_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  763. // Insert this template logo into the upper right Paragraph of Table.
  764. upperRightParagraph.InsertPicture(logo.CreatePicture());
  765. upperRightParagraph.Alignment = Alignment.right;
  766. // Get the upper left Paragraph in the layout_table.
  767. Paragraph upperLeftParagraphFirstTable = header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  768. upperLeftParagraphFirstTable.Append("Company Name - DocX Corporation");
  769. #endregion
  770. #region Company Logo in Header in Invisible Table
  771. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  772. Table header_second_table = header_odd.InsertTable(1, 2);
  773. header_second_table.Design = TableDesign.None;
  774. header_second_table.AutoFit = AutoFit.Window;
  775. // Get the upper right Paragraph in the layout_table.
  776. Paragraph upperRightParagraphSecondTable = header_second_table.Rows[0].Cells[1].Paragraphs[0];
  777. // Insert this template logo into the upper right Paragraph of Table.
  778. upperRightParagraphSecondTable.InsertPicture(logo.CreatePicture());
  779. upperRightParagraphSecondTable.Alignment = Alignment.right;
  780. // Get the upper left Paragraph in the layout_table.
  781. Paragraph upperLeftParagraphSecondTable = header_second_table.Rows[0].Cells[0].Paragraphs[0];
  782. upperLeftParagraphSecondTable.Append("Company Name - DocX Corporation");
  783. #endregion
  784. #region Company Logo in Footer in Table
  785. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  786. Table footer_first_table = footer_first.InsertTable(1, 2);
  787. footer_first_table.Design = TableDesign.TableGrid;
  788. footer_first_table.AutoFit = AutoFit.Window;
  789. // Get the upper right Paragraph in the layout_table.
  790. Paragraph upperRightParagraphFooterParagraph = footer_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  791. // Insert this template logo into the upper right Paragraph of Table.
  792. upperRightParagraphFooterParagraph.InsertPicture(logo.CreatePicture());
  793. upperRightParagraphFooterParagraph.Alignment = Alignment.right;
  794. // Get the upper left Paragraph in the layout_table.
  795. Paragraph upperLeftParagraphFirstTableFooter = footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
  796. upperLeftParagraphFirstTableFooter.Append("Company Name - DocX Corporation");
  797. #endregion
  798. #region Company Logo in Header in Invisible Table
  799. // Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
  800. Table footer_second_table = footer_odd.InsertTable(1, 2);
  801. footer_second_table.Design = TableDesign.None;
  802. footer_second_table.AutoFit = AutoFit.Window;
  803. // Get the upper right Paragraph in the layout_table.
  804. Paragraph upperRightParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[1].Paragraphs[0];
  805. // Insert this template logo into the upper right Paragraph of Table.
  806. upperRightParagraphSecondTableFooter.InsertPicture(logo.CreatePicture());
  807. upperRightParagraphSecondTableFooter.Alignment = Alignment.right;
  808. // Get the upper left Paragraph in the layout_table.
  809. Paragraph upperLeftParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[0].Paragraphs[0];
  810. upperLeftParagraphSecondTableFooter.Append("Company Name - DocX Corporation");
  811. #endregion
  812. // Save all changes to this document.
  813. document.Save();
  814. Console.WriteLine("\tCreated: docs\\HeadersAndFootersWithImagesAndTablesUsingInsertPicture.docx\n");
  815. }// Release this document from memory.
  816. }
  817. private static void CreateInvoice()
  818. {
  819. Console.WriteLine("\tCreateInvoice()");
  820. DocX g_document;
  821. try
  822. {
  823. // Store a global reference to the loaded document.
  824. g_document = DocX.Load(@"docs\InvoiceTemplate.docx");
  825. /*
  826. * The template 'InvoiceTemplate.docx' does exist,
  827. * so lets use it to create an invoice for a factitious company
  828. * called "The Happy Builder" and store a global reference it.
  829. */
  830. g_document = CreateInvoiceFromTemplate(DocX.Load(@"docs\InvoiceTemplate.docx"));
  831. // Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
  832. g_document.SaveAs(@"docs\Invoice_The_Happy_Builder.docx");
  833. Console.WriteLine("\tCreated: docs\\Invoice_The_Happy_Builder.docx\n");
  834. }
  835. // The template 'InvoiceTemplate.docx' does not exist, so create it.
  836. catch (FileNotFoundException)
  837. {
  838. // Create and store a global reference to the template 'InvoiceTemplate.docx'.
  839. g_document = CreateInvoiceTemplate();
  840. // Save the template 'InvoiceTemplate.docx'.
  841. g_document.Save();
  842. Console.WriteLine("\tCreated: docs\\InvoiceTemplate.docx");
  843. // The template exists now so re-call CreateInvoice().
  844. CreateInvoice();
  845. }
  846. }
  847. private static void CreateTableWithTextDirection()
  848. {
  849. Console.WriteLine("\tCreateTableWithTextDirection()");
  850. // Create a document.
  851. using (DocX document = DocX.Create(@"docs\\CeateTableWithTextDirection.docx"))
  852. {
  853. // Add a Table to this document.
  854. Table t = document.AddTable(2, 3);
  855. // Specify some properties for this Table.
  856. t.Alignment = Alignment.center;
  857. t.Design = TableDesign.MediumGrid1Accent2;
  858. // Add content to this Table.
  859. t.Rows[0].Cells[0].Paragraphs.First().Append("A");
  860. t.Rows[0].Cells[0].TextDirection = TextDirection.btLr;
  861. t.Rows[0].Cells[1].Paragraphs.First().Append("B");
  862. t.Rows[0].Cells[1].TextDirection = TextDirection.btLr;
  863. t.Rows[0].Cells[2].Paragraphs.First().Append("C");
  864. t.Rows[0].Cells[2].TextDirection = TextDirection.btLr;
  865. t.Rows[1].Cells[0].Paragraphs.First().Append("D");
  866. t.Rows[1].Cells[1].Paragraphs.First().Append("E");
  867. t.Rows[1].Cells[2].Paragraphs.First().Append("F");
  868. // Insert the Table into the document.
  869. document.InsertTable(t);
  870. document.Save();
  871. }// Release this document from memory.
  872. Console.WriteLine("\tCreated: docs\\CreateTableWithTextDirection.docx");
  873. }
  874. // Create an invoice for a factitious company called "The Happy Builder".
  875. private static DocX CreateInvoiceFromTemplate(DocX template)
  876. {
  877. #region Logo
  878. // A quick glance at the template shows us that the logo Paragraph is in row zero cell 1.
  879. Paragraph logo_paragraph = template.Tables[0].Rows[0].Cells[1].Paragraphs[0];
  880. // Remove the template Picture that is in this Paragraph.
  881. logo_paragraph.Pictures[0].Remove();
  882. // Add the Happy Builders logo to this document.
  883. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  884. rd.Up(2);
  885. Image logo = template.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
  886. // Insert the Happy Builders logo into this Paragraph.
  887. logo_paragraph.InsertPicture(logo.CreatePicture());
  888. #endregion
  889. #region Set CustomProperty values
  890. // Set the value of the custom property 'company_name'.
  891. template.AddCustomProperty(new CustomProperty("company_name", "The Happy Builder"));
  892. // Set the value of the custom property 'company_slogan'.
  893. template.AddCustomProperty(new CustomProperty("company_slogan", "No job too small"));
  894. // Set the value of the custom properties 'hired_company_address_line_one', 'hired_company_address_line_two' and 'hired_company_address_line_three'.
  895. template.AddCustomProperty(new CustomProperty("hired_company_address_line_one", "The Crooked House,"));
  896. template.AddCustomProperty(new CustomProperty("hired_company_address_line_two", "Dublin,"));
  897. template.AddCustomProperty(new CustomProperty("hired_company_address_line_three", "12345"));
  898. // Set the value of the custom property 'invoice_date'.
  899. template.AddCustomProperty(new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d")));
  900. // Set the value of the custom property 'invoice_number'.
  901. template.AddCustomProperty(new CustomProperty("invoice_number", 1));
  902. // Set the value of the custom property 'hired_company_details_line_one' and 'hired_company_details_line_two'.
  903. template.AddCustomProperty(new CustomProperty("hired_company_details_line_one", "Business Street, Dublin, 12345"));
  904. template.AddCustomProperty(new CustomProperty("hired_company_details_line_two", "Phone: 012-345-6789, Fax: 012-345-6789, e-mail: support@thehappybuilder.com"));
  905. #endregion
  906. /*
  907. * InvoiceTemplate.docx contains a blank Table,
  908. * we want to replace this with a new Table that
  909. * contains all of our invoice data.
  910. */
  911. Table t = template.Tables[1];
  912. Table invoice_table = CreateAndInsertInvoiceTableAfter(t, ref template);
  913. t.Remove();
  914. // Return the template now that it has been modified to hold all of our custom data.
  915. return template;
  916. }
  917. // Create an invoice template.
  918. private static DocX CreateInvoiceTemplate()
  919. {
  920. // Create a new document.
  921. DocX document = DocX.Create(@"docs\InvoiceTemplate.docx");
  922. // Create a table for layout purposes (This table will be invisible).
  923. Table layout_table = document.InsertTable(2, 2);
  924. layout_table.Design = TableDesign.TableNormal;
  925. layout_table.AutoFit = AutoFit.Window;
  926. // Dark formatting
  927. Formatting dark_formatting = new Formatting();
  928. dark_formatting.Bold = true;
  929. dark_formatting.Size = 12;
  930. dark_formatting.FontColor = Color.FromArgb(31, 73, 125);
  931. // Light formatting
  932. Formatting light_formatting = new Formatting();
  933. light_formatting.Italic = true;
  934. light_formatting.Size = 11;
  935. light_formatting.FontColor = Color.FromArgb(79, 129, 189);
  936. #region Company Name
  937. // Get the upper left Paragraph in the layout_table.
  938. Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0];
  939. // Create a custom property called company_name
  940. CustomProperty company_name = new CustomProperty("company_name", "Company Name");
  941. // Insert a field of type doc property (This will display the custom property 'company_name')
  942. layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting);
  943. // Force the next text insert to be on a new line.
  944. upper_left_paragraph.InsertText("\n", false);
  945. #endregion
  946. #region Company Slogan
  947. // Create a custom property called company_slogan
  948. CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here.");
  949. // Insert a field of type doc property (This will display the custom property 'company_slogan')
  950. upper_left_paragraph.InsertDocProperty(company_slogan, f: light_formatting);
  951. #endregion
  952. #region Company Logo
  953. // Get the upper right Paragraph in the layout_table.
  954. Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0];
  955. // Add a template logo image to this document.
  956. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  957. rd.Up(2);
  958. Image logo = document.AddImage(rd.Path + @"\images\logo_template.png");
  959. // Insert this template logo into the upper right Paragraph.
  960. upper_right_paragraph.InsertPicture(logo.CreatePicture());
  961. upper_right_paragraph.Alignment = Alignment.right;
  962. #endregion
  963. // Custom properties cannot contain newlines, so the company address must be split into 3 custom properties.
  964. #region Hired Company Address
  965. // Create a custom property called company_address_line_one
  966. CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,");
  967. // Get the lower left Paragraph in the layout_table.
  968. Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0];
  969. lower_left_paragraph.InsertText("TO:\n", false, dark_formatting);
  970. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one')
  971. lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, f: light_formatting);
  972. // Force the next text insert to be on a new line.
  973. lower_left_paragraph.InsertText("\n", false);
  974. // Create a custom property called company_address_line_two
  975. CustomProperty hired_company_address_line_two = new CustomProperty("hired_company_address_line_two", "City,");
  976. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two')
  977. lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f: light_formatting);
  978. // Force the next text insert to be on a new line.
  979. lower_left_paragraph.InsertText("\n", false);
  980. // Create a custom property called company_address_line_two
  981. CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code");
  982. // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three')
  983. lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f: light_formatting);
  984. #endregion
  985. #region Date & Invoice number
  986. // Get the lower right Paragraph from the layout table.
  987. Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0];
  988. CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"));
  989. lower_right_paragraph.InsertText("Date: ", false, dark_formatting);
  990. lower_right_paragraph.InsertDocProperty(invoice_date, f: light_formatting);
  991. CustomProperty invoice_number = new CustomProperty("invoice_number", 1);
  992. lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting);
  993. lower_right_paragraph.InsertText("#", false, light_formatting);
  994. lower_right_paragraph.InsertDocProperty(invoice_number, f: light_formatting);
  995. lower_right_paragraph.Alignment = Alignment.right;
  996. #endregion
  997. // Insert an empty Paragraph between two Tables, so that they do not touch.
  998. document.InsertParagraph(string.Empty, false);
  999. // This table will hold all of the invoice data.
  1000. Table invoice_table = document.InsertTable(4, 4);
  1001. invoice_table.Design = TableDesign.LightShadingAccent1;
  1002. invoice_table.Alignment = Alignment.center;
  1003. // A nice thank you Paragraph.
  1004. Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting);
  1005. thankyou.Alignment = Alignment.center;
  1006. #region Hired company details
  1007. CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code");
  1008. 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");
  1009. Paragraph companyDetails = document.InsertParagraph(string.Empty, false);
  1010. companyDetails.InsertDocProperty(hired_company_details_line_one, f: light_formatting);
  1011. companyDetails.InsertText("\n", false);
  1012. companyDetails.InsertDocProperty(hired_company_details_line_two, f: light_formatting);
  1013. companyDetails.Alignment = Alignment.center;
  1014. #endregion
  1015. // Return the document now that it has been created.
  1016. return document;
  1017. }
  1018. private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
  1019. {
  1020. // Grab data from somewhere (Most likely a database)
  1021. DataTable data = GetDataFromDatabase();
  1022. /*
  1023. * The trick to replacing one Table with another,
  1024. * is to insert the new Table after the old one,
  1025. * and then remove the old one.
  1026. */
  1027. Table invoice_table = t.InsertTableAfterSelf(data.Rows.Count + 1, data.Columns.Count);
  1028. invoice_table.Design = TableDesign.LightShadingAccent1;
  1029. #region Table title
  1030. Formatting table_title = new Formatting();
  1031. table_title.Bold = true;
  1032. invoice_table.Rows[0].Cells[0].Paragraphs[0].InsertText("Description", false, table_title);
  1033. invoice_table.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
  1034. invoice_table.Rows[0].Cells[1].Paragraphs[0].InsertText("Hours", false, table_title);
  1035. invoice_table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
  1036. invoice_table.Rows[0].Cells[2].Paragraphs[0].InsertText("Rate", false, table_title);
  1037. invoice_table.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
  1038. invoice_table.Rows[0].Cells[3].Paragraphs[0].InsertText("Amount", false, table_title);
  1039. invoice_table.Rows[0].Cells[3].Paragraphs[0].Alignment = Alignment.center;
  1040. #endregion
  1041. // Loop through the rows in the Table and insert data from the data source.
  1042. for (int row = 1; row < invoice_table.RowCount; row++)
  1043. {
  1044. for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
  1045. {
  1046. Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
  1047. cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
  1048. }
  1049. }
  1050. // We want to fill in the total by suming the values from the amount column.
  1051. Row total = invoice_table.InsertRow();
  1052. total.Cells[0].Paragraphs[0].InsertText("Total:", false);
  1053. Paragraph total_paragraph = total.Cells[invoice_table.ColumnCount - 1].Paragraphs[0];
  1054. /*
  1055. * Lots of people are scared of LINQ,
  1056. * so I will walk you through this line by line.
  1057. *
  1058. * invoice_table.Rows is an IEnumerable<Row> (i.e a collection of rows), with LINQ you can query collections.
  1059. * .Where(condition) is a filter that you want to apply to the items of this collection.
  1060. * My condition is that the index of the row must be greater than 0 and less than RowCount.
  1061. * .Select(something) lets you select something from each item in the filtered collection.
  1062. * I am selecting the Text value from each row, for example €100, then I am remove the €,
  1063. * and then I am parsing the remaining string as a double. This will return a collection of doubles,
  1064. * the final thing I do is call .Sum() on this collection which return one double the sum of all the doubles,
  1065. * this is the total.
  1066. */
  1067. double totalCost =
  1068. (
  1069. invoice_table.Rows
  1070. .Where((row, index) => index > 0 && index < invoice_table.RowCount - 1)
  1071. .Select(row => double.Parse(row.Cells[row.Cells.Count() - 1].Paragraphs[0].Text.Remove(0, 1)))
  1072. ).Sum();
  1073. // Insert the total calculated above using LINQ into the total Paragraph.
  1074. total_paragraph.InsertText(string.Format("€{0}", totalCost), false);
  1075. // Let the tables columns expand to fit its contents.
  1076. invoice_table.AutoFit = AutoFit.Contents;
  1077. // Center the Table
  1078. invoice_table.Alignment = Alignment.center;
  1079. // Return the invloce table now that it has been created.
  1080. return invoice_table;
  1081. }
  1082. // You need to rewrite this function to grab data from your data source.
  1083. private static DataTable GetDataFromDatabase()
  1084. {
  1085. DataTable table = new DataTable();
  1086. table.Columns.AddRange(new DataColumn[] { new DataColumn("Description"), new DataColumn("Hours"), new DataColumn("Rate"), new DataColumn("Amount") });
  1087. table.Rows.Add
  1088. (
  1089. "Install wooden doors (Kitchen, Sitting room, Dining room & Bedrooms)",
  1090. "5",
  1091. "€25",
  1092. string.Format("€{0}", 5 * 25)
  1093. );
  1094. table.Rows.Add
  1095. (
  1096. "Fit stairs",
  1097. "20",
  1098. "€30",
  1099. string.Format("€{0}", 20 * 30)
  1100. );
  1101. table.Rows.Add
  1102. (
  1103. "Replace Sitting room window",
  1104. "6",
  1105. "€50",
  1106. string.Format("€{0}", 6 * 50)
  1107. );
  1108. table.Rows.Add
  1109. (
  1110. "Build garden shed",
  1111. "10",
  1112. "€10",
  1113. string.Format("€{0}", 10 * 10)
  1114. );
  1115. table.Rows.Add
  1116. (
  1117. "Fit new lock on back door",
  1118. "0.5",
  1119. "€30",
  1120. string.Format("€{0}", 0.5 * 30)
  1121. );
  1122. table.Rows.Add
  1123. (
  1124. "Tile Kitchen floor",
  1125. "24",
  1126. "€25",
  1127. string.Format("€{0}", 24 * 25)
  1128. );
  1129. return table;
  1130. }
  1131. /// <summary>
  1132. /// Creates a simple document with the text Hello World.
  1133. /// </summary>
  1134. static void HelloWorld()
  1135. {
  1136. Console.WriteLine("\tHelloWorld()");
  1137. // Create a new document.
  1138. using (DocX document = DocX.Create(@"docs\Hello World.docx"))
  1139. {
  1140. // Insert a Paragraph into this document.
  1141. Paragraph p = document.InsertParagraph();
  1142. // Append some text and add formatting.
  1143. p.Append("Hello World!^011Hello World!")
  1144. .Font(new FontFamily("Times New Roman"))
  1145. .FontSize(32)
  1146. .Color(Color.Blue)
  1147. .Bold();
  1148. // Save this document to disk.
  1149. document.Save();
  1150. Console.WriteLine("\tCreated: docs\\Hello World.docx\n");
  1151. }
  1152. }
  1153. /// <summary>
  1154. /// Loads a document 'Input.docx' and writes the text 'Hello World' into the first imbedded Image.
  1155. /// This code creates the file 'Output.docx'.
  1156. /// </summary>
  1157. static void ProgrammaticallyManipulateImbeddedImage()
  1158. {
  1159. Console.WriteLine("\tProgrammaticallyManipulateImbeddedImage()");
  1160. const string str = "Hello World";
  1161. // Open the document Input.docx.
  1162. using (DocX document = DocX.Load(@"Input.docx"))
  1163. {
  1164. // Make sure this document has at least one Image.
  1165. if (document.Images.Count() > 0)
  1166. {
  1167. Image img = document.Images[0];
  1168. // Write "Hello World" into this Image.
  1169. Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
  1170. /*
  1171. * Get the Graphics object for this Bitmap.
  1172. * The Graphics object provides functions for drawing.
  1173. */
  1174. Graphics g = Graphics.FromImage(b);
  1175. // Draw the string "Hello World".
  1176. g.DrawString
  1177. (
  1178. str,
  1179. new Font("Tahoma", 20),
  1180. Brushes.Blue,
  1181. new PointF(0, 0)
  1182. );
  1183. // Save this Bitmap back into the document using a Create\Write stream.
  1184. b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
  1185. }
  1186. else
  1187. Console.WriteLine("The provided document contains no Images.");
  1188. // Save this document as Output.docx.
  1189. document.SaveAs(@"docs\Output.docx");
  1190. Console.WriteLine("\tCreated: docs\\Output.docx\n");
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// For each of the documents in the folder 'docs\',
  1195. /// Replace the string a with the string b,
  1196. /// Do this in Parrallel accross many CPU cores.
  1197. /// </summary>
  1198. static void ReplaceTextParallel()
  1199. {
  1200. Console.WriteLine("\tReplaceTextParallel()\n");
  1201. const string a = "apple";
  1202. const string b = "pear";
  1203. // Directory containing many .docx documents.
  1204. DirectoryInfo di = new DirectoryInfo(@"docs\");
  1205. // Loop through each document in this specified direction.
  1206. Parallel.ForEach
  1207. (
  1208. di.GetFiles(),
  1209. currentFile =>
  1210. {
  1211. // Load the document.
  1212. using (DocX document = DocX.Load(currentFile.FullName))
  1213. {
  1214. // Replace text in this document.
  1215. document.ReplaceText(a, b);
  1216. // Save changes made to this document.
  1217. document.Save();
  1218. } // Release this document from memory.
  1219. }
  1220. );
  1221. Console.WriteLine("\tCreated: None\n");
  1222. }
  1223. static void AddToc()
  1224. {
  1225. Console.WriteLine("\tAddToc()");
  1226. using (var document = DocX.Create(@"docs\Toc.docx"))
  1227. {
  1228. document.InsertTableOfContents("I can haz table of contentz", TableOfContentsSwitches.O | TableOfContentsSwitches.U | TableOfContentsSwitches.Z | TableOfContentsSwitches.H, "Heading2");
  1229. var h1 = document.InsertParagraph("Heading 1");
  1230. h1.StyleName = "Heading1";
  1231. document.InsertParagraph("Some very interesting content here");
  1232. var h2 = document.InsertParagraph("Heading 2");
  1233. document.InsertSectionPageBreak();
  1234. h2.StyleName = "Heading1";
  1235. document.InsertParagraph("Some very interesting content here as well");
  1236. var h3 = document.InsertParagraph("Heading 2.1");
  1237. h3.StyleName = "Heading2";
  1238. document.InsertParagraph("Not so very interesting....");
  1239. document.Save();
  1240. }
  1241. }
  1242. static void AddTocByReference()
  1243. {
  1244. Console.WriteLine("\tAddTocByReference()");
  1245. using (var document = DocX.Create(@"docs\TocByReference.docx"))
  1246. {
  1247. var h1 = document.InsertParagraph("Heading 1");
  1248. h1.StyleName = "Heading1";
  1249. document.InsertParagraph("Some very interesting content here");
  1250. var h2 = document.InsertParagraph("Heading 2");
  1251. document.InsertSectionPageBreak();
  1252. h2.StyleName = "Heading1";
  1253. document.InsertParagraph("Some very interesting content here as well");
  1254. var h3 = document.InsertParagraph("Heading 2.1");
  1255. h3.StyleName = "Heading2";
  1256. document.InsertParagraph("Not so very interesting....");
  1257. document.InsertTableOfContents(h2, "I can haz table of contentz", TableOfContentsSwitches.O | TableOfContentsSwitches.U | TableOfContentsSwitches.Z | TableOfContentsSwitches.H, "Heading2");
  1258. document.Save();
  1259. }
  1260. }
  1261. static void HelloWorldKeepWithNext()
  1262. {
  1263. // Create a Paragraph that will stay on the same page as the paragraph that comes next
  1264. Console.WriteLine("\tHelloWorldKeepWithNext()");
  1265. // Create a new document.
  1266. using (DocX document = DocX.Create("docs\\HelloWorldKeepWithNext.docx"))
  1267. {
  1268. // Create a new Paragraph with the text "Hello World".
  1269. Paragraph p = document.InsertParagraph("Hello World.");
  1270. p.KeepWithNext();
  1271. document.InsertParagraph("Previous paragraph will appear on the same page as this paragraph");
  1272. // Save all changes made to this document.
  1273. document.Save();
  1274. Console.WriteLine("\tCreated: docs\\HelloWorldKeepWithNext.docx\n");
  1275. }
  1276. }
  1277. static void HelloWorldKeepLinesTogether()
  1278. {
  1279. // Create a Paragraph that will stay on the same page as the paragraph that comes next
  1280. Console.WriteLine("\tHelloWorldKeepLinesTogether()");
  1281. // Create a new document.
  1282. using (DocX document = DocX.Create("docs\\HelloWorldKeepLinesTogether.docx"))
  1283. {
  1284. // Create a new Paragraph with the text "Hello World".
  1285. Paragraph p = document.InsertParagraph("All lines of this paragraph will appear on the same page...\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6...");
  1286. p.KeepLinesTogether();
  1287. // Save all changes made to this document.
  1288. document.Save();
  1289. Console.WriteLine("\tCreated: docs\\HelloWorldKeepLinesTogether.docx\n");
  1290. }
  1291. }
  1292. }
  1293. }