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

Program.cs 90KB

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