Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Program.cs 66KB

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