You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Program.cs 87KB

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