public override void SaveToDocument(string destination, string documentName)
        {
            MainDocumentPart     mainPart = document.MainDocumentPart;
            DocumentSettingsPart documentSettingsPart1 = mainPart.DocumentSettingsPart;

            //
            AttachedTemplate attachedTemplate1 = new AttachedTemplate()
            {
                Id = "relationId1"
            };

            documentSettingsPart1.Settings.Append(attachedTemplate1);

            documentSettingsPart1.AddExternalRelationship(
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
                new Uri(TemplatePath, UriKind.Absolute),
                "relationId1");
            mainPart.Document.Save();

            document.Close();

            using (FileStream fs = new FileStream(Path.Combine(destination, documentName), FileMode.Create))
            {
#warning См. комментарий
                // Цитата со StackOverflow:
                // Use CopyTo instead, there is a bug in WriteTo which makes it fail to write the entire content of the buffer when the target stream does not support writing everything in one go.
                memory.WriteTo(fs);
            }

            memory.Close();
            IsDisposed = true;
        }
Exemple #2
0
        /// <summary>
        /// Protects the document.
        /// </summary>
        /// <param name="wordprocessingDocument">The wordprocessing document.</param>
        public void ProtectDocument(WordprocessingDocument wordprocessingDocument)
        {
            if (wordprocessingDocument == null)
            {
                throw new ArgumentNullException("wordprocessingDocument");
            }

            DocumentSettingsPart documentSettingsPart = wordprocessingDocument.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().FirstOrDefault();

            if (documentSettingsPart != null)
            {
                var documentProtection = documentSettingsPart.Settings.Elements <DocumentProtection>().FirstOrDefault();

                if (documentProtection != null)
                {
                    documentProtection.Enforcement = true;
                }
                else
                {
                    documentProtection = new DocumentProtection()
                    {
                        Edit = DocumentProtectionValues.Comments, Enforcement = true, CryptographicProviderType = CryptProviderValues.RsaFull, CryptographicAlgorithmClass = CryptAlgorithmClassValues.Hash, CryptographicAlgorithmType = CryptAlgorithmValues.TypeAny, CryptographicAlgorithmSid = 4, CryptographicSpinCount = (UInt32Value)100000U, Hash = "2krUoz1qWd0WBeXqVrOq81l8xpk=", Salt = "9kIgmDDYtt2r5U2idCOwMA=="
                    };
                    documentSettingsPart.Settings.Append(documentProtection);
                }
            }

            wordprocessingDocument.MainDocumentPart.Document.Save();
        }
Exemple #3
0
        public override void Save(string path)
        {
            MainDocumentPart     mainPart = document.MainDocumentPart;
            DocumentSettingsPart documentSettingsPart1 = mainPart.DocumentSettingsPart;

#if templates_old
            AttachedTemplate attachedTemplate1 = new AttachedTemplate()
            {
                Id = "relationId1"
            };
            documentSettingsPart1.Settings.Append(attachedTemplate1);

            // На заметку: узнать подробнее про External Relationships в структуре OpenXML.
            // Пэ Эс: можно (и даже нужно) заполнять фигней. Если подставлять реальный URI, может повесить ворд.
            documentSettingsPart1.AddExternalRelationship(
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
                new Uri(@"c:\foo\bar", UriKind.Absolute),
                "relationId1");
#endif

            mainPart.Document.Save();

            document.Close();

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                memory.WriteTo(fs);
            }
            memory.Close();
            IsDisposed = true;
        }
Exemple #4
0
        //.....................................................................
        /// <summary>
        ///
        /// </summary>
        /// <param name="settingsPART"></param>
        public static void Generate(DocumentSettingsPart SettingsPART)
        {
            OpenDocxSettingsPart openxml = new OpenDocxSettingsPart( );

            openxml.GenerateSettingsPart(SettingsPART);

            return;
        }
Exemple #5
0
        //public static void AddSettingsTable(WordprocessingDocument doc, List<CCOLElement> elements)
        //{
        //    Table table = new Table();
        //
        //    TableProperties props = new TableProperties(
        //        new TableBorders(
        //        new TopBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new BottomBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new LeftBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new RightBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new InsideHorizontalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 },
        //        new InsideVerticalBorder { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 1 }),
        //        new TableWidth() { Type = TableWidthUnitValues.Pct, Width = $"{100 * 50}" });
        //
        //    table.AppendChild(props);
        //
        //    AddRowToTable(
        //            table,
        //            new[] { "Type", "Naam", "Instelling", "Commentaar" },
        //            new[] { 14, 14, 14, 58 });
        //
        //    foreach (var e in elements)
        //    {
        //        AddRowToTable(
        //            table,
        //            new[] { e.Type.ToString(), e.Naam, e.Instelling.ToString(), e.Commentaar },
        //            new[] { 14, 14, 14, 58 });
        //    }
        //
        //    doc.MainDocumentPart.Document.Body.Append(new Paragraph(new Run(table)));
        //}



        public static void SetDirtyFlag(WordprocessingDocument doc)
        {
            DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            UpdateFieldsOnOpen   updateFields = new UpdateFieldsOnOpen();

            updateFields.Val = new OnOffValue(true);
            settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
            settingsPart.Settings.Save();
        }
