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 65KB

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