Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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