Exemple #6
0
 private void CreateSettings()
 {
     if (_settings == null)
     {
         DocumentSettingsPart documentSettingsPart = _mainPart.AddNewPart <DocumentSettingsPart>();
         _settings = new Settings();
         documentSettingsPart.Settings = _settings;
     }
 }
        /*
         * function:judge document whether is set to evenandodd//判断是否奇数偶数页不同
         * true 表示设置了奇数偶数页不同
         */
        protected bool evenAndOddHeaders(MainDocumentPart Mpart)
        {
            DocumentSettingsPart dsp     = Mpart.DocumentSettingsPart;
            Settings             setting = dsp.Settings;

            if (setting.GetFirstChild <EvenAndOddHeaders>() == null)
            {
                return(false);
            }
            return(true);
        }
Exemple #8
0
        private static void GenerateDocumentSettingsPartContent(DocumentSettingsPart documentSettingsPart)
        {
            Settings settings = new Settings()
            {
                MCAttributes = MarkupCompatibilityAttributes
            };

            Schemas.AddNamespaceDeclarations(settings);

            documentSettingsPart.Settings = settings;
        }
Exemple #9
0
        /*
         * function:judge document whether is set to evenandodd
         * params:***
         */
        void evenAndOddHeaders(MainDocumentPart Mpart, XmlNode root, XmlDocument xmlDocx)
        {
            DocumentSettingsPart dsp     = Mpart.DocumentSettingsPart;
            Settings             setting = dsp.Settings;

            if (setting.GetFirstChild <EvenAndOddHeaders>() == null)
            {
                XmlElement xml = xmlDocx.CreateElement("Text");
                xml.InnerText = "论文应设置奇偶页不同";
                root.AppendChild(xml);
            }
        }
Exemple #10
0
        private static byte[] CreateWordDocument(FileInfo file, List <Tuple <string, string> > strings)
        {
            FileInfo template = file;

            //var template = @"~/docs/tmc.dotx";
            byte[] templateBytes = File.ReadAllBytes(template.FullName);

            using (var templateStream = new MemoryStream())
            {
                templateStream.Write(templateBytes, 0, templateBytes.Length);
                using (WordprocessingDocument document = WordprocessingDocument.Open(templateStream, true))
                {
                    // Change the document type to Document
                    document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

                    // Get the MainPart of the document
                    MainDocumentPart mainPart = document.MainDocumentPart;

                    // Get the Document Settings Part
                    DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;

                    foreach (var str in strings)
                    {
                        try
                        {
                            ReplaceBookmarkParagraphs(document, str.Item1, str.Item2);
                        }
                        catch (InvalidOperationException)
                        {
                            // ignore
                        }
                    }
                    // Create a new attachedTemplate and specify a relationship ID
                    //AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" };

                    // Append the attached template to the DocumentSettingsPart
                    //documentSettingPart1.Settings.Append(attachedTemplate1);

                    // Add an ExternalRelationShip of type AttachedTemplate.
                    // Specify the path of template and the relationship ID
                    //documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(template.FullName, UriKind.Absolute), "relationId1");

                    // Save the document
                    mainPart.Document.Save();
                }

                templateStream.Position = 0;
                var result = templateStream.ToArray();
                templateStream.Flush();

                return(result);
            }
        }
Exemple #11
0
        /// <summary>
        /// The field values in the word doc need to be update in the property settings object of the word doc. The questions
        /// have 'keys' which we are using with MappingsEnum to know how update with the value from the IntakeForms. Then we
        /// explicitly ask the user to verify the fields are to be updated when opening the word doc.
        /// </summary>
        /// <param name="intakeForms"></param>
        /// <param name="doc"></param>
        private void UpdateValuesInWordDocsCustomProperties(
            WordprocessingDocument doc,
            IntakeFormModel intakeForm,
            PatientModel patient,
            PhysicianModel physician,
            ICollection <SignatureModel> signatures)
        {
            // Get all question's with a key, then gather the value as all answers comma delimited
            var intakeFromKeys = intakeForm.Questions
                                 .Where(r => !string.IsNullOrEmpty(r.Key))
                                 .Select(y => new KeyValuePair <string, string>(y.Key.ToUpper(), y.Answers.Select(z => z.Text)
                                                                                .Aggregate((c, n) => $"{c},{n}"))).ToList();

            intakeFromKeys.AddRange(GetPatientKeys(patient));
            intakeFromKeys.AddRange(GetAllCodes(intakeForm));
            intakeFromKeys.AddRange(GetPhysicanKeys(physician));
            intakeFromKeys.AddRange(GetSignature(signatures.First())); // just use the first signature for now since IP/Creation should be identicalish
            intakeFromKeys.AddRange(GetDrNotes(intakeForm.PhysicianNotes ?? ""));

            //This will update all of the custom properties that are used in the word doc.
            //Again, the fields are update in the document settings, but the downloading user
            //will need to approve the update for any fields.

            //https://docs.microsoft.com/en-us/office/open-xml/how-to-set-a-custom-property-in-a-word-processing-document
            Properties properties = doc.CustomFilePropertiesPart.Properties;

            foreach (MappingEnums propertyEnum in Enum.GetValues(typeof(MappingEnums)))
            {
                var item = (CustomDocumentProperty)properties
                           .FirstOrDefault(x => ((CustomDocumentProperty)x).Name.Value.Equals(propertyEnum.ToString()));
                if (item != null)
                {
                    //If a key doesn't exist, you could see an empty value stuffed into the word doc
                    var val = intakeFromKeys.FirstOrDefault(x => x.Key == propertyEnum.ToString().ToUpper()).Value ?? "N/A";
                    item.VTLPWSTR = new VTLPWSTR(val);
                }
            }

            properties.Save();

            //The docx is using Custom Properties and above we are updating the custom property values,
            //however there is no way (that I have found) to programatically updated all of the fields
            //that are using the custom properties without requiring the downloader to
            DocumentSettingsPart settingsPart = doc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            var updateFields = new UpdateFieldsOnOpen
            {
                Val = new OnOffValue(true)
            };

            settingsPart.Settings.PrependChild(updateFields);
            settingsPart.Settings.Save();
            doc.Save();
        }
