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

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