Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Program.cs 90KB

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