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

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