Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Program.cs 89KB

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