Exemple #12
0
        public void SetUpdateOnOpen(WordprocessingDocument xmlDoc)
        {
            //Open Word Setting File
            DocumentSettingsPart settingsPart = xmlDoc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();
            //Update Fields
            UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();

            updateFields.Val = new OnOffValue(true);

            settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
            settingsPart.Settings.Save();
        }
        public static WordprocessingDocument UpdatePropertiesOnOpening(this WordprocessingDocument wordDoc)
        {
            DocumentSettingsPart settingsPart = wordDoc.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();

            //Update Fields
            UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();

            updateFields.Val = new OnOffValue(true);

            settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);
            settingsPart.Settings.Save();

            return(wordDoc);
        }
Exemple #14
0
        public static void RemoveDataSourceSettingFromMergedDocument(WordprocessingDocument document)
        {
            // If the Document has settings remove them so the end user doesn't get prompted to use the data source
            DocumentSettingsPart settingsPart = document.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();

            var oxeSettings = settingsPart.Settings.FirstOrDefault(a => a.LocalName == "mailMerge");

            if (oxeSettings != null)
            {
                settingsPart.Settings.RemoveChild(oxeSettings);

                settingsPart.Settings.Save();
            }
        }
        private static void RemoveRsidInfoInSettings(WordprocessingDocument doc)
        {
            DocumentSettingsPart part = doc.MainDocumentPart.DocumentSettingsPart;

            if (part == null)
            {
                return;
            }

            XDocument settingsXDoc = part.GetXDocument();

            settingsXDoc.Descendants(W.rsids).Remove();
            part.PutXDocument();
        }
