forked from xceedsoftware/DocX
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
2023 lines (1640 loc) · 90.5 KB
/
Copy pathProgram.cs
File metadata and controls
2023 lines (1640 loc) · 90.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Novacode;
using WindowsBitmap = System.Drawing.Bitmap;
using WindowsBrushes = System.Drawing.Brushes;
using WindowsColor = System.Drawing.Color;
using WindowsFont = System.Drawing.Font;
using WindowsFontFamily = System.Drawing.FontFamily;
using WindowsGraphics = System.Drawing.Graphics;
using WindowsImageFormat = System.Drawing.Imaging.ImageFormat;
namespace Examples
{
class Program
{
private static Border BlankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, WindowsColor.White);
static void Main(string[] args)
{
Setup();
Examples();
}
static void Examples()
{
// Easy
Console.WriteLine("\nRunning Easy Examples");
HelloWorld();
HelloWorldKeepLinesTogether();
HelloWorldKeepWithNext();
HelloWorldAdvancedFormatting();
HelloWorldProtectedDocument();
HelloWorldAddPictureToWord();
HelloWorldInsertHorizontalLine();
RightToLeft();
Indentation();
HeadersAndFooters();
HyperlinksImagesTables();
AddList();
Equations();
Bookmarks();
BookmarksReplaceTextOfBookmarkKeepingFormat();
BarChart();
PieChart();
LineChart();
Chart3D();
DocumentMargins();
CreateTableWithTextDirection();
CreateTableRowsFromTemplate();
AddToc();
AddTocByReference();
// Intermediate
Console.WriteLine("\nRunning Intermediate Examples");
CreateInvoice();
HyperlinksImagesTablesWithLists();
HeadersAndFootersWithImagesAndTables();
HeadersAndFootersWithImagesAndTablesUsingInsertPicture();
DocumentsWithListsFontChange();
DocumentHeading();
LargeTable();
TableWithSpecifiedWidths();
//Contents();
// Advanced
Console.WriteLine("\nRunning Advanced Examples");
ProgrammaticallyManipulateImbeddedImage();
ReplaceTextParallel();
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
private static void Setup()
{
if (!Directory.Exists("docs"))
{
Directory.CreateDirectory("docs");
}
}
#region Charts
private class ChartData
{
public String Mounth { get; set; }
public Double Money { get; set; }
public static List<ChartData> CreateCompanyList1()
{
List<ChartData> company1 = new List<ChartData>();
company1.Add(new ChartData() { Mounth = "January", Money = 100 });
company1.Add(new ChartData() { Mounth = "February", Money = 120 });
company1.Add(new ChartData() { Mounth = "March", Money = 140 });
return company1;
}
public static List<ChartData> CreateCompanyList2()
{
List<ChartData> company2 = new List<ChartData>();
company2.Add(new ChartData() { Mounth = "January", Money = 80 });
company2.Add(new ChartData() { Mounth = "February", Money = 160 });
company2.Add(new ChartData() { Mounth = "March", Money = 130 });
return company2;
}
}
private static void BarChart()
{
Console.WriteLine("\tBarChart()");
// Create new document.
using (DocX document = DocX.Create(@"docs\BarChart.docx"))
{
// Create chart.
BarChart c = new BarChart();
c.BarDirection = BarDirection.Column;
c.BarGrouping = BarGrouping.Standard;
c.GapWidth = 400;
c.AddLegend(ChartLegendPosition.Bottom, false);
// Create data.
List<ChartData> company1 = ChartData.CreateCompanyList1();
List<ChartData> company2 = ChartData.CreateCompanyList2();
// Create and add series
Series s1 = new Series("Microsoft");
s1.Color = WindowsColor.GreenYellow;
s1.Bind(company1, "Mounth", "Money");
c.AddSeries(s1);
Series s2 = new Series("Apple");
s2.Bind(company2, "Mounth", "Money");
c.AddSeries(s2);
// Insert chart into document
document.InsertParagraph("Diagram").FontSize(20);
document.InsertChart(c);
document.Save();
}
Console.WriteLine("\tCreated: docs\\BarChart.docx\n");
}
private static void PieChart()
{
Console.WriteLine("\tPieChart()");
// Create new document.
using (DocX document = DocX.Create(@"docs\PieChart.docx"))
{
// Create chart.
PieChart c = new PieChart();
c.AddLegend(ChartLegendPosition.Bottom, false);
// Create data.
List<ChartData> company2 = ChartData.CreateCompanyList2();
// Create and add series
Series s = new Series("Apple");
s.Bind(company2, "Mounth", "Money");
c.AddSeries(s);
// Insert chart into document
document.InsertParagraph("Diagram").FontSize(20);
document.InsertChart(c);
document.Save();
}
Console.WriteLine("\tCreated: docs\\PieChart.docx\n");
}
private static void LineChart()
{
Console.WriteLine("\tLineChart()");
// Create new document.
using (DocX document = DocX.Create(@"docs\LineChart.docx"))
{
// Create chart.
LineChart c = new LineChart();
c.AddLegend(ChartLegendPosition.Bottom, false);
// Create data.
List<ChartData> company1 = ChartData.CreateCompanyList1();
List<ChartData> company2 = ChartData.CreateCompanyList2();
// Create and add series
Series s1 = new Series("Microsoft");
s1.Color = WindowsColor.GreenYellow;
s1.Bind(company1, "Mounth", "Money");
c.AddSeries(s1);
Series s2 = new Series("Apple");
s2.Bind(company2, "Mounth", "Money");
c.AddSeries(s2);
// Insert chart into document
document.InsertParagraph("Diagram").FontSize(20);
document.InsertChart(c);
document.Save();
}
Console.WriteLine("\tCreated: docs\\LineChart.docx\n");
}
private static void Chart3D()
{
Console.WriteLine("\tChart3D()");
// Create new document.
using (DocX document = DocX.Create(@"docs\3DChart.docx"))
{
// Create chart.
BarChart c = new BarChart();
c.View3D = true;
// Create data.
List<ChartData> company1 = ChartData.CreateCompanyList1();
// Create and add series
Series s = new Series("Microsoft");
s.Color = WindowsColor.GreenYellow;
s.Bind(company1, "Mounth", "Money");
c.AddSeries(s);
// Insert chart into document
document.InsertParagraph("3D Diagram").FontSize(20);
document.InsertChart(c);
document.Save();
}
Console.WriteLine("\tCreated: docs\\3DChart.docx\n");
}
#endregion
/// <summary>
/// Load a document and set content controls.
/// </summary>
private static void Contents()
{
Console.WriteLine("\tContent()");
// Load a document.
using (DocX document = DocX.Load(@"docs\Content.docx"))
{
foreach (var c in document.Contents)
{
Console.WriteLine(String.Format("Name : {0}, Tag : {1}", c.Name, c.Tag));
}
(from d in document.Contents
where d.Name == "Name"
select d).First().SetText("NewerText");
document.SaveAs(@"docs\ContentSetSingle.docx");
XElement el = new XElement("Root",
new XElement("Name", "Claudia"),
new XElement("Address", "17 Liberty St"),
new XElement("Total", "123.45")
);
XDocument doc = new XDocument(el);
document.SetContent(el);
document.SaveAs(@"docs\ContentSetWithElement.docx");
doc.Save(@"docs\elements.xml");
document.SetContent(@"docs\elements.xml");
document.SaveAs(@"docs\ContentSetWithPath.docx");
}
}
/// <summary>
/// Create a document wit(h two equations.
/// </summary>
private static void Equations()
{
Console.WriteLine("\tEquations()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\Equations.docx"))
{
// Insert first Equation in this document.
Paragraph pEquation1 = document.InsertEquation("x = y+z");
// Insert second Equation in this document and add formatting.
Paragraph pEquation2 = document.InsertEquation("x = (y+z)/t").FontSize(18).Color(WindowsColor.Blue);
// Save this document to disk.
document.Save();
Console.WriteLine("\tCreated: docs\\Equations.docx\n");
}
}
public static void DocumentHeading()
{
Console.WriteLine("\tDocumentHeading()");
using (DocX document = DocX.Create(@"docs\DocumentHeading.docx"))
{
foreach (HeadingType heading in (HeadingType[])Enum.GetValues(typeof(HeadingType)))
{
string text = string.Format("{0} - The quick brown fox jumps over the lazy dog", heading.EnumDescription());
Paragraph p = document.InsertParagraph();
p.AppendLine(text).Heading(heading);
}
document.Save();
Console.WriteLine("\tCreated: docs\\DocumentHeading.docx\n");
}
}
/// <summary>
/// Loads a document having a table with a given line as template.
/// It avoids extra manipulation regarding style
/// </summary>
private static void CreateTableRowsFromTemplate()
{
Console.WriteLine("\tCreateTableFromTemplate()");
using (DocX docX = DocX.Load(@"docs\DocumentWithTemplateTable.docx"))
{
//look for one specific table here
Table orderTable = docX.Tables.First(t => t.TableCaption == "ORDER_TABLE");
if (orderTable != null)
{
//Row 0 and 1 are Headers
//Row 2 is pattern
if (orderTable.RowCount >= 2)
{
//get the Pattern row for duplication
Row orderRowPattern = orderTable.Rows[2];
//Add 5 lines of product
for (int i = 0; i < 5; i++)
{
//InsertRow performs a copy, so we get markup in new line ready for replacements
Row newOrderRow = orderTable.InsertRow(orderRowPattern, 2 + i);
newOrderRow.ReplaceText("%PRODUCT_NAME%", "Product_" + i);
newOrderRow.ReplaceText("%PRODUCT_PRICE1%", "$ " + i * new Random().Next(1, 50));
newOrderRow.ReplaceText("%PRODUCT_PRICE2%", "$ " + i * new Random().Next(1, 50));
}
//pattern row is at the end now, can be removed from table
orderRowPattern.Remove();
}
docX.SaveAs(@"docs\CreateTableFromTemplate.docx");
}
else
{
Console.WriteLine("\tError, couldn't find table with caption ORDER_TABLE in document");
}
}
Console.WriteLine("\tCreated: docs\\CreateTableFromTemplate.docx");
}
private static void Bookmarks()
{
Console.WriteLine("\tBookmarks()");
using (var document = DocX.Create(@"docs\Bookmarks.docx"))
{
var paragraph = document.InsertBookmark("firstBookmark");
var paragraph2 = document.InsertParagraph("This is a paragraph which contains a ");
paragraph2.AppendBookmark("secondBookmark");
paragraph2.Append("bookmark");
paragraph2.InsertAtBookmark("handy ", "secondBookmark");
document.Save();
Console.WriteLine("\tCreated: docs\\Bookmarks.docx\n");
}
}
/// <summary>
/// Loads a document 'DocumentWithBookmarks.docx' and changes text inside bookmark keeping formatting the same.
/// This code creates the file 'BookmarksReplaceTextOfBookmarkKeepingFormat.docx'.
/// </summary>
private static void BookmarksReplaceTextOfBookmarkKeepingFormat()
{
Console.WriteLine("\tBookmarksReplaceTextOfBookmarkKeepingFormat()");
using (DocX docX = DocX.Load(@"docs\DocumentWithBookmarks.docx"))
{
foreach (Bookmark bookmark in docX.Bookmarks)
Console.WriteLine("\t\tFound bookmark {0}", bookmark.Name);
// Replace bookmars content
docX.Bookmarks["bmkNoContent"].SetText("Here there was a bookmark");
docX.Bookmarks["bmkContent"].SetText("Here there was a bookmark with a previous content");
docX.Bookmarks["bmkFormattedContent"].SetText("Here there was a formatted bookmark");
docX.SaveAs(@"docs\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
}
Console.WriteLine("\tCreated: docs\\BookmarksReplaceTextOfBookmarkKeepingFormat.docx");
}
/// <summary>
/// Create a document with a Paragraph whos first line is indented.
/// </summary>
private static void Indentation()
{
Console.WriteLine("\tIndentation()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\Indentation.docx"))
{
// Create a new Paragraph.
Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
// Indent only the first line of the Paragraph.
p.IndentationFirstLine = 1.0f;
// Save all changes made to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\Indentation.docx\n");
}
}
/// <summary>
/// Create a document that with RightToLeft text flow.
/// </summary>
private static void RightToLeft()
{
Console.WriteLine("\tRightToLeft()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\RightToLeft.docx"))
{
// Create a new Paragraph with the text "Hello World".
Paragraph p = document.InsertParagraph("Hello World.");
// Make this Paragraph flow right to left. Default is left to right.
p.Direction = Direction.RightToLeft;
// You don't need to manually set the text direction foreach Paragraph, you can just call this function.
document.SetDirection(Direction.RightToLeft);
// Save all changes made to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\RightToLeft.docx\n");
}
}
/// <summary>
/// Creates a document with a Hyperlink, an Image and a Table.
/// </summary>
private static void HyperlinksImagesTables()
{
Console.WriteLine("\tHyperlinksImagesTables()");
// Create a document.
using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx"))
{
// Add a hyperlink into the document.
Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
// Add a Table into the document.
Table table = document.AddTable(2, 2);
table.Design = TableDesign.ColorfulGridAccent2;
table.Alignment = Alignment.center;
table.Rows[0].Cells[0].Paragraphs[0].Append("1");
table.Rows[0].Cells[1].Paragraphs[0].Append("2");
table.Rows[1].Cells[0].Paragraphs[0].Append("3");
table.Rows[1].Cells[1].Paragraphs[0].Append("4");
Row newRow = table.InsertRow(table.Rows[1]);
newRow.ReplaceText("4", "5");
// Add an image into the document.
RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
rd.Up(2);
Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
// Create a picture (A custom view of an Image).
Picture picture = image.CreatePicture();
picture.Rotation = 10;
picture.SetPictureShape(BasicShapes.cube);
// Insert a new Paragraph into the document.
Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new Font("Comic Sans MS"));
title.Alignment = Alignment.center;
// Insert a new Paragraph into the document.
Paragraph p1 = document.InsertParagraph();
// Append content to the Paragraph
p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
p1.AppendLine();
p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
p1.AppendLine();
p1.AppendLine("Can you check this Table of figures for me?");
p1.AppendLine();
// Insert the Table after Paragraph 1.
p1.InsertTableAfterSelf(table);
// Insert a new Paragraph into the document.
Paragraph p2 = document.InsertParagraph();
// Append content to the Paragraph.
p2.AppendLine("Is it correct?");
// Save this document.
document.Save();
Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
}
}
private static void HyperlinksImagesTablesWithLists()
{
Console.WriteLine("\tHyperlinksImagesTablesWithLists()");
// Create a document.
using (DocX document = DocX.Create(@"docs\HyperlinksImagesTablesWithLists.docx"))
{
// Add a hyperlink into the document.
Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
// created numbered lists
var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
document.AddListItem(numberedList, "First sub list item", 1);
document.AddListItem(numberedList, "Second List Item.");
document.AddListItem(numberedList, "Third list item.");
document.AddListItem(numberedList, "Nested item.", 1);
document.AddListItem(numberedList, "Second nested item.", 1);
// created bulleted lists
var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
document.AddListItem(bulletedList, "Second bullet item");
document.AddListItem(bulletedList, "Sub bullet item", 1);
document.AddListItem(bulletedList, "Second sub bullet item", 1);
document.AddListItem(bulletedList, "Third bullet item");
// Add a Table into the document.
Table table = document.AddTable(2, 2);
table.Design = TableDesign.ColorfulGridAccent2;
table.Alignment = Alignment.center;
table.Rows[0].Cells[0].Paragraphs[0].Append("1");
table.Rows[0].Cells[1].Paragraphs[0].Append("2");
table.Rows[1].Cells[0].Paragraphs[0].Append("3");
table.Rows[1].Cells[1].Paragraphs[0].Append("4");
Row newRow = table.InsertRow(table.Rows[1]);
newRow.ReplaceText("4", "5");
// Add an image into the document.
RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
rd.Up(2);
Image image = document.AddImage(rd.Path + @"\images\logo_template.png");
// Create a picture (A custom view of an Image).
Picture picture = image.CreatePicture();
picture.Rotation = 10;
picture.SetPictureShape(BasicShapes.cube);
// Insert a new Paragraph into the document.
Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new Font("Comic Sans MS"));
title.Alignment = Alignment.center;
// Insert a new Paragraph into the document.
Paragraph p1 = document.InsertParagraph();
// Append content to the Paragraph
p1.AppendLine("This line contains a ").Append("bold").Bold().Append(" word.");
p1.AppendLine("Here is a cool ").AppendHyperlink(link).Append(".");
p1.AppendLine();
p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
p1.AppendLine();
p1.AppendLine("Can you check this Table of figures for me?");
p1.AppendLine();
// Insert the Table after Paragraph 1.
p1.InsertTableAfterSelf(table);
// Insert a new Paragraph into the document.
Paragraph p2 = document.InsertParagraph();
// Append content to the Paragraph.
p2.AppendLine("Is it correct?");
p2.AppendLine();
p2.AppendLine("Adding bullet list below: ");
document.InsertList(bulletedList);
// Adding another paragraph to add table and bullet list after it
Paragraph p3 = document.InsertParagraph();
p3.AppendLine();
p3.AppendLine("Adding another table...");
// Adding another table
Table table1 = document.AddTable(2, 2);
table1.Design = TableDesign.ColorfulGridAccent2;
table1.Alignment = Alignment.center;
table1.Rows[0].Cells[0].Paragraphs[0].Append("1");
table1.Rows[0].Cells[1].Paragraphs[0].Append("2");
table1.Rows[1].Cells[0].Paragraphs[0].Append("3");
table1.Rows[1].Cells[1].Paragraphs[0].Append("4");
Paragraph p4 = document.InsertParagraph();
p4.InsertTableBeforeSelf(table1);
p4.AppendLine();
// Insert numbered list after table
Paragraph p5 = document.InsertParagraph();
p5.AppendLine("Adding numbered list below: ");
p5.AppendLine();
document.InsertList(numberedList);
// Save this document.
document.Save();
Console.WriteLine("\tCreated: docs\\HyperlinksImagesTablesWithLists.docx\n");
}
}
private static void DocumentMargins()
{
Console.WriteLine("\tDocumentMargins()");
// Create a document.
using (DocX document = DocX.Create(@"docs\DocumentMargins.docx"))
{
// Create a float var that contains doc Margins properties.
float leftMargin = document.MarginLeft;
float rightMargin = document.MarginRight;
float topMargin = document.MarginTop;
float bottomMargin = document.MarginBottom;
// Modify using your own vars.
leftMargin = 95F;
rightMargin = 45F;
topMargin = 50F;
bottomMargin = 180F;
// Or simply work the margins by setting the property directly.
document.MarginLeft = leftMargin;
document.MarginRight = rightMargin;
document.MarginTop = topMargin;
document.MarginBottom = bottomMargin;
// created bulleted lists
var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
document.AddListItem(bulletedList, "Second bullet item");
document.AddListItem(bulletedList, "Sub bullet item", 1);
document.AddListItem(bulletedList, "Second sub bullet item", 1);
document.AddListItem(bulletedList, "Third bullet item");
document.InsertList(bulletedList);
// Save this document.
document.Save();
Console.WriteLine("\tCreated: docs\\DocumentMargins.docx\n");
}
}
private static void DocumentsWithListsFontChange()
{
Console.WriteLine("\tDocumentsWithListsFontChange()");
// Create a document.
using (DocX document = DocX.Create(@"docs\DocumentsWithListsFontChange.docx"))
{
foreach (var oneFontFamily in WindowsFontFamily.Families)
{
var fontFamily = new Font(oneFontFamily.Name);
var fontSize = 15.0;
// created numbered lists
var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered, 1);
document.AddListItem(numberedList, "First sub list item", 1);
document.AddListItem(numberedList, "Second List Item.");
document.AddListItem(numberedList, "Third list item.");
document.AddListItem(numberedList, "Nested item.", 1);
document.AddListItem(numberedList, "Second nested item.", 1);
// created bulleted lists
var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
document.AddListItem(bulletedList, "Second bullet item");
document.AddListItem(bulletedList, "Sub bullet item", 1);
document.AddListItem(bulletedList, "Second sub bullet item", 1);
document.AddListItem(bulletedList, "Third bullet item");
document.InsertList(bulletedList);
document.InsertList(numberedList, fontFamily, fontSize);
}
// Save this document.
document.Save();
Console.WriteLine("\tCreated: docs\\DocumentsWithListsFontChange.docx\n");
}
}
private static void AddList()
{
Console.WriteLine("\tAddList()");
using (var document = DocX.Create(@"docs\Lists.docx"))
{
var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered);
//Add a numbered list starting at 2
document.AddListItem(numberedList, "Second List Item.");
document.AddListItem(numberedList, "Third list item.");
document.AddListItem(numberedList, "First sub list item", 1);
document.AddListItem(numberedList, "Nested item.", 2);
document.AddListItem(numberedList, "Fourth nested item.");
var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
document.AddListItem(bulletedList, "Second bullet item");
document.AddListItem(bulletedList, "Sub bullet item", 1);
document.AddListItem(bulletedList, "Second sub bullet item", 2);
document.AddListItem(bulletedList, "Third bullet item");
document.InsertList(numberedList);
document.InsertList(bulletedList);
document.Save();
Console.WriteLine("\tCreated: docs\\Lists.docx");
}
}
private static void HeadersAndFooters()
{
Console.WriteLine("\tHeadersAndFooters()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx"))
{
// Add Headers and Footers to this document.
document.AddHeaders();
document.AddFooters();
// Force the first page to have a different Header and Footer.
document.DifferentFirstPage = true;
// Force odd & even pages to have different Headers and Footers.
document.DifferentOddAndEvenPages = true;
// Get the first, odd and even Headers for this document.
Header header_first = document.Headers.first;
Header header_odd = document.Headers.odd;
Header header_even = document.Headers.even;
// Get the first, odd and even Footer for this document.
Footer footer_first = document.Footers.first;
Footer footer_odd = document.Footers.odd;
Footer footer_even = document.Footers.even;
// Insert a Paragraph into the first Header.
Paragraph p0 = header_first.InsertParagraph();
p0.Append("Hello First Header.").Bold();
// Insert a Paragraph into the odd Header.
Paragraph p1 = header_odd.InsertParagraph();
p1.Append("Hello Odd Header.").Bold();
// Insert a Paragraph into the even Header.
Paragraph p2 = header_even.InsertParagraph();
p2.Append("Hello Even Header.").Bold();
// Insert a Paragraph into the first Footer.
Paragraph p3 = footer_first.InsertParagraph();
p3.Append("Hello First Footer.").Bold();
// Insert a Paragraph into the odd Footer.
Paragraph p4 = footer_odd.InsertParagraph();
p4.Append("Hello Odd Footer.").Bold();
// Insert a Paragraph into the even Header.
Paragraph p5 = footer_even.InsertParagraph();
p5.Append("Hello Even Footer.").Bold();
// Insert a Paragraph into the document.
Paragraph p6 = document.InsertParagraph();
p6.AppendLine("Hello First page.");
// Create a second page to show that the first page has its own header and footer.
p6.InsertPageBreakAfterSelf();
// Insert a Paragraph after the page break.
Paragraph p7 = document.InsertParagraph();
p7.AppendLine("Hello Second page.");
// Create a third page to show that even and odd pages have different headers and footers.
p7.InsertPageBreakAfterSelf();
// Insert a Paragraph after the page break.
Paragraph p8 = document.InsertParagraph();
p8.AppendLine("Hello Third page.");
//Insert a next page break, which is a section break combined with a page break
document.InsertSectionPageBreak();
//Insert a paragraph after the "Next" page break
Paragraph p9 = document.InsertParagraph();
p9.Append("Next page section break.");
//Insert a continuous section break
document.InsertSection();
//Create a paragraph in the new section
var p10 = document.InsertParagraph();
p10.Append("Continuous section paragraph.");
// Save all changes to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n");
}// Release this document from memory.
}
private static void HeadersAndFootersWithImagesAndTables()
{
Console.WriteLine("\tHeadersAndFootersWithImagesAndTables()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\HeadersAndFootersWithImagesAndTables.docx"))
{
// Add a template logo image to this document.
RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
rd.Up(2);
Image logo = document.AddImage(rd.Path + @"\images\logo_the_happy_builder.png");
// Add Headers and Footers to this document.
document.AddHeaders();
document.AddFooters();
// Force the first page to have a different Header and Footer.
document.DifferentFirstPage = true;
// Force odd & even pages to have different Headers and Footers.
document.DifferentOddAndEvenPages = true;
// Get the first, odd and even Headers for this document.
Header header_first = document.Headers.first;
Header header_odd = document.Headers.odd;
Header header_even = document.Headers.even;
// Get the first, odd and even Footer for this document.
Footer footer_first = document.Footers.first;
Footer footer_odd = document.Footers.odd;
Footer footer_even = document.Footers.even;
// Insert a Paragraph into the first Header.
Paragraph p0 = header_first.InsertParagraph();
p0.Append("Hello First Header.").Bold();
// Insert a Paragraph into the odd Header.
Paragraph p1 = header_odd.InsertParagraph();
p1.Append("Hello Odd Header.").Bold();
// Insert a Paragraph into the even Header.
Paragraph p2 = header_even.InsertParagraph();
p2.Append("Hello Even Header.").Bold();
// Insert a Paragraph into the first Footer.
Paragraph p3 = footer_first.InsertParagraph();
p3.Append("Hello First Footer.").Bold();
// Insert a Paragraph into the odd Footer.
Paragraph p4 = footer_odd.InsertParagraph();
p4.Append("Hello Odd Footer.").Bold();
// Insert a Paragraph into the even Header.
Paragraph p5 = footer_even.InsertParagraph();
p5.Append("Hello Even Footer.").Bold();
// Insert a Paragraph into the document.
Paragraph p6 = document.InsertParagraph();
p6.AppendLine("Hello First page.");
// Create a second page to show that the first page has its own header and footer.
p6.InsertPageBreakAfterSelf();
// Insert a Paragraph after the page break.
Paragraph p7 = document.InsertParagraph();
p7.AppendLine("Hello Second page.");
// Create a third page to show that even and odd pages have different headers and footers.
p7.InsertPageBreakAfterSelf();
// Insert a Paragraph after the page break.
Paragraph p8 = document.InsertParagraph();
p8.AppendLine("Hello Third page.");
//Insert a next page break, which is a section break combined with a page break
document.InsertSectionPageBreak();
//Insert a paragraph after the "Next" page break
Paragraph p9 = document.InsertParagraph();
p9.Append("Next page section break.");
//Insert a continuous section break
document.InsertSection();
//Create a paragraph in the new section
var p10 = document.InsertParagraph();
p10.Append("Continuous section paragraph.");
// Inserting logo into footer and header into Tables
#region Company Logo in Header in Table
// Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
Table header_first_table = header_first.InsertTable(1, 2);
header_first_table.Design = TableDesign.TableGrid;
header_first_table.AutoFit = AutoFit.Window;
// Get the upper right Paragraph in the layout_table.
Paragraph upperRightParagraph = header_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
// Insert this template logo into the upper right Paragraph of Table.
upperRightParagraph.AppendPicture(logo.CreatePicture());
upperRightParagraph.Alignment = Alignment.right;
// Get the upper left Paragraph in the layout_table.
Paragraph upperLeftParagraphFirstTable = header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
upperLeftParagraphFirstTable.Append("Company Name - DocX Corporation");
#endregion
#region Company Logo in Header in Invisible Table
// Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
Table header_second_table = header_odd.InsertTable(1, 2);
header_second_table.Design = TableDesign.None;
header_second_table.AutoFit = AutoFit.Window;
// Get the upper right Paragraph in the layout_table.
Paragraph upperRightParagraphSecondTable = header_second_table.Rows[0].Cells[1].Paragraphs[0];
// Insert this template logo into the upper right Paragraph of Table.
upperRightParagraphSecondTable.AppendPicture(logo.CreatePicture());
upperRightParagraphSecondTable.Alignment = Alignment.right;
// Get the upper left Paragraph in the layout_table.
Paragraph upperLeftParagraphSecondTable = header_second_table.Rows[0].Cells[0].Paragraphs[0];
upperLeftParagraphSecondTable.Append("Company Name - DocX Corporation");
#endregion
#region Company Logo in Footer in Table
// Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
Table footer_first_table = footer_first.InsertTable(1, 2);
footer_first_table.Design = TableDesign.TableGrid;
footer_first_table.AutoFit = AutoFit.Window;
// Get the upper right Paragraph in the layout_table.
Paragraph upperRightParagraphFooterParagraph = footer_first.Tables[0].Rows[0].Cells[1].Paragraphs[0];
// Insert this template logo into the upper right Paragraph of Table.
upperRightParagraphFooterParagraph.AppendPicture(logo.CreatePicture());
upperRightParagraphFooterParagraph.Alignment = Alignment.right;
// Get the upper left Paragraph in the layout_table.
Paragraph upperLeftParagraphFirstTableFooter = footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0];
upperLeftParagraphFirstTableFooter.Append("Company Name - DocX Corporation");
#endregion
#region Company Logo in Header in Invisible Table
// Insert Table into First Header - Create a new Table with 2 columns and 1 rows.
Table footer_second_table = footer_odd.InsertTable(1, 2);
footer_second_table.Design = TableDesign.None;
footer_second_table.AutoFit = AutoFit.Window;
// Get the upper right Paragraph in the layout_table.
Paragraph upperRightParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[1].Paragraphs[0];
// Insert this template logo into the upper right Paragraph of Table.
upperRightParagraphSecondTableFooter.AppendPicture(logo.CreatePicture());
upperRightParagraphSecondTableFooter.Alignment = Alignment.right;
// Get the upper left Paragraph in the layout_table.
Paragraph upperLeftParagraphSecondTableFooter = footer_second_table.Rows[0].Cells[0].Paragraphs[0];
upperLeftParagraphSecondTableFooter.Append("Company Name - DocX Corporation");
#endregion
// Save all changes to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\HeadersAndFootersWithImagesAndTables.docx\n");
}// Release this document from memory.
}
private static void HeadersAndFootersWithImagesAndTablesUsingInsertPicture()