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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  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.Xml.Linq;
  9. using System.Threading.Tasks;
  10. using Novacode;
  11. using Image = Novacode.Image;
  12. namespace Examples
  13. {
  14. class Program
  15. {
  16. private static Border BlankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White);
  17. static void Main(string[] args)
  18. {
  19. Setup();
  20. HelloWorld();
  21. //Contents();
  22. AddList();
  23. Console.ReadLine();
  24. // Examples();
  25. }
  26. static void Examples()
  27. {
  28. // Setup();
  29. // Easy
  30. Console.WriteLine("\nRunning Easy Examples");
  31. HelloWorld();
  32. HelloWorldKeepLinesTogether();
  33. HelloWorldKeepWithNext();
  34. HelloWorldAdvancedFormatting();
  35. HelloWorldProtectedDocument();
  36. HelloWorldAddPictureToWord();
  37. RightToLeft();
  38. Indentation();
  39. HeadersAndFooters();
  40. HyperlinksImagesTables();
  41. AddList();
  42. Equations();
  43. Bookmarks();
  44. BookmarksReplaceTextOfBookmarkKeepingFormat();
  45. BarChart();
  46. PieChart();
  47. LineChart();
  48. Chart3D();
  49. DocumentMargins();
  50. CreateTableWithTextDirection();
  51. AddToc();
  52. AddTocByReference();
  53. // Intermediate
  54. Console.WriteLine("\nRunning Intermediate Examples");
  55. CreateInvoice();
  56. HyperlinksImagesTablesWithLists();
  57. HeadersAndFootersWithImagesAndTables();
  58. HeadersAndFootersWithImagesAndTablesUsingInsertPicture();
  59. DocumentsWithListsFontChange();
  60. DocumentHeading();
  61. LargeTable();
  62. TableWithSpecifiedWidths();
  63. // Advanced
  64. Console.WriteLine("\nRunning Advanced Examples");
  65. ProgrammaticallyManipulateImbeddedImage();
  66. ReplaceTextParallel();
  67. Console.WriteLine("\nPress any key to exit.");
  68. Console.ReadKey();
  69. }
  70. private static void Setup()
  71. {
  72. if (!Directory.Exists("docs"))
  73. {
  74. Directory.CreateDirectory("docs");
  75. }
  76. }
  77. #region Charts
  78. private class ChartData
  79. {
  80. public String Mounth { get; set; }
  81. public Double Money { get; set; }
  82. public static List<ChartData> CreateCompanyList1()
  83. {
  84. List<ChartData> company1 = new List<ChartData>();
  85. company1.Add(new ChartData() { Mounth = "January", Money = 100 });
  86. company1.Add(new ChartData() { Mounth = "February", Money = 120 });
  87. company1.Add(new ChartData() { Mounth = "March", Money = 140 });
  88. return company1;
  89. }
  90. public static List<ChartData> CreateCompanyList2()
  91. {
  92. List<ChartData> company2 = new List<ChartData>();
  93. company2.Add(new ChartData() { Mounth = "January", Money = 80 });
  94. company2.Add(new ChartData() { Mounth = "February", Money = 160 });
  95. company2.Add(new ChartData() { Mounth = "March", Money = 130 });
  96. return company2;
  97. }
  98. }
  99. private static void BarChart()
  100. {
  101. Console.WriteLine("\tBarChart()");
  102. // Create new document.
  103. using (DocX document = DocX.Create(@"docs\BarChart.docx"))
  104. {
  105. // Create chart.
  106. BarChart c = new BarChart();
  107. c.BarDirection = BarDirection.Column;
  108. c.BarGrouping = BarGrouping.Standard;
  109. c.GapWidth = 400;
  110. c.AddLegend(ChartLegendPosition.Bottom, false);
  111. // Create data.
  112. List<ChartData> company1 = ChartData.CreateCompanyList1();
  113. List<ChartData> company2 = ChartData.CreateCompanyList2();
  114. // Create and add series
  115. Series s1 = new Series("Microsoft");
  116. s1.Color = Color.GreenYellow;
  117. s1.Bind(company1, "Mounth", "Money");
  118. c.AddSeries(s1);
  119. Series s2 = new Series("Apple");
  120. s2.Bind(company2, "Mounth", "Money");
  121. c.AddSeries(s2);
  122. // Insert chart into document
  123. document.InsertParagraph("Diagram").FontSize(20);
  124. document.InsertChart(c);
  125. document.Save();
  126. }
  127. Console.WriteLine("\tCreated: docs\\BarChart.docx\n");
  128. }
  129. private static void PieChart()
  130. {
  131. Console.WriteLine("\tPieChart()");
  132. // Create new document.
  133. using (DocX document = DocX.Create(@"docs\PieChart.docx"))
  134. {
  135. // Create chart.
  136. PieChart c = new PieChart();
  137. c.AddLegend(ChartLegendPosition.Bottom, false);
  138. // Create data.
  139. List<ChartData> company2 = ChartData.CreateCompanyList2();
  140. // Create and add series
  141. Series s = new Series("Apple");
  142. s.Bind(company2, "Mounth", "Money");
  143. c.AddSeries(s);
  144. // Insert chart into document
  145. document.InsertParagraph("Diagram").FontSize(20);
  146. document.InsertChart(c);
  147. document.Save();
  148. }
  149. Console.WriteLine("\tCreated: docs\\PieChart.docx\n");
  150. }
  151. private static void LineChart()
  152. {
  153. Console.WriteLine("\tLineChart()");
  154. // Create new document.
  155. using (DocX document = DocX.Create(@"docs\LineChart.docx"))
  156. {
  157. // Create chart.
  158. LineChart c = new LineChart();
  159. c.AddLegend(ChartLegendPosition.Bottom, false);
  160. // Create data.
  161. List<ChartData> company1 = ChartData.CreateCompanyList1();
  162. List<ChartData> company2 = ChartData.CreateCompanyList2();
  163. // Create and add series
  164. Series s1 = new Series("Microsoft");
  165. s1.Color = Color.GreenYellow;
  166. s1.Bind(company1, "Mounth", "Money");
  167. c.AddSeries(s1);
  168. Series s2 = new Series("Apple");
  169. s2.Bind(company2, "Mounth", "Money");
  170. c.AddSeries(s2);
  171. // Insert chart into document
  172. document.InsertParagraph("Diagram").FontSize(20);
  173. document.InsertChart(c);
  174. document.Save();
  175. }
  176. Console.WriteLine("\tCreated: docs\\LineChart.docx\n");
  177. }
  178. private static void Chart3D()
  179. {
  180. Console.WriteLine("\tChart3D()");
  181. // Create new document.
  182. using (DocX document = DocX.Create(@"docs\3DChart.docx"))
  183. {
  184. // Create chart.
  185. BarChart c = new BarChart();
  186. c.View3D = true;
  187. // Create data.
  188. List<ChartData> company1 = ChartData.CreateCompanyList1();
  189. // Create and add series
  190. Series s = new Series("Microsoft");
  191. s.Color = Color.GreenYellow;
  192. s.Bind(company1, "Mounth", "Money");
  193. c.AddSeries(s);
  194. // Insert chart into document
  195. document.InsertParagraph("3D Diagram").FontSize(20);
  196. document.InsertChart(c);
  197. document.Save();
  198. }
  199. Console.WriteLine("\tCreated: docs\\3DChart.docx\n");
  200. }
  201. #endregion
  202. /// <summary>
  203. /// Load a document and set content controls.
  204. /// </summary>
  205. private static void Contents()
  206. {
  207. Console.WriteLine("\tContent()");
  208. // Load a document.
  209. using (DocX document = DocX.Load(@"docs\Content.docx"))
  210. {
  211. foreach (var c in document.Contents)
  212. {
  213. Console.WriteLine(String.Format("Name : {0}, Tag : {1}", c.Name, c.Tag));
  214. }
  215. (from d in document.Contents
  216. where d.Name == "Name"
  217. select d).First().SetText("NewerText");
  218. document.SaveAs(@"docs\ContentSetSingle.docx");
  219. XElement el = new XElement("Root",
  220. new XElement("Name", "Claudia"),
  221. new XElement("Address", "17 Liberty St"),
  222. new XElement("Total", "123.45")
  223. );
  224. XDocument doc = new XDocument(el);
  225. document.SetContent(el);
  226. document.SaveAs(@"docs\ContentSetWithElement.docx");
  227. doc.Save(@"docs\elements.xml");
  228. document.SetContent(@"docs\elements.xml");
  229. document.SaveAs(@"docs\ContentSetWithPath.docx");
  230. }
  231. }
  232. /// <summary>
  233. /// Create a document wit(h two equations.
  234. /// </summary>
  235. private static void Equations()
  236. {
  237. Console.WriteLine("\tEquations()");
  238. // Create a new document.
  239. using (DocX document = DocX.Create(@"docs\Equations.docx"))
  240. {
  241. // Insert first Equation in this document.
  242. Paragraph pEquation1 = document.InsertEquation("x = y+z");
  243. // Insert second Equation in this document and add formatting.
  244. Paragraph pEquation2 = document.InsertEquation("x = (y+z)/t").FontSize(18).Color(Color.Blue);
  245. // Save this document to disk.
  246. document.Save();
  247. Console.WriteLine("\tCreated: docs\\Equations.docx\n");
  248. }
  249. }
  250. public static void DocumentHeading()
  251. {
  252. Console.WriteLine("\tDocumentHeading()");
  253. using (DocX document = DocX.Create(@"docs\DocumentHeading.docx"))
  254. {
  255. foreach (HeadingType heading in (HeadingType[])Enum.GetValues(typeof(HeadingType)))
  256. {
  257. string text = string.Format("{0} - The quick brown fox jumps over the lazy dog", heading.EnumDescription());
  258. Paragraph p = document.InsertParagraph();
  259. p.AppendLine(text).Heading(heading);
  260. }
  261. document.Save();
  262. Console.WriteLine("\tCreated: docs\\DocumentHeading.docx\n");
  263. }
  264. }
  265. private static void Bookmarks()
  266. {
  267. Console.WriteLine("\tBookmarks()");
  268. using (var document = DocX.Create(@"docs\Bookmarks.docx"))
  269. {
  270. var paragraph = document.InsertBookmark("firstBookmark");
  271. var paragraph2 = document.InsertParagraph("This is a paragraph which contains a ");
  272. paragraph2.AppendBookmark("secondBookmark");
  273. paragraph2.Append("bookmark");
  274. paragraph2.InsertAtBookmark("handy ", "secondBookmark");
  275. document.Save();
  276. Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n");
  277. }
  278. }
  279. /// <summary>
  280. /// Loads a document 'DocumentWithBookmarks.docx' and changes text inside bookmark keeping formatting the same.
  281. /// This code creates the file 'BookmarksReplaceTextOfBookmarkKeepingFormat.docx'.
  282. /// </summary>
  283. private static void BookmarksReplaceTextOfBookmarkKeepingFormat()
  284. {
  285. Console.WriteLine("\tBookmarksReplaceTextOfBookmarkKeepingFormat()");
  286. using (DocX docX = DocX.Load("DocumentWithBookmarks.docx"))
  287. {
  288. foreach (Bookmark bookmark in docX.Bookmarks)
  289. Console.WriteLine("\t\tFound bookmark {0}", bookmark.Name);
  290. // Replace bookmars content
  291. docX.Bookmarks["bmkNoContent"].SetText("Here there was a bookmark");
  292. docX.Bookmarks["bmkContent"].SetText("Here there was a bookmark with a previous content");
  293. docX.Bookmarks["bmkFormattedContent"].SetText("Here there was a formatted bookmark");
  294. docX.SaveAs(@"docs\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
  295. }
  296. Console.WriteLine("\tCreated: docs\\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
  297. }
  298. /// <summary>
  299. /// Create a document with a Paragraph whos first line is indented.
  300. /// </summary>
  301. private static void Indentation()
  302. {
  303. Console.WriteLine("\tIndentation()");
  304. // Create a new document.
  305. using (DocX document = DocX.Create(@"docs\Indentation.docx"))
  306. {
  307. // Create a new Paragraph.
  308. Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
  309. // Indent only the first line of the Paragraph.
  310. p.IndentationFirstLine = 1.0f;
  311. // Save all changes made to this document.
  312. document.Save();
  313. Console.WriteLine("\tCreated: docs\\Indentation.docx\n");
  314. }
  315. }
  316. /// <summary>
  317. /// Create a document that with RightToLeft text flow.
  318. /// </summary>
  319. private static void RightToLeft()
  320. {
  321. Console.WriteLine("\tRightToLeft()");
  322. // Create a new document.
  323. using (DocX document = DocX.Create(@"docs\RightToLeft.docx"))
  324. {
  325. // Create a new Paragraph with the text "Hello World".
  326. Paragraph p = document.InsertParagraph("Hello World.");
  327. // Make this Paragraph flow right to left. Default is left to right.
  328. p.Direction = Direction.RightToLeft;
  329. // You don't need to manually set the text direction foreach Paragraph, you can just call this function.
  330. document.SetDirection(Direction.RightToLeft);
  331. // Save all changes made to this document.
  332. document.Save();
  333. Console.WriteLine("\tCreated: docs\\RightToLeft.docx\n");
  334. }
  335. }
  336. /// <summary>
  337. /// Creates a document with a Hyperlink, an Image and a Table.
  338. /// </summary>
  339. private static void HyperlinksImagesTables()
  340. {
  341. Console.WriteLine("\tHyperlinksImagesTables()");
  342. // Create a document.
  343. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx"))
  344. {
  345. // Add a hyperlink into the document.
  346. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  347. // Add a Table into the document.
  348. Table table = document.AddTable(2, 2);
  349. table.Design = TableDesign.ColorfulGridAccent2;
  350. table.Alignment = Alignment.center;
  351. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  352. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  353. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  354. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  355. Row newRow = table.InsertRow(table.Rows[1]);
  356. newRow.ReplaceText("4", "5");
  357. // Add an image into the document.
  358. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  359. rd.Up(2);
  360. Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  361. // Create a picture (A custom view of an Image).
  362. Picture picture = image.CreatePicture();
  363. picture.Rotation = 10;
  364. picture.SetPictureShape(BasicShapes.cube);
  365. // Insert a new Paragraph into the document.
  366. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  367. title.Alignment = Alignment.center;
  368. // Insert a new Paragraph into the document.
  369. Paragraph p1 = document.InsertParagraph();
  370. // Append content to the Paragraph
  371. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  372. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  373. p1.AppendLine();
  374. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  375. p1.AppendLine();
  376. p1.AppendLine("Can you check this Table of figures for me?");
  377. p1.AppendLine();
  378. // Insert the Table after Paragraph 1.
  379. p1.InsertTableAfterSelf(table);
  380. // Insert a new Paragraph into the document.
  381. Paragraph p2 = document.InsertParagraph();
  382. // Append content to the Paragraph.
  383. p2.AppendLine("Is it correct?");
  384. // Save this document.
  385. document.Save();
  386. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
  387. }
  388. }
  389. private static void HyperlinksImagesTablesWithLists()
  390. {
  391. Console.WriteLine("\tHyperlinksImagesTablesWithLists()");
  392. // Create a document.
  393. using (DocX document = DocX.Create(@"docs\HyperlinksImagesTablesWithLists.docx"))
  394. {
  395. // Add a hyperlink into the document.
  396. Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
  397. // created numbered lists
  398. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
  399. document.AddListItem(numberedList, "First sub list item", 1);
  400. document.AddListItem(numberedList, "Second List Item.");
  401. document.AddListItem(numberedList, "Third list item.");
  402. document.AddListItem(numberedList, "Nested item.", 1);
  403. document.AddListItem(numberedList, "Second nested item.", 1);
  404. // created bulleted lists
  405. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  406. document.AddListItem(bulletedList, "Second bullet item");
  407. document.AddListItem(bulletedList, "Sub bullet item", 1);
  408. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  409. document.AddListItem(bulletedList, "Third bullet item");
  410. // Add a Table into the document.
  411. Table table = document.AddTable(2, 2);
  412. table.Design = TableDesign.ColorfulGridAccent2;
  413. table.Alignment = Alignment.center;
  414. table.Rows[0].Cells[0].Paragraphs[0].Append("1");
  415. table.Rows[0].Cells[1].Paragraphs[0].Append("2");
  416. table.Rows[1].Cells[0].Paragraphs[0].Append("3");
  417. table.Rows[1].Cells[1].Paragraphs[0].Append("4");
  418. Row newRow = table.InsertRow(table.Rows[1]);
  419. newRow.ReplaceText("4", "5");
  420. // Add an image into the document.
  421. RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
  422. rd.Up(2);
  423. Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
  424. // Create a picture (A custom view of an Image).
  425. Picture picture = image.CreatePicture();
  426. picture.Rotation = 10;
  427. picture.SetPictureShape(BasicShapes.cube);
  428. // Insert a new Paragraph into the document.
  429. Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
  430. title.Alignment = Alignment.center;
  431. // Insert a new Paragraph into the document.
  432. Paragraph p1 = document.InsertParagraph();
  433. // Append content to the Paragraph
  434. p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
  435. p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
  436. p1.AppendLine();
  437. p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
  438. p1.AppendLine();
  439. p1.AppendLine("Can you check this Table of figures for me?");
  440. p1.AppendLine();
  441. // Insert the Table after Paragraph 1.
  442. p1.InsertTableAfterSelf(table);
  443. // Insert a new Paragraph into the document.
  444. Paragraph p2 = document.InsertParagraph();
  445. // Append content to the Paragraph.
  446. p2.AppendLine("Is it correct?");
  447. p2.AppendLine();
  448. p2.AppendLine("Adding bullet list below: ");
  449. document.InsertList(bulletedList);
  450. // Adding another paragraph to add table and bullet list after it
  451. Paragraph p3 = document.InsertParagraph();
  452. p3.AppendLine();
  453. p3.AppendLine("Adding another table...");
  454. // Adding another table
  455. Table table1 = document.AddTable(2, 2);
  456. table1.Design = TableDesign.ColorfulGridAccent2;
  457. table1.Alignment = Alignment.center;
  458. table1.Rows[0].Cells[0].Paragraphs[0].Append("1");
  459. table1.Rows[0].Cells[1].Paragraphs[0].Append("2");
  460. table1.Rows[1].Cells[0].Paragraphs[0].Append("3");
  461. table1.Rows[1].Cells[1].Paragraphs[0].Append("4");
  462. Paragraph p4 = document.InsertParagraph();
  463. p4.InsertTableBeforeSelf(table1);
  464. p4.AppendLine();
  465. // Insert numbered list after table
  466. Paragraph p5 = document.InsertParagraph();
  467. p5.AppendLine("Adding numbered list below: ");
  468. p5.AppendLine();
  469. document.InsertList(numberedList);
  470. // Save this document.
  471. document.Save();
  472. Console.WriteLine("\tCreated: docs\\HyperlinksImagesTablesWithLists.docx\n");
  473. }
  474. }
  475. private static void DocumentMargins()
  476. {
  477. Console.WriteLine("\tDocumentMargins()");
  478. // Create a document.
  479. using (DocX document = DocX.Create(@"docs\DocumentMargins.docx"))
  480. {
  481. // Create a float var that contains doc Margins properties.
  482. float leftMargin = document.MarginLeft;
  483. float rightMargin = document.MarginRight;
  484. float topMargin = document.MarginTop;
  485. float bottomMargin = document.MarginBottom;
  486. // Modify using your own vars.
  487. leftMargin = 95F;
  488. rightMargin = 45F;
  489. topMargin = 50F;
  490. bottomMargin = 180F;
  491. // Or simply work the margins by setting the property directly.
  492. document.MarginLeft = leftMargin;
  493. document.MarginRight = rightMargin;
  494. document.MarginTop = topMargin;
  495. document.MarginBottom = bottomMargin;
  496. // created bulleted lists
  497. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  498. document.AddListItem(bulletedList, "Second bullet item");
  499. document.AddListItem(bulletedList, "Sub bullet item", 1);
  500. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  501. document.AddListItem(bulletedList, "Third bullet item");
  502. document.InsertList(bulletedList);
  503. // Save this document.
  504. document.Save();
  505. Console.WriteLine("\tCreated: docs\\DocumentMargins.docx\n");
  506. }
  507. }
  508. private static void DocumentsWithListsFontChange()
  509. {
  510. Console.WriteLine("\tDocumentsWithListsFontChange()");
  511. // Create a document.
  512. using (DocX document = DocX.Create(@"docs\DocumentsWithListsFontChange.docx"))
  513. {
  514. foreach (FontFamily oneFontFamily in FontFamily.Families)
  515. {
  516. FontFamily fontFamily = oneFontFamily;
  517. double fontSize = 15;
  518. // created numbered lists
  519. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
  520. document.AddListItem(numberedList, "First sub list item", 1);
  521. document.AddListItem(numberedList, "Second List Item.");
  522. document.AddListItem(numberedList, "Third list item.");
  523. document.AddListItem(numberedList, "Nested item.", 1);
  524. document.AddListItem(numberedList, "Second nested item.", 1);
  525. // created bulleted lists
  526. var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
  527. document.AddListItem(bulletedList, "Second bullet item");
  528. document.AddListItem(bulletedList, "Sub bullet item", 1);
  529. document.AddListItem(bulletedList, "Second sub bullet item", 1);
  530. document.AddListItem(bulletedList, "Third bullet item");
  531. document.InsertList(bulletedList);
  532. document.InsertList(numberedList, fontFamily, fontSize);
  533. }
  534. // Save this document.
  535. document.Save();
  536. Console.WriteLine("\tCreated: docs\\DocumentsWithListsFontChange.docx\n");
  537. }
  538. }
  539. private static void AddList()
  540. {
  541. Console.WriteLine("\tAddList()");
  542. using (var document = DocX.Create(@"docs\Lists.docx"))
  543. {
  544. var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered);
  545. //Add a numbered list starting at 2
  546. document.AddListItem(numberedList, "Second List Item.");
  547. document.AddListItem(numberedList, "Third list item.");
  548. document.AddListItem(numberedList, "First sub list item", 1);
  549. document.AddListItem(numberedList, "Nested item.", 2);
  550. document.AddListItem(numberedList, "Fourth nested item.");
  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", 2);
  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. }