Exemple #16
0
        public static void InsertTemplateURI(this WordprocessingDocument document, string url)
        {
            MainDocumentPart mainPart = document.MainDocumentPart;
            var uri = new Uri(url);
            DocumentSettingsPart documentSettingsPart = mainPart.DocumentSettingsPart;
            ExternalRelationship relationship         = documentSettingsPart.AddExternalRelationship(
                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", uri);

            documentSettingsPart.Settings.Append(
                new DocumentFormat.OpenXml.Wordprocessing.AttachedTemplate()
            {
                Id = relationship.Id
            });
        }
        private static void AddSettingsToMainDocumentPart(MainDocumentPart part)
        {
            DocumentSettingsPart settingsPart = part.AddNewPart <DocumentSettingsPart>();

            settingsPart.Settings = new Settings(
                new Compatibility(
                    new CompatibilitySetting()
            {
                Name = new EnumValue <CompatSettingNameValues>(CompatSettingNameValues.CompatibilityMode),
                Val  = new StringValue("16"),
                Uri  = new StringValue("http://schemas.microsoft.com/office/word")
            }
                    )
                );
            settingsPart.Settings.Save();
        }
Exemple #18
0
        /// <summary>
        /// Unprotects the document.
        /// </summary>
        /// <param name="wordprocessingDocument">The wordprocessing document.</param>
        public void UnprotectDocument(WordprocessingDocument wordprocessingDocument)
        {
            if (wordprocessingDocument == null)
            {
                throw new ArgumentNullException("wordprocessingDocument");
            }

            DocumentSettingsPart documentSettingsPart = wordprocessingDocument.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().FirstOrDefault();

            if (documentSettingsPart != null)
            {
                var documentProtection = documentSettingsPart.Settings.Elements <DocumentProtection>().FirstOrDefault();

                if (documentProtection != null)
                {
                    documentProtection.Remove();
                }
            }

            List <OpenXmlLeafElement> permElements = new List <OpenXmlLeafElement>();

            foreach (var permStart in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants <PermStart>())
            {
                if (!permElements.Contains(permStart))
                {
                    permElements.Add(permStart);
                }
            }

            foreach (var permEnd in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants <PermEnd>())
            {
                if (!permElements.Contains(permEnd))
                {
                    permElements.Add(permEnd);
                }
            }

            foreach (var permElem in permElements)
            {
                if (permElem.Parent != null)
                {
                    permElem.Remove();
                }
            }

            wordprocessingDocument.MainDocumentPart.Document.Save();
        }
        /// <summary>
        /// Retrieves a document variable by its name
        /// </summary>
        /// <param name="name">The name of the document variable (case sensitive)</param>
        /// <param name="document">The wordprocessing document</param>
        /// <returns>The document variable if found, other wise it returns null</returns>
        public static DocumentVariable GetVariableByName(string name, WordprocessingDocument document)
        {
            // Get the document settings part
            DocumentSettingsPart documentSettings = document.MainDocumentPart.DocumentSettingsPart;
            // Get the settings element
            Settings settings = documentSettings.Settings;
            // Get the DocumentVariables element
            DocumentVariables variables = settings.Elements <DocumentVariables>().FirstOrDefault();

            // check if the variables are not null
            if (variables != null)
            {
                return(variables.Elements <DocumentVariable>().Where(v => v.Name == name)
                       .FirstOrDefault());
            }
            return(null);
        }
Exemple #20
0
        public static OpenXmlPowerToolsDocument Lock(WmlDocument doc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    //Finds the settings part
                    XDocument settingsDocument;
                    XElement  documentProtectionElement = null;
                    if (document.MainDocumentPart.DocumentSettingsPart == null)
                    {
                        //If settings part does not exist creates a new one
                        DocumentSettingsPart settingsPart = document.MainDocumentPart.AddNewPart <DocumentSettingsPart>();
                        settingsDocument = settingsPart.GetXDocument();
                        settingsDocument.Add(new XElement(W.settings,
                                                          new XAttribute(XNamespace.Xmlns + "w", W.w),
                                                          new XAttribute(XNamespace.Xmlns + "r", R.r)));
                    }
                    else
                    {
                        //If the settings part does exist looks if documentProtection has been included
                        settingsDocument          = document.MainDocumentPart.DocumentSettingsPart.GetXDocument();
                        documentProtectionElement = settingsDocument.Element(W.settings).Element(W.documentProtection);
                    }

                    //Creates the documentProtection element, or edits it if it exists
                    if (documentProtectionElement == null)
                    {
                        settingsDocument
                        .Element(W.settings)
                        .Add(
                            new XElement(W.documentProtection,
                                         new XAttribute(W.edit, "readOnly")
                                         )
                            );
                    }
                    else
                    {
                        documentProtectionElement.SetAttributeValue(W.edit, "readOnly");
                    }
                    document.MainDocumentPart.DocumentSettingsPart.PutXDocument();
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
        private WordTemplateModel GenerateDataMappingOxml(string TemplateFileLocation, WordTemplateModel model)
        {
            try
            {
                using (WordprocessingDocument document = WordprocessingDocument.Open(TemplateFileLocation, true))
                {
                    // Change the document type to Document
                    document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

                    // Get the MainPart of the document
                    MainDocumentPart mainPart = document.MainDocumentPart;

                    // Get the Document Settings Part
                    DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
                    OpenXmlElement[]     Enumerate            = mainPart.ContentControls().ToArray();
                    List <ModelField>    dataMapping          = new List <ModelField>();
                    for (int i = 0; i < Enumerate.Count(); i++)
                    {
                        OpenXmlElement cc      = Enumerate[i];
                        SdtProperties  props   = cc.Elements <SdtProperties>().FirstOrDefault();
                        Tag            tag     = props.Elements <Tag>().FirstOrDefault();
                        SdtAlias       alias   = props.Elements <SdtAlias>().FirstOrDefault();
                        string         title   = ((DocumentFormat.OpenXml.Wordprocessing.StringType)(alias)).Val;
                        string         tagName = tag.Val;

                        dataMapping.Add(new ModelField()
                        {
                            Key = title
                        });
                    }

                    model.DataMapping = dataMapping;
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(model);
        }
        void SetMailMergeSetting(WordprocessingDocument doc, DocumentSettingsPart settingPart, string udlPath, string query, string connectionString)
        {
            int mailmergecount = doc.MainDocumentPart.DocumentSettingsPart.Settings.Elements <XOPEN.Wordprocessing.MailMerge>().Count();

            if (mailmergecount != 1)
            {
                throw new ArgumentException("mailmergecount is not 1");
            }
            // Get the Document Settings Part

            var newUri = new Uri(udlPath);


            var mymerge = settingPart.Settings.Elements <XOPEN.Wordprocessing.MailMerge>().First();
            var myDataSourceReference = mymerge.DataSourceReference;

            if (myDataSourceReference != null)
            {
                var myOldRelationship = settingPart.GetExternalRelationship(myDataSourceReference.Id);
                if (myOldRelationship != null)
                {
                    settingPart.DeleteExternalRelationship(myOldRelationship);
                    settingPart.AddExternalRelationship(myOldRelationship.RelationshipType, newUri, myDataSourceReference.Id);
                }
            }
            if (mymerge.DataSourceObject != null && mymerge.DataSourceObject.SourceReference != null)
            {
                var myOldRelationship2 = settingPart.GetExternalRelationship(mymerge.DataSourceObject.SourceReference.Id);
                if (myOldRelationship2 != null)
                {
                    settingPart.DeleteExternalRelationship(myOldRelationship2);
                    settingPart.AddExternalRelationship(myOldRelationship2.RelationshipType, newUri, mymerge.DataSourceObject.SourceReference.Id);
                }
                if (mymerge.DataSourceObject.UdlConnectionString != null)
                {
                    mymerge.DataSourceObject.UdlConnectionString.Val = connectionString;
                }
            }
            mymerge.ConnectString.Val = connectionString;
            mymerge.Query.Val         = query;
        }
        void SetMacroPath(WordprocessingDocument doc, DocumentSettingsPart settingPart, string macroTemplatePath)
        {
            if (!String.IsNullOrEmpty(macroTemplatePath))
            {
                var hasMacros = doc.MainDocumentPart.DocumentSettingsPart.Settings.Elements <XOPEN.Wordprocessing.AttachedTemplate>().Count();

                var newUriMacr = new Uri(macroTemplatePath);
                if (hasMacros > 0)
                {
                    AttachedTemplate attachTemplate = doc.MainDocumentPart.DocumentSettingsPart.Settings.Elements <XOPEN.Wordprocessing.AttachedTemplate>().First();

                    var attachTemplateRelationship = settingPart.GetExternalRelationship(attachTemplate.Id);

                    // attachTemplateRelationship.Uri=  new Uri(macroTemplatePath, UriKind.Absolute);

                    if (attachTemplateRelationship != null)
                    {
                        settingPart.DeleteExternalRelationship(attachTemplateRelationship);
                        settingPart.AddExternalRelationship(attachTemplateRelationship.RelationshipType, newUriMacr, attachTemplate.Id);
                    }
                }
            }
        }
        private void Language(MainDocumentPart mainPart)
        {
            DocumentSettingsPart objDocumentSettingPart =
                mainPart.AddNewPart <DocumentSettingsPart>();

            objDocumentSettingPart.Settings = new Settings();
            Compatibility        objCompatibility        = new Compatibility();
            CompatibilitySetting objCompatibilitySetting =
                new CompatibilitySetting()
            {
                Name = CompatSettingNameValues.CompatibilityMode,
                Uri  = "http://schemas.microsoft.com/office/word",
                Val  = "14"
            };

            objCompatibility.Append(objCompatibilitySetting);
            ActiveWritingStyle aws = new ActiveWritingStyle()
            {
                Language = "es-MX"
            };

            objDocumentSettingPart.Settings.Append(objCompatibility);
            objDocumentSettingPart.Settings.Append(aws);
        }
        /// <summary>
        /// Adds the documentProtection element to a document
        /// </summary>
        public void AddDocumentProtectionElement()
        {
            //Finds the settings part
            XDocument settingsDocument;
            XElement  documentProtectionElement = null;

            if (parentDocument.Document.MainDocumentPart.DocumentSettingsPart == null)
            {
                //If settings part does not exist creates a new one
                DocumentSettingsPart settingsPart = parentDocument.Document.MainDocumentPart.AddNewPart <DocumentSettingsPart>();
                settingsDocument = parentDocument.GetXDocument(settingsPart);
                settingsDocument.Add(CreateEmptySettings().Root);
            }
            else
            {
                //If the settings part does exist looks if documentProtection has been included
                settingsDocument          = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart.DocumentSettingsPart);
                documentProtectionElement = settingsDocument.Element(ns + "settings").Element(ns + "documentProtection");
            }

            //Creates the documentProtection element, or edits it if it exists
            if (documentProtectionElement == null)
            {
                settingsDocument
                .Element(ns + "settings")
                .Add(
                    new XElement(ns + "documentProtection",
                                 new XAttribute(ns + "edit", "readOnly")
                                 )
                    );
            }
            else
            {
                documentProtectionElement.SetAttributeValue(ns + "edit", "readOnly");
            }
        }
        public static bool EvenOddHeadersAndFooters(this DocumentSettingsPart documentSettingsPart)
        {
            var hasElement = documentSettingsPart.Settings?.ChildsOfType <EvenAndOddHeaders>().Any() ?? false;

            return(hasElement);
        }
Exemple #27
0
        private void CreateParts(WordprocessingDocument document)
        {
            DocxBase.CurrentTitle = DocxServiceProvinceRes.Title;

            ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart <ExtendedFilePropertiesPart>("rId3");

            DocxBase.GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();

            GenerateMainDocumentPart1Content(mainDocumentPart1);

            FontTablePart fontTablePart1 = mainDocumentPart1.AddNewPart <FontTablePart>("rId13");

            DocxBase.GenerateFontTablePart1Content(fontTablePart1);

            StyleDefinitionsPart styleDefinitionsPart1 = mainDocumentPart1.AddNewPart <StyleDefinitionsPart>("rId3");

            DocxBase.GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);

            EndnotesPart endnotesPart1 = mainDocumentPart1.AddNewPart <EndnotesPart>("rId7");

            DocxBase.GenerateEndnotesPart1Content(endnotesPart1);

            FooterPart footerPart1 = mainDocumentPart1.AddNewPart <FooterPart>("rId12");

            DocxBase.GenerateFooterPart1Content(footerPart1);

            NumberingDefinitionsPart numberingDefinitionsPart1 = mainDocumentPart1.AddNewPart <NumberingDefinitionsPart>("rId2");

            DocxBase.GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);

            CustomXmlPart customXmlPart1 = mainDocumentPart1.AddNewPart <CustomXmlPart>("application/xml", "rId1");

            DocxBase.GenerateCustomXmlPart1Content(customXmlPart1);

            CustomXmlPropertiesPart customXmlPropertiesPart1 = customXmlPart1.AddNewPart <CustomXmlPropertiesPart>("rId1");

            DocxBase.GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1);

            FootnotesPart footnotesPart1 = mainDocumentPart1.AddNewPart <FootnotesPart>("rId6");

            DocxBase.GenerateFootnotesPart1Content(footnotesPart1);

            HeaderPart headerPart1 = mainDocumentPart1.AddNewPart <HeaderPart>("rId11");

            DocxBase.GenerateHeaderPart1Content(headerPart1);

            WebSettingsPart webSettingsPart1 = mainDocumentPart1.AddNewPart <WebSettingsPart>("rId5");

            DocxBase.GenerateWebSettingsPart1Content(webSettingsPart1);

            //ChartPart chartPart1 = mainDocumentPart1.AddNewPart<ChartPart>("rId10");
            //DocxBase.GenerateChartPart1Content(chartPart1);

            //EmbeddedPackagePart embeddedPackagePart1 = chartPart1.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");
            //DocxBase.GenerateEmbeddedPackagePart1Content(embeddedPackagePart1);

            //ChartColorStylePart chartColorStylePart1 = chartPart1.AddNewPart<ChartColorStylePart>("rId2");
            //DocxBase.GenerateChartColorStylePart1Content(chartColorStylePart1);

            //ChartStylePart chartStylePart1 = chartPart1.AddNewPart<ChartStylePart>("rId1");
            //DocxBase.GenerateChartStylePart1Content(chartStylePart1);

            DocumentSettingsPart documentSettingsPart1 = mainDocumentPart1.AddNewPart <DocumentSettingsPart>("rId4");

            DocxBase.GenerateDocumentSettingsPart1Content(documentSettingsPart1);

            //ChartPart chartPart2 = mainDocumentPart1.AddNewPart<ChartPart>("rId9");
            //DocxBase.GenerateChartPart2Content(chartPart2);

            //EmbeddedPackagePart embeddedPackagePart2 = chartPart2.AddNewPart<EmbeddedPackagePart>("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "rId3");
            //DocxBase.GenerateEmbeddedPackagePart2Content(embeddedPackagePart2);

            //ChartColorStylePart chartColorStylePart2 = chartPart2.AddNewPart<ChartColorStylePart>("rId2");
            //DocxBase.GenerateChartColorStylePart2Content(chartColorStylePart2);

            //ChartStylePart chartStylePart2 = chartPart2.AddNewPart<ChartStylePart>("rId1");
            //DocxBase.GenerateChartStylePart2Content(chartStylePart2);

            ThemePart themePart1 = mainDocumentPart1.AddNewPart <ThemePart>("rId14");

            DocxBase.GenerateThemePart1Content(themePart1);

            foreach (UsedHyperlink usedHyperlink in DocxBase.UsedHyperlinkList)
            {
                mainDocumentPart1.AddHyperlinkRelationship(new System.Uri(usedHyperlink.URL, System.UriKind.Absolute), true, usedHyperlink.Id.ToString());
            }

            DocxBase.SetPackageProperties(document);
        }
