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

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