Для создания и редактирование документа word формата docx существует не мало библиотек, вот некоторые из них: GemBox, Aspose, WordGlue и DocX. Только последний является бесплатным, но к сожалению несет в себе некоторые ограничения, в общем эти ограничения возможно присутствуют и в других библиотеках.
К примеру дана задача, сгенерировать документ word с водяным знаком, и при этом, запретить удалять пользователям этот водяной знак, но пользователь должен иметь возможность изменять любой текст в документе. Нетривиальная задача, реализация которой с помощью вышеуказанных библиотек навряд ли возможна.
Для того, чтобы запретить пользователю удалять водяной знак необходимо защитить документ, а для того, чтобы дать возможность редактировать текст в документе, необходимо добавить области которые пользователь может редактировать.
Для работы с openxml понадобится библиотека DocumentFormat.OpenXml.dll, также в проект нужно добавить стандартную библиотеку WindowsBase.
Создание водяного знака
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 | using System.IO; using System.Linq; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Vml; using DocumentFormat.OpenXml.Vml.Office; using DocumentFormat.OpenXml.Vml.Wordprocessing; using DocumentFormat.OpenXml.Wordprocessing; using HorizontalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.HorizontalAnchorValues; using Lock = DocumentFormat.OpenXml.Vml.Office.Lock; using Path = DocumentFormat.OpenXml.Vml.Path; using VerticalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.VerticalAnchorValues; namespace WordUtils { class WordWatermark { public static void AddWatermarkInDoc(string fileName, string textWatermark) { byte[] sourceBytes = File.ReadAllBytes(fileName); MemoryStream inMemoryStream = new MemoryStream(); inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length); var doc = WordprocessingDocument.Open(inMemoryStream, true); AddWatermark(doc, textWatermark); doc.MainDocumentPart.Document.Save(); doc.Close(); doc.Dispose(); doc = null; using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { inMemoryStream.WriteTo(fileStream); } inMemoryStream.Close(); inMemoryStream.Dispose(); inMemoryStream = null; } static void AddWatermark(WordprocessingDocument doc, string textWatermark) { if (doc.MainDocumentPart.HeaderParts.Count() == 0) { doc.MainDocumentPart.DeleteParts(doc.MainDocumentPart.HeaderParts); var newHeaderPart = doc.MainDocumentPart.AddNewPart<HeaderPart>(); var rId = doc.MainDocumentPart.GetIdOfPart(newHeaderPart); var headerRef = new HeaderReference(); headerRef.Id = rId; var sectionProps = doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().LastOrDefault(); if (sectionProps == null) { sectionProps = new SectionProperties(); doc.MainDocumentPart.Document.Body.Append(sectionProps); } sectionProps.RemoveAllChildren<HeaderReference>(); sectionProps.Append(headerRef); newHeaderPart.Header = MakeHeader(); newHeaderPart.Header.Save(); } foreach (HeaderPart headerPart in doc.MainDocumentPart.HeaderParts) { var sdtBlock1 = new SdtBlock(); var sdtProperties1 = new SdtProperties(); var sdtId1 = new SdtId() { Val = 87908844 }; var sdtContentDocPartObject1 = new SdtContentDocPartObject(); var docPartGallery1 = new DocPartGallery() { Val = "Watermarks" }; var docPartUnique1 = new DocPartUnique(); sdtContentDocPartObject1.Append(docPartGallery1); sdtContentDocPartObject1.Append(docPartUnique1); sdtProperties1.Append(sdtId1); sdtProperties1.Append(sdtContentDocPartObject1); var sdtContentBlock1 = new SdtContentBlock(); var paragraph2 = new Paragraph() { RsidParagraphAddition = "00656E18", RsidRunAdditionDefault = "00656E18" }; var paragraphProperties2 = new ParagraphProperties(); var paragraphStyleId2 = new ParagraphStyleId() { Val = "Header" }; paragraphProperties2.Append(paragraphStyleId2); var run1 = new Run(); var runProperties1 = new RunProperties(); var noProof1 = new NoProof(); var languages1 = new Languages() { EastAsia = "zh-TW" }; runProperties1.Append(noProof1); runProperties1.Append(languages1); var picture1 = new Picture(); var shapetype1 = new Shapetype() { Id = "_x0000_t136", CoordinateSize = "21600,21600", OptionalNumber = 136, Adjustment = "10800", EdgePath = "m@7,l@8,m@5,21600l@6,21600e" }; var formulas1 = new Formulas(); var formula1 = new Formula() { Equation = "sum #0 0 10800" }; var formula2 = new Formula() { Equation = "prod #0 2 1" }; var formula3 = new Formula() { Equation = "sum 21600 0 @1" }; var formula4 = new Formula() { Equation = "sum 0 0 @2" }; var formula5 = new Formula() { Equation = "sum 21600 0 @3" }; var formula6 = new Formula() { Equation = "if @0 @3 0" }; var formula7 = new Formula() { Equation = "if @0 21600 @1" }; var formula8 = new Formula() { Equation = "if @0 0 @2" }; var formula9 = new Formula() { Equation = "if @0 @4 21600" }; var formula10 = new Formula() { Equation = "mid @5 @6" }; var formula11 = new Formula() { Equation = "mid @8 @5" }; var formula12 = new Formula() { Equation = "mid @7 @8" }; var formula13 = new Formula() { Equation = "mid @6 @7" }; var formula14 = new Formula() { Equation = "sum @6 0 @5" }; formulas1.Append(formula1); formulas1.Append(formula2); formulas1.Append(formula3); formulas1.Append(formula4); formulas1.Append(formula5); formulas1.Append(formula6); formulas1.Append(formula7); formulas1.Append(formula8); formulas1.Append(formula9); formulas1.Append(formula10); formulas1.Append(formula11); formulas1.Append(formula12); formulas1.Append(formula13); formulas1.Append(formula14); var path1 = new Path() { AllowTextPath = TrueFalseValue.FromBoolean(true), ConnectionPointType = ConnectValues.Custom, ConnectionPoints = "@9,0;@10,10800;@11,21600;@12,10800", ConnectAngles = "270,180,90,0" }; var textPath1 = new TextPath() { On = TrueFalseValue.FromBoolean(true), FitShape = TrueFalseValue.FromBoolean(true) }; var shapeHandles1 = new ShapeHandles(); var shapeHandle1 = new ShapeHandle() { Position = "#0,bottomRight", XRange = "6629,14971" }; shapeHandles1.Append(shapeHandle1); var lock1 = new Lock { Extension = ExtensionHandlingBehaviorValues.Edit, TextLock = TrueFalseValue.FromBoolean(true), ShapeType = TrueFalseValue.FromBoolean(true) }; shapetype1.Append(formulas1); shapetype1.Append(path1); shapetype1.Append(textPath1); shapetype1.Append(shapeHandles1); shapetype1.Append(lock1); var shape1 = new Shape() { Id = "PowerPlusWaterMarkObject357922611", Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", OptionalString = "_x0000_s2049", AllowInCell = TrueFalseValue.FromBoolean(true), FillColor = "silver", Stroked = TrueFalseValue.FromBoolean(false), Type = "#_x0000_t136" }; var fill1 = new Fill() { Opacity = ".5" }; TextPath textPath2 = new TextPath() { Style = "font-family:\"Calibri\";font-size:1pt", String = textWatermark }; var textWrap1 = new TextWrap() { AnchorX = HorizontalAnchorValues.Margin, AnchorY = VerticalAnchorValues.Margin }; shape1.Append(fill1); shape1.Append(textPath2); shape1.Append(textWrap1); picture1.Append(shapetype1); picture1.Append(shape1); run1.Append(runProperties1); run1.Append(picture1); paragraph2.Append(paragraphProperties2); paragraph2.Append(run1); sdtContentBlock1.Append(paragraph2); sdtBlock1.Append(sdtProperties1); sdtBlock1.Append(sdtContentBlock1); headerPart.Header.Append(sdtBlock1); headerPart.Header.Save(); //break; } } static Header MakeHeader() { var header = new Header(); var paragraph = new Paragraph(); var run = new Run(); var text = new Text(); text.Text = ""; run.Append(text); paragraph.Append(run); header.Append(paragraph); return header; } } } |
В метод AddWatermarkInDoc передается путь к файлу и текст, который будет в водяном знаке.
По необходимости можно изменить прозрачность, сделать обводку.
Для этого нужно поменять в коде для прозрачности строка
var fill1 = new Fill() { Opacity = ".5" };
и для обводки вместо
Stroked = TrueFalseValue.FromBoolean(false) написать
Stroked = TrueFalseValue.FromBoolean(true).
Защита документа
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 | using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; namespace WordUtils { class ProtectWord { static int[] InitialCodeArray = { 0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3 }; static 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} }; private static 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; } public static void AddProtectionInDoc(string fileName, string strPassword) { byte[] sourceBytes = File.ReadAllBytes(fileName); MemoryStream inMemoryStream = new MemoryStream(); inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length); var doc = WordprocessingDocument.Open(inMemoryStream, true); ApplyDocumentProtection(doc, strPassword); doc.MainDocumentPart.Document.Save(); doc.Close(); doc.Dispose(); doc = null; using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { inMemoryStream.WriteTo(fileStream); } inMemoryStream.Close(); inMemoryStream.Dispose(); inMemoryStream = null; } // Main implementation private static void ApplyDocumentProtection(WordprocessingDocument wdDocument, string strPassword) { // 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)) { // Truncate the password to 15 characters strPassword = strPassword.Substring(0, Math.Min(strPassword.Length, intMaxPasswordLength)); // Construct a new NULL-terminated string consisting of single-byte characters: // -- > Get the single-byte values by iterating through the Unicode characters of the truncated Password. // --> For each character, if the low byte is not equal to 0, take it. Otherwise, take the high byte. 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); } // Compute the high-order word of the new key: // --> Initialize from the initial code array (see below), depending on the strPassword’s length. int intHighOrderWord = InitialCodeArray[arrByteChars.Length - 1]; // --> For each character in the strPassword: // --> For every bit in the character, starting with the least significant and progressing to (but excluding) // the most significant, if the bit is set, XOR the key’s high-order word with the corresponding word from // the Encryption Matrix 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]; } } } // Compute the low-order word of the new key: // Initialize with 0 int intLowOrderWord = 0; // For each character in the strPassword, going backwards for (int intLoopChar = arrByteChars.Length - 1; intLoopChar >= 0; intLoopChar--) { // low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR character intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars[intLoopChar]; } // Lastly,low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR strPassword length XOR 0xCE4B. 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)); } } // Implementation Notes List: // --> In this third stage, the reversed byte order legacy hash from the second stage shall be converted to Unicode hex // --> string representation 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()); // Implementation Notes List: //Word appends the binary form of the salt attribute and not the base64 string representation when hashing // Before calculating the initial hash, you are supposed to prepend (not append) the salt to the key 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; // Iterations specifies the number of times the hashing function shall be iteratively run (using each // iteration's result as the input for the next iteration). int iterations = 50000; // Implementation Notes List: //Word requires that the initial hash of the password with the salt not be considered in the count. // The initial hash of salt + key is not included in the iteration count. HashAlgorithm sha1 = new SHA1Managed(); generatedKey = sha1.ComputeHash(generatedKey); byte[] iterator = new byte[4]; for (int intTmp = 0; intTmp < iterations; intTmp++) { //When iterating on the hash, you are supposed to append the current iteration number. 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); } // Apply the element DocumentProtection documentProtection = new DocumentProtection(); documentProtection.Edit = DocumentProtectionValues.ReadOnly; OnOffValue docProtection = new OnOffValue(true); documentProtection.Enforcement = docProtection; documentProtection.CryptographicAlgorithmClass = CryptAlgorithmClassValues.Hash; documentProtection.CryptographicProviderType = CryptProviderValues.RsaFull; documentProtection.CryptographicAlgorithmType = CryptAlgorithmValues.TypeAny; documentProtection.CryptographicAlgorithmSid = 4; // SHA1 // The iteration count is unsigned UInt32Value uintVal = new UInt32Value(); uintVal.Value = (uint)iterations; documentProtection.CryptographicSpinCount = uintVal; documentProtection.Hash = Convert.ToBase64String(generatedKey); documentProtection.Salt = Convert.ToBase64String(arrSalt); // if protection in current document is exist then delete it DocumentProtection existingDocumentProtection = wdDocument.MainDocumentPart.DocumentSettingsPart.Settings.Descendants<DocumentProtection>().FirstOrDefault(); if (existingDocumentProtection != null) { existingDocumentProtection.Remove(); } wdDocument.MainDocumentPart.DocumentSettingsPart.Settings.AppendChild(documentProtection); wdDocument.MainDocumentPart.DocumentSettingsPart.Settings.Save(); } } } |
В метод AddProtectionInDoc передаем путь к файлу и пароль.
Данный код создаст защиту документа, которую можно будет отключить только по паролю.
Добавление в защищенный элемент области, разрешенные для редактирования
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 | // for all text foreach (var text in body.Descendants<Text>()) { PermStart newPermStart = new PermStart(); newPermStart.Id = id; newPermStart.EditorGroup = RangePermissionEditingGroupValues.Everyone; text.InsertBeforeSelf(newPermStart); PermEnd newPermEnd = new PermEnd(); newPermEnd.Id = id++; text.InsertAfterSelf(newPermEnd); } // for all table var paras = body.Elements<Table>(); foreach (var para in paras) { PermStart newPermStart = new PermStart(); newPermStart.Id = id; newPermStart.EditorGroup = RangePermissionEditingGroupValues.Everyone; para.InsertBeforeSelf(newPermStart); PermEnd newPermEnd = new PermEnd(); newPermEnd.Id = id++; para.InsertAfterSelf(newPermEnd); } wdDocument.MainDocumentPart.Document.Save(); // for headers foreach (HeaderPart headerPart in wdDocument.MainDocumentPart.HeaderParts) { foreach (var text in headerPart.RootElement.Descendants<Text>()) { PermStart newPermStart = new PermStart(); newPermStart.Id = id; newPermStart.EditorGroup = RangePermissionEditingGroupValues.Everyone; text.InsertBeforeSelf(newPermStart); PermEnd newPermEnd = new PermEnd(); newPermEnd.Id = id++; text.InsertAfterSelf(newPermEnd); } headerPart.Header.Save(); } foreach (FooterPart footerPart in wdDocument.MainDocumentPart.FooterParts) { foreach (var text in footerPart.RootElement.Descendants<Text>()) { PermStart newPermStart = new PermStart(); newPermStart.Id = id; newPermStart.EditorGroup = RangePermissionEditingGroupValues.Everyone; text.InsertBeforeSelf(newPermStart); PermEnd newPermEnd = new PermEnd(); newPermEnd.Id = id++; text.InsertAfterSelf(newPermEnd); } footerPart.Footer.Save(); } |
Первая половина кода создает разрешенные области в самом документе для текстовых фрагментов и таблиц.
Вторая половина добавляет разрешенные области в колонтитулы.
Yes, you are right; the demand for app developers continuously rises as the tech world evolves and businesses become increasingly reliant on technology. A developer's income depends on the role and the software they are working on. You should check out
ОтветитьУдалитьEiliana.com; they showcase your skills to the right people and hire app developers.