Exemple #28
0
        public static void Test_Header_01(bool header = false, bool footer = false, bool pageNumber = false)
        {
            SetDirectory();
            string file = "test_header_01.docx";

            Trace.WriteLine("create docx \"{0}\" using OXmlDoc", file);

            using (WordprocessingDocument doc = WordprocessingDocument.Create(zPath.Combine(_directory, file), WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                if (header || footer)
                {
                    // activate even and odd headers
                    DocumentSettingsPart documentSettingsPart = mainPart.AddNewPart <DocumentSettingsPart>();
                    Settings             settings             = new Settings();
                    // <w:evenAndOddHeaders />
                    settings.AppendChild(new EvenAndOddHeaders());
                    documentSettingsPart.Settings = settings;
                }

                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());


                Styles styles = Test_OpenXml_Creator.CreateStyles(mainPart);
                //styles.DocDefaults = Test_OXmlCreator.CreateDocDefaults();

                string headerStyleId = null;
                if (header)
                {
                    headerStyleId = "Header";
                    styles.Append(Test_OpenXml_Creator.CreateHeaderFooterStyle(headerStyleId));
                }

                string footerStyleId = null;
                if (footer)
                {
                    footerStyleId = "Footer";
                    styles.Append(Test_OpenXml_Creator.CreateHeaderFooterStyle(footerStyleId));
                }

                string defaultHeaderPartId = null;
                string firstHeaderPartId   = null;
                string evenHeaderPartId    = null;
                if (header)
                {
                    defaultHeaderPartId = Test_OpenXml_Creator.CreateHeader(mainPart, Test_OpenXml_Creator.CreateParagraph_01(headerStyleId, "Default header", tab: 1));
                    firstHeaderPartId   = Test_OpenXml_Creator.CreateHeader(mainPart, Test_OpenXml_Creator.CreateParagraph_01(headerStyleId, "First header", tab: 1));
                    evenHeaderPartId    = Test_OpenXml_Creator.CreateHeader(mainPart, Test_OpenXml_Creator.CreateParagraph_01(headerStyleId, "Even header", tab: 1));
                }

                string defaultFooterPartId = null;
                string firstFooterPartId   = null;
                string evenFooterPartId    = null;
                if (footer)
                {
                    OpenXmlCompositeElement element;
                    if (pageNumber)
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_PageNumber(footerStyleId, "Default footer");
                    }
                    else
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_01(footerStyleId, "Default footer", tab: 1);
                    }
                    defaultFooterPartId = Test_OpenXml_Creator.CreateFooter(mainPart, element);

                    if (pageNumber)
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_PageNumber(footerStyleId, "First footer");
                    }
                    else
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_01(footerStyleId, "First footer", tab: 1);
                    }
                    firstFooterPartId = Test_OpenXml_Creator.CreateFooter(mainPart, element);

                    if (pageNumber)
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_PageNumber(footerStyleId, "Even footer");
                    }
                    else
                    {
                        element = Test_OpenXml_Creator.CreateParagraph_01(footerStyleId, "Even footer", tab: 1);
                    }
                    evenFooterPartId = Test_OpenXml_Creator.CreateFooter(mainPart, element);
                }


                // for SectionProperties
                mainPart.Document.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
                //AddSection(body, defaultHeaderPartId, defaultFooterPartId, firstHeaderPartId, firstFooterPartId);
                SectionProperties sectionProperties = body.AppendChild(new SectionProperties());
                Test_OpenXml_Creator.SetSectionPage(sectionProperties);
                Test_OpenXml_Creator.SetSectionHeaders(sectionProperties, defaultHeaderPartId, defaultFooterPartId, firstHeaderPartId, firstFooterPartId, evenHeaderPartId, evenFooterPartId);
                //Test_OXmlCreator.SetSectionPageNumberType(sectionProperties, start: 1);

                //AddText(body, 200);
                body.Append(Test_OpenXml_Creator.CreateText_02(200));
            }
        }
