您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Program.cs 61KB

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