forked from xceedsoftware/DocX
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDocX.cs
4459 lines (3973 loc) · 196 KB
/
DocX.cs
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.IO;
using System.IO.Packaging;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Collections.ObjectModel;
namespace Novacode
{
/// <summary>
/// Represents a document.
/// </summary>
public class DocX : Container, IDisposable
{
#region Namespaces
static internal XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
static internal XNamespace rel = "http://schemas.openxmlformats.org/package/2006/relationships";
static internal XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
static internal XNamespace m = "http://schemas.openxmlformats.org/officeDocument/2006/math";
static internal XNamespace customPropertiesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
static internal XNamespace customVTypesSchema = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes";
static internal XNamespace wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
static internal XNamespace a = "http://schemas.openxmlformats.org/drawingml/2006/main";
static internal XNamespace c = "http://schemas.openxmlformats.org/drawingml/2006/chart";
static internal XNamespace v = "urn:schemas-microsoft-com:vml";
internal static XNamespace n = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
#endregion
internal float getMarginAttribute(XName name)
{
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr != null)
{
XElement pgMar = sectPr.Element(XName.Get("pgMar", DocX.w.NamespaceName));
if (pgMar != null)
{
XAttribute top = pgMar.Attribute(name);
if (top != null)
{
float f;
if (float.TryParse(top.Value, out f))
return (int)(f / 20.0f);
}
}
}
return 0;
}
internal void setMarginAttribute(XName xName, float value)
{
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr != null)
{
XElement pgMar = sectPr.Element(XName.Get("pgMar", DocX.w.NamespaceName));
if (pgMar != null)
{
XAttribute top = pgMar.Attribute(xName);
if (top != null)
{
top.SetValue(value * 20);
}
}
}
}
public BookmarkCollection Bookmarks
{
get
{
BookmarkCollection bookmarks = new BookmarkCollection();
foreach (Paragraph paragraph in Paragraphs)
bookmarks.AddRange(paragraph.GetBookmarks());
return bookmarks;
}
}
/// <summary>
/// Top margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float MarginTop
{
get
{
return getMarginAttribute(XName.Get("top", DocX.w.NamespaceName));
}
set
{
setMarginAttribute(XName.Get("top", DocX.w.NamespaceName), value);
}
}
/// <summary>
/// Bottom margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float MarginBottom
{
get
{
return getMarginAttribute(XName.Get("bottom", DocX.w.NamespaceName));
}
set
{
setMarginAttribute(XName.Get("bottom", DocX.w.NamespaceName), value);
}
}
/// <summary>
/// Left margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float MarginLeft
{
get
{
return getMarginAttribute(XName.Get("left", DocX.w.NamespaceName));
}
set
{
setMarginAttribute(XName.Get("left", DocX.w.NamespaceName), value);
}
}
/// <summary>
/// Right margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float MarginRight
{
get
{
return getMarginAttribute(XName.Get("right", DocX.w.NamespaceName));
}
set
{
setMarginAttribute(XName.Get("right", DocX.w.NamespaceName), value);
}
}
/// <summary>
/// Header margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float MarginHeader
{
get
{
return getMarginAttribute(XName.Get("header", DocX.w.NamespaceName));
}
set
{
setMarginAttribute(XName.Get("header", DocX.w.NamespaceName), value);
}
}
/// <summary>
/// Footer margin value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float MarginFooter
{
get
{
return getMarginAttribute(XName.Get("footer", DocX.w.NamespaceName));
}
set
{
setMarginAttribute(XName.Get("footer", DocX.w.NamespaceName), value);
}
}
/// <summary>
/// Page width value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float PageWidth
{
get
{
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr != null)
{
XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
if (pgSz != null)
{
XAttribute w = pgSz.Attribute(XName.Get("w", DocX.w.NamespaceName));
if (w != null)
{
float f;
if (float.TryParse(w.Value, out f))
return (int)(f / 20.0f);
}
}
}
return (12240.0f / 20.0f);
}
set
{
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
if (body != null)
{
XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr != null)
{
XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
if (pgSz != null)
{
pgSz.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), value * 20);
}
}
}
}
}
/// <summary>
/// Page height value in points. 1pt = 1/72 of an inch. Word internally writes docx using units = 1/20th of a point.
/// </summary>
public float PageHeight
{
get
{
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr != null)
{
XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
if (pgSz != null)
{
XAttribute w = pgSz.Attribute(XName.Get("h", DocX.w.NamespaceName));
if (w != null)
{
float f;
if (float.TryParse(w.Value, out f))
return (int)(f / 20.0f);
}
}
}
return (15840.0f / 20.0f);
}
set
{
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
if (body != null)
{
XElement sectPr = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr != null)
{
XElement pgSz = sectPr.Element(XName.Get("pgSz", DocX.w.NamespaceName));
if (pgSz != null)
{
pgSz.SetAttributeValue(XName.Get("h", DocX.w.NamespaceName), value * 20);
}
}
}
}
}
/// <summary>
/// Returns true if any editing restrictions are imposed on this document.
/// </summary>
/// <example>
/// <code>
/// // Create a new document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// if(document.isProtected)
/// Console.WriteLine("Protected");
/// else
/// Console.WriteLine("Not protected");
///
/// // Save the document.
/// document.Save();
/// }
/// </code>
/// </example>
/// <seealso cref="AddProtection(EditRestrictions)"/>
/// <seealso cref="RemoveProtection"/>
/// <seealso cref="GetProtectionType"/>
public bool isProtected
{
get
{
return settings.Descendants(XName.Get("documentProtection", DocX.w.NamespaceName)).Count() > 0;
}
}
/// <summary>
/// Returns the type of editing protection imposed on this document.
/// </summary>
/// <returns>The type of editing protection imposed on this document.</returns>
/// <example>
/// <code>
/// Create a new document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Make sure the document is protected before checking the protection type.
/// if (document.isProtected)
/// {
/// EditRestrictions protection = document.GetProtectionType();
/// Console.WriteLine("Document is protected using " + protection.ToString());
/// }
///
/// else
/// Console.WriteLine("Document is not protected.");
///
/// // Save the document.
/// document.Save();
/// }
/// </code>
/// </example>
/// <seealso cref="AddProtection(EditRestrictions)"/>
/// <seealso cref="RemoveProtection"/>
/// <seealso cref="isProtected"/>
public EditRestrictions GetProtectionType()
{
if (isProtected)
{
XElement documentProtection = settings.Descendants(XName.Get("documentProtection", DocX.w.NamespaceName)).FirstOrDefault();
string edit_type = documentProtection.Attribute(XName.Get("edit", DocX.w.NamespaceName)).Value;
return (EditRestrictions)Enum.Parse(typeof(EditRestrictions), edit_type);
}
return EditRestrictions.none;
}
/// <summary>
/// Add editing protection to this document.
/// </summary>
/// <param name="er">The type of protection to add to this document.</param>
/// <example>
/// <code>
/// // Create a new document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Allow no editing, only the adding of comment.
/// document.AddProtection(EditRestrictions.comments);
///
/// // Save the document.
/// document.Save();
/// }
/// </code>
/// </example>
/// <seealso cref="RemoveProtection"/>
/// <seealso cref="GetProtectionType"/>
/// <seealso cref="isProtected"/>
public void AddProtection(EditRestrictions er)
{
// Call remove protection before adding a new protection element.
RemoveProtection();
if (er == EditRestrictions.none)
return;
XElement documentProtection = new XElement(XName.Get("documentProtection", DocX.w.NamespaceName));
documentProtection.Add(new XAttribute(XName.Get("edit", DocX.w.NamespaceName), er.ToString()));
documentProtection.Add(new XAttribute(XName.Get("enforcement", DocX.w.NamespaceName), "1"));
settings.Root.AddFirst(documentProtection);
}
public void AddProtection(EditRestrictions er, string strPassword)
{
// http://blogs.msdn.com/b/vsod/archive/2010/04/05/how-to-set-the-editing-restrictions-in-word-using-open-xml-sdk-2-0.aspx
// Call remove protection before adding a new protection element.
RemoveProtection();
if (er == EditRestrictions.none)
return;
XElement documentProtection = new XElement(XName.Get("documentProtection", DocX.w.NamespaceName));
documentProtection.Add(new XAttribute(XName.Get("edit", DocX.w.NamespaceName), er.ToString()));
documentProtection.Add(new XAttribute(XName.Get("enforcement", DocX.w.NamespaceName), "1"));
int[] InitialCodeArray = { 0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3 };
int[,] EncryptionMatrix = new int[15, 7]
{
/* char 1 */ {0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09},
/* char 2 */ {0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF},
/* char 3 */ {0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0},
/* char 4 */ {0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40},
/* char 5 */ {0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5},
/* char 6 */ {0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A},
/* char 7 */ {0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9},
/* char 8 */ {0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0},
/* char 9 */ {0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC},
/* char 10 */ {0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10},
/* char 11 */ {0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168},
/* char 12 */ {0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C},
/* char 13 */ {0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD},
/* char 14 */ {0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC},
/* char 15 */ {0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4}
};
// Generate the Salt
byte[] arrSalt = new byte[16];
RandomNumberGenerator rand = new RNGCryptoServiceProvider();
rand.GetNonZeroBytes(arrSalt);
//Array to hold Key Values
byte[] generatedKey = new byte[4];
//Maximum length of the password is 15 chars.
int intMaxPasswordLength = 15;
if (!String.IsNullOrEmpty(strPassword))
{
strPassword = strPassword.Substring(0, Math.Min(strPassword.Length, intMaxPasswordLength));
byte[] arrByteChars = new byte[strPassword.Length];
for (int intLoop = 0; intLoop < strPassword.Length; intLoop++)
{
int intTemp = Convert.ToInt32(strPassword[intLoop]);
arrByteChars[intLoop] = Convert.ToByte(intTemp & 0x00FF);
if (arrByteChars[intLoop] == 0)
arrByteChars[intLoop] = Convert.ToByte((intTemp & 0xFF00) >> 8);
}
int intHighOrderWord = InitialCodeArray[arrByteChars.Length - 1];
for (int intLoop = 0; intLoop < arrByteChars.Length; intLoop++)
{
int tmp = intMaxPasswordLength - arrByteChars.Length + intLoop;
for (int intBit = 0; intBit < 7; intBit++)
{
if ((arrByteChars[intLoop] & (0x0001 << intBit)) != 0)
{
intHighOrderWord ^= EncryptionMatrix[tmp, intBit];
}
}
}
int intLowOrderWord = 0;
// For each character in the strPassword, going backwards
for (int intLoopChar = arrByteChars.Length - 1; intLoopChar >= 0; intLoopChar--)
{
intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars[intLoopChar];
}
intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars.Length ^ 0xCE4B;
// Combine the Low and High Order Word
int intCombinedkey = (intHighOrderWord << 16) + intLowOrderWord;
// The byte order of the result shall be reversed [Example: 0x64CEED7E becomes 7EEDCE64. end example],
// and that value shall be hashed as defined by the attribute values.
for (int intTemp = 0; intTemp < 4; intTemp++)
{
generatedKey[intTemp] = Convert.ToByte(((uint)(intCombinedkey & (0x000000FF << (intTemp * 8)))) >> (intTemp * 8));
}
}
StringBuilder sb = new StringBuilder();
for (int intTemp = 0; intTemp < 4; intTemp++)
{
sb.Append(Convert.ToString(generatedKey[intTemp], 16));
}
generatedKey = Encoding.Unicode.GetBytes(sb.ToString().ToUpper());
byte[] tmpArray1 = generatedKey;
byte[] tmpArray2 = arrSalt;
byte[] tempKey = new byte[tmpArray1.Length + tmpArray2.Length];
Buffer.BlockCopy(tmpArray2, 0, tempKey, 0, tmpArray2.Length);
Buffer.BlockCopy(tmpArray1, 0, tempKey, tmpArray2.Length, tmpArray1.Length);
generatedKey = tempKey;
int iterations = 100000;
HashAlgorithm sha1 = new SHA1Managed();
generatedKey = sha1.ComputeHash(generatedKey);
byte[] iterator = new byte[4];
for (int intTmp = 0; intTmp < iterations; intTmp++)
{
iterator[0] = Convert.ToByte((intTmp & 0x000000FF) >> 0);
iterator[1] = Convert.ToByte((intTmp & 0x0000FF00) >> 8);
iterator[2] = Convert.ToByte((intTmp & 0x00FF0000) >> 16);
iterator[3] = Convert.ToByte((intTmp & 0xFF000000) >> 24);
generatedKey = concatByteArrays(iterator, generatedKey);
generatedKey = sha1.ComputeHash(generatedKey);
}
documentProtection.Add(new XAttribute(XName.Get("cryptProviderType", DocX.w.NamespaceName), "rsaFull"));
documentProtection.Add(new XAttribute(XName.Get("cryptAlgorithmClass", DocX.w.NamespaceName), "hash"));
documentProtection.Add(new XAttribute(XName.Get("cryptAlgorithmType", DocX.w.NamespaceName), "typeAny"));
documentProtection.Add(new XAttribute(XName.Get("cryptAlgorithmSid", DocX.w.NamespaceName), "4")); // SHA1
documentProtection.Add(new XAttribute(XName.Get("cryptSpinCount", DocX.w.NamespaceName), iterations.ToString()));
documentProtection.Add(new XAttribute(XName.Get("hash", DocX.w.NamespaceName), Convert.ToBase64String(generatedKey)));
documentProtection.Add(new XAttribute(XName.Get("salt", DocX.w.NamespaceName), Convert.ToBase64String(arrSalt)));
settings.Root.AddFirst(documentProtection);
}
private byte[] concatByteArrays(byte[] array1, byte[] array2)
{
byte[] result = new byte[array1.Length + array2.Length];
Buffer.BlockCopy(array2, 0, result, 0, array2.Length);
Buffer.BlockCopy(array1, 0, result, array2.Length, array1.Length);
return result;
}
/// <summary>
/// Remove editing protection from this document.
/// </summary>
/// <example>
/// <code>
/// // Create a new document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Remove any editing restrictions that are imposed on this document.
/// document.RemoveProtection();
///
/// // Save the document.
/// document.Save();
/// }
/// </code>
/// </example>
/// <seealso cref="AddProtection(EditRestrictions)"/>
/// <seealso cref="GetProtectionType"/>
/// <seealso cref="isProtected"/>
public void RemoveProtection()
{
// Remove every node of type documentProtection.
settings.Descendants(XName.Get("documentProtection", DocX.w.NamespaceName)).Remove();
}
public PageLayout PageLayout
{
get
{
XElement sectPr = Xml.Element(XName.Get("sectPr", DocX.w.NamespaceName));
if (sectPr == null)
{
Xml.SetElementValue(XName.Get("sectPr", DocX.w.NamespaceName), string.Empty);
sectPr = Xml.Element(XName.Get("sectPr", DocX.w.NamespaceName));
}
return new PageLayout(this, sectPr);
}
}
/// <summary>
/// Returns a collection of Headers in this Document.
/// A document typically contains three Headers.
/// A default one (odd), one for the first page and one for even pages.
/// </summary>
/// <example>
/// <code>
/// // Create a document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Add header support to this document.
/// document.AddHeaders();
///
/// // Get a collection of all headers in this document.
/// Headers headers = document.Headers;
///
/// // The header used for the first page of this document.
/// Header first = headers.first;
///
/// // The header used for odd pages of this document.
/// Header odd = headers.odd;
///
/// // The header used for even pages of this document.
/// Header even = headers.even;
/// }
/// </code>
/// </example>
public Headers Headers
{
get
{
return headers;
}
}
private Headers headers;
/// <summary>
/// Returns a collection of Footers in this Document.
/// A document typically contains three Footers.
/// A default one (odd), one for the first page and one for even pages.
/// </summary>
/// <example>
/// <code>
/// // Create a document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Add footer support to this document.
/// document.AddFooters();
///
/// // Get a collection of all footers in this document.
/// Footers footers = document.Footers;
///
/// // The footer used for the first page of this document.
/// Footer first = footers.first;
///
/// // The footer used for odd pages of this document.
/// Footer odd = footers.odd;
///
/// // The footer used for even pages of this document.
/// Footer even = footers.even;
/// }
/// </code>
/// </example>
public Footers Footers
{
get
{
return footers;
}
}
private Footers footers;
/// <summary>
/// Should the Document use different Headers and Footers for odd and even pages?
/// </summary>
/// <example>
/// <code>
/// // Create a document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Add header support to this document.
/// document.AddHeaders();
///
/// // Get a collection of all headers in this document.
/// Headers headers = document.Headers;
///
/// // The header used for odd pages of this document.
/// Header odd = headers.odd;
///
/// // The header used for even pages of this document.
/// Header even = headers.even;
///
/// // Force the document to use a different header for odd and even pages.
/// document.DifferentOddAndEvenPages = true;
///
/// // Content can be added to the Headers in the same manor that it would be added to the main document.
/// Paragraph p1 = odd.InsertParagraph();
/// p1.Append("This is the odd pages header.");
///
/// Paragraph p2 = even.InsertParagraph();
/// p2.Append("This is the even pages header.");
///
/// // Save all changes to this document.
/// document.Save();
/// }// Release this document from memory.
/// </code>
/// </example>
public bool DifferentOddAndEvenPages
{
get
{
XDocument settings;
using (TextReader tr = new StreamReader(settingsPart.GetStream()))
settings = XDocument.Load(tr);
XElement evenAndOddHeaders = settings.Root.Element(w + "evenAndOddHeaders");
return evenAndOddHeaders != null;
}
set
{
XDocument settings;
using (TextReader tr = new StreamReader(settingsPart.GetStream()))
settings = XDocument.Load(tr);
XElement evenAndOddHeaders = settings.Root.Element(w + "evenAndOddHeaders");
if (evenAndOddHeaders == null)
{
if (value)
settings.Root.AddFirst(new XElement(w + "evenAndOddHeaders"));
}
else
{
if (!value)
evenAndOddHeaders.Remove();
}
using (TextWriter tw = new StreamWriter(new PackagePartStream(settingsPart.GetStream())))
settings.Save(tw);
}
}
/// <summary>
/// Should the Document use an independent Header and Footer for the first page?
/// </summary>
/// <example>
/// // Create a document.
/// using (DocX document = DocX.Create(@"Test.docx"))
/// {
/// // Add header support to this document.
/// document.AddHeaders();
///
/// // The header used for the first page of this document.
/// Header first = document.Headers.first;
///
/// // Force the document to use a different header for first page.
/// document.DifferentFirstPage = true;
///
/// // Content can be added to the Headers in the same manor that it would be added to the main document.
/// Paragraph p = first.InsertParagraph();
/// p.Append("This is the first pages header.");
///
/// // Save all changes to this document.
/// document.Save();
/// }// Release this document from memory.
/// </example>
public bool DifferentFirstPage
{
get
{
XElement body = mainDoc.Root.Element(w + "body");
XElement sectPr = body.Element(w + "sectPr");
if (sectPr != null)
{
XElement titlePg = sectPr.Element(w + "titlePg");
if (titlePg != null)
return true;
}
return false;
}
set
{
XElement body = mainDoc.Root.Element(w + "body");
XElement sectPr = null;
XElement titlePg = null;
if (sectPr == null)
body.Add(new XElement(w + "sectPr", string.Empty));
sectPr = body.Element(w + "sectPr");
titlePg = sectPr.Element(w + "titlePg");
if (titlePg == null)
{
if (value)
sectPr.Add(new XElement(w + "titlePg", string.Empty));
}
else
{
if (!value)
titlePg.Remove();
}
}
}
private Header GetHeaderByType(string type)
{
return (Header)GetHeaderOrFooterByType(type, true);
}
private Footer GetFooterByType(string type)
{
return (Footer)GetHeaderOrFooterByType(type, false);
}
private object GetHeaderOrFooterByType(string type, bool isHeader)
{
// Switch which handles either case Header\Footer, this just cuts down on code duplication.
string reference = "footerReference";
if (isHeader)
reference = "headerReference";
// Get the Id of the [default, even or first] [Header or Footer]
string Id =
(
from e in mainDoc.Descendants(XName.Get("body", DocX.w.NamespaceName)).Descendants()
where (e.Name.LocalName == reference) && (e.Attribute(w + "type").Value == type)
select e.Attribute(r + "id").Value
).LastOrDefault();
if (Id != null)
{
// Get the Xml file for this Header or Footer.
Uri partUri = mainPart.GetRelationship(Id).TargetUri;
// Weird problem with PackaePart API.
if (!partUri.OriginalString.StartsWith("/word/"))
partUri = new Uri("/word/" + partUri.OriginalString, UriKind.Relative);
// Get the Part and open a stream to get the Xml file.
PackagePart part = package.GetPart(partUri);
XDocument doc;
using (TextReader tr = new StreamReader(part.GetStream()))
{
doc = XDocument.Load(tr);
// Header and Footer extend Container.
Container c;
if (isHeader)
c = new Header(this, doc.Element(w + "hdr"), part);
else
c = new Footer(this, doc.Element(w + "ftr"), part);
return c;
}
}
// If we got this far something went wrong.
return null;
}
public List<Section> GetSections()
{
var allParas = Paragraphs;
var parasInASection = new List<Paragraph>();
var sections = new List<Section>();
foreach (var para in allParas)
{
var sectionInPara = para.Xml.Descendants().FirstOrDefault(s => s.Name.LocalName == "sectPr");
if (sectionInPara == null)
{
parasInASection.Add(para);
}
else
{
parasInASection.Add(para);
var section = new Section(Document, sectionInPara) { SectionParagraphs = parasInASection };
sections.Add(section);
parasInASection = new List<Paragraph>();
}
}
XElement body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
XElement baseSectionXml = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
var baseSection = new Section(Document, baseSectionXml) { SectionParagraphs = parasInASection };
sections.Add(baseSection);
return sections;
}
// Get the word\settings.xml part
internal PackagePart settingsPart;
internal PackagePart endnotesPart;
internal PackagePart footnotesPart;
internal PackagePart stylesPart;
internal PackagePart stylesWithEffectsPart;
internal PackagePart numberingPart;
internal PackagePart fontTablePart;
#region Internal variables defined foreach DocX object
// Object representation of the .docx
internal Package package;
// The mainDocument is loaded into a XDocument object for easy querying and editing
internal XDocument mainDoc;
internal XDocument settings;
internal XDocument endnotes;
internal XDocument footnotes;
internal XDocument styles;
internal XDocument stylesWithEffects;
internal XDocument numbering;
internal XDocument fontTable;
internal XDocument header1;
internal XDocument header2;
internal XDocument header3;
// A lookup for the Paragraphs in this document.
internal Dictionary<int, Paragraph> paragraphLookup = new Dictionary<int, Paragraph>();
// Every document is stored in a MemoryStream, all edits made to a document are done in memory.
internal MemoryStream memoryStream;
// The filename that this document was loaded from
internal string filename;
// The stream that this document was loaded from
internal Stream stream;
#endregion
internal DocX(DocX document, XElement xml)
: base(document, xml)
{
}
/// <summary>
/// Returns a list of Images in this document.
/// </summary>
/// <example>
/// Get the unique Id of every Image in this document.
/// <code>
/// // Load a document.
/// DocX document = DocX.Load(@"C:\Example\Test.docx");
///
/// // Loop through each Image in this document.
/// foreach (Novacode.Image i in document.Images)
/// {
/// // Get the unique Id which identifies this Image.
/// string uniqueId = i.Id;
/// }
///
/// </code>
/// </example>
/// <seealso cref="AddImage(string)"/>
/// <seealso cref="AddImage(Stream)"/>
/// <seealso cref="Paragraph.Pictures"/>
/// <seealso cref="Paragraph.InsertPicture"/>
public List<Image> Images
{
get
{
PackageRelationshipCollection imageRelationships = mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
if (imageRelationships.Count() > 0)
{
return
(
from i in imageRelationships
select new Image(this, i)
).ToList();
}
return new List<Image>();
}
}
/// <summary>
/// Returns a list of custom properties in this document.
/// </summary>
/// <example>
/// Method 1: Get the name, type and value of each CustomProperty in this document.
/// <code>
/// // Load Example.docx
/// DocX document = DocX.Load(@"C:\Example\Test.docx");
///
/// /*
/// * No two custom properties can have the same name,
/// * so a Dictionary is the perfect data structure to store them in.
/// * Each custom property can be accessed using its name.
/// */
/// foreach (string name in document.CustomProperties.Keys)
/// {
/// // Grab a custom property using its name.
/// CustomProperty cp = document.CustomProperties[name];
///
/// // Write this custom properties details to Console.
/// Console.WriteLine(string.Format("Name: '{0}', Value: {1}", cp.Name, cp.Value));
/// }
///
/// Console.WriteLine("Press any key...");
///
/// // Wait for the user to press a key before closing the Console.
/// Console.ReadKey();
/// </code>
/// </example>
/// <example>
/// Method 2: Get the name, type and value of each CustomProperty in this document.
/// <code>
/// // Load Example.docx
/// DocX document = DocX.Load(@"C:\Example\Test.docx");
///
/// /*
/// * No two custom properties can have the same name,
/// * so a Dictionary is the perfect data structure to store them in.
/// * The values of this Dictionary are CustomProperties.
/// */
/// foreach (CustomProperty cp in document.CustomProperties.Values)
/// {