Exemple #29
0
        private void SetupStyles()
        {
            WordprocessingCommentsPart commentsPart        = AddTemplatePart <WordprocessingCommentsPart>(this.document, CommentsStyleResource);
            EndnotesPart             endNotesPart          = AddTemplatePart <EndnotesPart>(this.document, EndNotesStyleResource);
            FontTablePart            fontTablePart         = AddTemplatePart <FontTablePart>(this.document, FontsTableStyleResource);
            FootnotesPart            footnotesPart         = AddTemplatePart <FootnotesPart>(this.document, FootNotesStyleResource);
            HeaderPart               headerPart            = AddTemplatePart <HeaderPart>(this.document, HeaderStyleResource);
            DocumentSettingsPart     settingsPart          = AddTemplatePart <DocumentSettingsPart>(this.document, SettingsStyleResource);
            StyleDefinitionsPart     styles                = AddTemplatePart <StyleDefinitionsPart>(this.document, StylesStyleResource);
            StylesWithEffectsPart    stylesWithEffectsPart = AddTemplatePart <StylesWithEffectsPart>(this.document, StylesWithEffectsStyleResource);
            WebSettingsPart          webSettingsPart       = AddTemplatePart <WebSettingsPart>(this.document, WebSettingsStyleResource);
            ThemePart                themePart             = AddTemplatePart <ThemePart>(this.document, ThemeStyleResource);
            NumberingDefinitionsPart numberingPart         = AddTemplatePart <NumberingDefinitionsPart>(this.document, NumberingStyleResource);

            // Initialize the comments manager with the comments part
            this.commentManager = new CommentManager(commentsPart.Comments);

            // Initialize the footer
            string     footerTitle      = this.implementationGuide.GetDisplayName();
            DateTime   footerDate       = this.implementationGuide.PublishDate != null ? this.implementationGuide.PublishDate.Value : DateTime.Now;
            string     footerDateString = footerDate.ToString("m");
            FooterPart newFooterPart    = this.document.MainDocumentPart.AddNewPart <FooterPart>();
            Footer     newFooter        = new Footer();
            Paragraph  pFooter          = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = "Footer"
            }));

            pFooter.Append(
                new Run(
                    new Text(footerTitle)),
                new Run(
                    new TabChar(),
                    new Text(footerDateString)
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new TabChar(),
                    new Text("Page ")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.Begin
            }),
                new Run(
                    new FieldCode(" PAGE ")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.Separate
            }),
                new Run(
                    new RunProperties(
                        new NoProof()),
                    new Text("54")),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.End
            }));
            newFooter.Append(pFooter);
            newFooterPart.Footer = newFooter;

            // Add numbering for templates
            foreach (Template cTemplate in this.templates)
            {
                NumberingInstance ni = new NumberingInstance(
                    new AbstractNumId()
                {
                    Val = 3
                })
                {
                    NumberID = GenerationConstants.BASE_TEMPLATE_INDEX + (int)cTemplate.Id
                };

                for (int i = 0; i < 9; i++)
                {
                    ni.Append(new LevelOverride(
                                  new StartOverrideNumberingValue()
                    {
                        Val = 1
                    })
                    {
                        LevelIndex = i
                    });
                }

                numberingPart.Numbering.Append(ni);
            }
        }
