Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Program.cs 83KB

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