Exemple #30
0
        public static DocX CreateDocA(DocX template, JIUViewModel model, string source)
        {
            string sym = model.Sym.ToString();

            string[] SymStr   = sym.Split('/');
            string[] sym1     = SymStr.Skip(1).ToArray();
            string   Fsym     = String.Join("/", sym1);
            int      yearppos = 0;


            //document Language "Section"
            string Ftlang = "";

            Ftlang = Tlanguage(model.lang_ID);
            //ORiginal Language
            string Folang = "";
            // Folang = Olanguage1(model.Olang_ID);


            string FPname = "[Prepared By]";

            //Typist
            if (!String.IsNullOrEmpty(model.Pname))
            {
                //string[] arr = model.Pname.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                //FPname = "";
                //for (int x = 0; x < arr.Length-1; x++)
                //{

                //    FPname = FPname+ arr[x] +"\n";

                //}
                //int xs = arr.Length;
                //FPname = FPname + arr[xs-1];
                FPname = model.Pname.ToString();
            }
            //Novacode.Formatting prepared = new Novacode.Formatting();
            //prepared.Italic = true;
            //prepared.Bold = true;
            //prepared.Size=14;


            // template.ReplaceText("Pname", FPname,false,RegexOptions.None,prepared);

            //Agenda Title
            string FJtitle = "[Title]";

            if (!String.IsNullOrEmpty(model.JTitle))
            {
                FJtitle = model.JTitle.ToString();
            }
            ///
            //Year Jdate

            string structure = model.structure.ToString();

            string[] str    = structure.Split('/');
            string   FJdate = "[YEAR]";

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == "&")
                {
                    yearppos = i;
                    FJdate   = SymStr[i];
                }
            }

            //create barcode
            string Fbar = "";

            if (!String.IsNullOrEmpty(model.Gdoc))
            {
                Fbar = model.Gdoc.ToString();
                Fbar = "*" + Fbar + "*";
            }

            string gdoc   = "";
            string Fgdocf = "";

            if (!String.IsNullOrEmpty(model.Gdoc))
            {
                gdoc   = model.Gdoc.ToString();
                gdoc   = gdoc.Insert(2, "-");
                Fgdocf = gdoc;
            }



            DateTime xxx = DateTime.Now;



            template.AddCustomProperty(new CustomProperty("sym1", Fsym));

            template.AddCustomProperty(new CustomProperty("symh", sym));
            //template.AddCustomProperty(new CustomProperty("symh1", sym));
            //template.AddCustomProperty(new CustomProperty("symh2", sym));

            // template.ReplaceText(sym, sym, false, RegexOptions.IgnoreCase);



            template.AddCustomProperty(new CustomProperty("jdate", FJdate));
            //   template.ReplaceText("sdate", Fsdate, false, RegexOptions.IgnoreCase);


            template.AddCustomProperty(new CustomProperty("olang", Ftlang));
            template.AddCustomProperty(new CustomProperty("gdoc", gdoc));
            template.AddCustomProperty(new CustomProperty("gdoc1", gdoc));
            // template.ReplaceText("gdoc", gdoc, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("gdocf", Fgdocf));
            template.AddCustomProperty(new CustomProperty("test", Fgdocf));
            //template.AddCustomProperty(new CustomProperty("gdocf1", Fgdocf));
            //template.AddCustomProperty(new CustomProperty("gdocf2", Fgdocf));
            // template.ReplaceText("gdocf", Fgdocf, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("tlang", ""));
            // template.ReplaceText("tlang", Ftlang, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("jtitle", FJtitle));
            // template.ReplaceText("atitle", Fatitle, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("Pname", FPname));
            // template.ReplaceText("stitle", Fstitle, false, RegexOptions.IgnoreCase);



            template.AddCustomProperty(new CustomProperty("bar", Fbar));
            //   template.ReplaceText("bar", Fbar, false, RegexOptions.IgnoreCase);

            template.AddCustomProperty(new CustomProperty("Date-Generated", xxx));
            template.AddCustomProperty(new CustomProperty("Org", "JIU"));
            template.AddCustomProperty(new CustomProperty("Entity", "JIU"));
            template.AddCustomProperty(new CustomProperty("doctype", "Main"));
            template.AddCustomProperty(new CustomProperty("category", "Report"));

            using (WordprocessingDocument
                   document = WordprocessingDocument.Open(source, true))

            {
                DocumentSettingsPart settingsPart = document.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First();



                // Create object to update fields on open


                UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();

                updateFields.Val = new DocumentFormat.OpenXml.OnOffValue(true);



                // Insert object into settings part.


                settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields);

                settingsPart.Settings.Save();


                document.MainDocumentPart.Document.RemoveAllChildren <BookmarkStart>();
                document.MainDocumentPart.Document.RemoveAllChildren <BookmarkEnd>();
            }

            return(template);
        }