/// <summary>
        /// Initializes a new instance of the OpenXmlPartReader class using the supplied OpenXmlPart class.
        /// </summary>
        /// <param name="openXmlPart">The OpenXmlPart to read.</param>
        public OpenXmlPartReader(OpenXmlPart openXmlPart)
            : base()
        {
            if (openXmlPart is null)
            {
                throw new ArgumentNullException(nameof(openXmlPart));
            }

            _xmlReader = CreateReader(openXmlPart.GetStream(FileMode.Open), true, openXmlPart.MaxCharactersInPart, ignoreWhitespace: true, out _standalone, out _encoding);
        }
Esempio n. 2
0
 public void AddContentPartRelTypeResourceIdTupple(OpenXmlPart contentPart, string relationshipType, string relationshipId)
 {
     ContentPartRelTypeIdList.Add(
         new ContentPartRelTypeIdTuple
     {
         ContentPart      = contentPart,
         RelationshipType = relationshipType,
         RelationshipId   = relationshipId
     });
 }
 public ImageData(OpenXmlPart contentPart, ImagePart part)
 {
     ContentType = part.ContentType;
     ContentPart = contentPart;
     using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))
     {
         Image = new byte[s.Length];
         s.Read(Image, 0, (int)s.Length);
     }
 }
        private static void AssertBinaryContentEquals(OpenXmlPart part, byte[] expected)
        {
            using (Stream stream = part.GetStream(FileMode.Open))
            {
                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);

                Assert.Equal(expected, buffer);
            }
        }
Esempio n. 5
0
        protected NestedWordDocumentContainer(string identifier, WordprocessingDocument document)
        {
            this.Identifier       = identifier;
            this.mainWordDocument = document;
            this.document         = this.GetPart();

            this.MainDocumentPart = this.LoadPart(this.document);
            this.NumberingPart    = this.LoadPart(document.MainDocumentPart.NumberingDefinitionsPart);
            this.StylesPart       = this.LoadPart(document.MainDocumentPart.StyleDefinitionsPart);
        }
 private static void GenerateImagePart(OpenXmlPart part,
                                       byte[] imageFileBytes)
 {
     // Write the contents of the image to the ImagePart.
     using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
     {
         writer.Write(imageFileBytes);
         writer.Flush();
     }
 }
        private static List <ComparisonUnitAtom> CreateComparisonUnitAtomListInternal(
            OpenXmlPart part,
            XElement contentParent,
            WmlComparerSettings settings)
        {
            var comparisonUnitAtomList = new List <ComparisonUnitAtom>();

            CreateComparisonUnitAtomListRecurse(part, contentParent, comparisonUnitAtomList, settings);
            return(comparisonUnitAtomList);
        }
        protected NestedWordDocumentContainer(string identifier, WordprocessingDocument document)
        {
            Identifier        = identifier;
            _mainWordDocument = document;
            _document         = GetPart();

            MainDocumentPart = LoadPart(_document);
            NumberingPart    = LoadPart(document.MainDocumentPart.NumberingDefinitionsPart);
            StylesPart       = LoadPart(document.MainDocumentPart.StyleDefinitionsPart);
        }
        public static XDocument GetHeader(WordprocessingDocument document, HeaderType type, int sectionIndex)
        {
            OpenXmlPart header = GetHeaderPart(document, type, sectionIndex);

            if (header != null)
            {
                return(header.GetXDocument());
            }
            return(null);
        }
        /// <summary>
        /// Initializes a new instance of the OpenXmlPartRootElement class using the supplied OpenXmlPart.
        /// </summary>
        /// <param name="openXmlPart">The OpenXmlPart class.</param>
        protected OpenXmlPartRootElement(OpenXmlPart openXmlPart)
        {
            if (openXmlPart == null)
            {
                throw new ArgumentNullException("openXmlPart");
            }

            this._elementContext = new OpenXmlElementContext();
            LoadFromPart(openXmlPart);
        }
        /// <summary>
        /// Initializes a new instance of the OpenXmlPartRootElement class using the supplied OpenXmlPart.
        /// </summary>
        /// <param name="openXmlPart">The OpenXmlPart class.</param>
        protected OpenXmlPartRootElement(OpenXmlPart openXmlPart)
        {
            if (openXmlPart == null)
            {
                throw new ArgumentNullException("openXmlPart");
            }

            this._elementContext = new OpenXmlElementContext();
            LoadFromPart(openXmlPart);
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the OpenXmlPartReader class using the supplied OpenXmlPart and Boolean values.
        /// </summary>
        /// <param name="openXmlPart">The OpenXmlPart to read.</param>
        /// <param name="readMiscNodes">Specify false to indicate to the reader to skip all miscellaneous nodes. The default value is false.</param>
        public OpenXmlPartReader(OpenXmlPart openXmlPart, bool readMiscNodes)
            : this(readMiscNodes)
        {
            if (openXmlPart == null)
            {
                throw new ArgumentNullException(nameof(openXmlPart));
            }

            _xmlReader = CreateReader(openXmlPart.GetStream(FileMode.Open), true, openXmlPart.MaxCharactersInPart, out _standalone, out _encoding);
        }
        protected OpenXmlPartRootElement(OpenXmlPart openXmlPart)
        {
            if (openXmlPart is null)
            {
                throw new ArgumentNullException(nameof(openXmlPart));
            }

            RootElementContext = new OpenXmlElementContext();
            LoadFromPart(openXmlPart);
        }
Esempio n. 14
0
        private void ValidatePart(OpenXmlPart part, ValidationContext context)
        {
            // if the part is not defined in the specified version, then do not validate the content.
            if (!part.IsInVersion(_cache.Version))
            {
                return;
            }

            /*******************
            * DOM traversal is not performance bottleneck.
            * Is this the good way that we separate the schema validation and the semantics validation?
            *******************/

            try
            {
                // Must be called before the call to PartRootElement { get; }
                bool partRootElementLoaded = part.IsRootElementLoaded;

                // Schema validation
                using (context.Stack.Push(part: part, element: part.PartRootElement))
                {
                    var lastErrorCount = context.Errors.Count;

                    if (part.PartRootElement != null)
                    {
                        _schemaValidator.Validate(context);

                        // TODO: Is this needed? It's set 8 lines up
                        using (context.Stack.Push(element: part.PartRootElement))
                        {
                            context.Events.OnPartValidationStarted(context);
                            _semanticValidator.Validate(context);
                        }
                    }

                    if (!partRootElementLoaded && context.Errors.Count == lastErrorCount)
                    {
                        // No new errors in this part. Release the DOM to GC memory.
                        part.SetPartRootElementToNull();
                    }
                }
            }
            catch (System.Xml.XmlException e)
            {
                var errorInfo = new ValidationErrorInfo
                {
                    ErrorType   = ValidationErrorType.Schema,
                    Id          = "ExceptionError",
                    Part        = part,
                    Description = SR.Format(ValidationResources.ExceptionError, e.Message),
                };

                context.AddError(errorInfo);
            }
        }
Esempio n. 15
0
        public static void TransformPartToSingleCharacterRuns(OpenXmlPart part)
        {
            // After transforming to single character runs, Rsid info will be invalid, so
            // remove from the part.
            XElement root    = part.GetXElement();
            var      newRoot = (XElement)RemoveRsidTransform(root);

            newRoot = (XElement)SingleCharacterRunTransform(newRoot);
            root.ReplaceWith(newRoot);
            part.PutXElement();
        }
Esempio n. 16
0
        private static PdfRendererVisitor InterpretDocument(OpenXmlPart openXmlPart, PdfDocumentContext documentContext,
                                                            object model = null)
        {
            var interpreterContext = new InterpreterContext();
            var visitor            = new PdfRendererVisitor(interpreterContext, documentContext, model);
            var pdfInterpreter     = new PdfRendererInterpreter(interpreterContext, visitor);

            documentContext.Images = GetImages(openXmlPart);
            pdfInterpreter.Interpret(openXmlPart.RootElement);
            return(visitor);
        }
Esempio n. 17
0
        /// <summary>
        /// Returns the <see cref="OpenXmlPart" />'s root element <see cref="XNamespace" />.
        /// </summary>
        /// <param name="part">The part.</param>
        /// <returns>The namespace.</returns>
        public static XNamespace GetRootNamespace(this OpenXmlPart part)
        {
            if (part == null)
            {
                throw new ArgumentNullException("part");
            }

            var root = part.GetRootElement();

            return(root != null ? root.Name.Namespace : null);
        }
        /// <summary>
        /// Throws if the <see cref="OpenXmlPart"/> is not supported in the given version
        /// </summary>
        /// <param name="version">Version to check</param>
        /// <param name="part">Part to validate</param>
        public static void ThrowIfNotInVersion(this FileFormatVersions version, OpenXmlPart part)
        {
            version.ThrowExceptionIfFileFormatNotSupported(nameof(version));

            if (!part.IsInVersion(version))
            {
                var message = string.Format(CultureInfo.CurrentCulture, ExceptionMessages.PartIsNotInOfficeVersion, version.GetOfficeYear());

                throw new InvalidOperationException(message);
            }
        }
Esempio n. 19
0
        public static bool IsSupportedPart(OpenXmlPart part)
        {
            bool isSupported = false;

            isSupported = part is SlidePart;
            //|| element is Wordproc.Picture
            //|| element is Wordproc.Drawing
            //|| element is Wordproc.Table;

            return(isSupported);
        }
        private static void MergeCommentsInPart(OpenXmlPart part1, OpenXmlPart part2,
                                                OpenXmlPart destinationPart, XDocument commentsPartXDoc)
        {
            XDocument xdoc1 = part1.GetXDocument();
            XDocument xdoc2 = part2.GetXDocument();

            XElement newRootElement = (XElement)MergeElementTransform(xdoc1.Root, xdoc2.Root,
                                                                      commentsPartXDoc);

            destinationPart.PutXDocument(new XDocument(newRootElement));
        }
Esempio n. 21
0
        public void LoadAttributeTest()
        {
            using (var stream = GetStream(TestFiles.Mcdoc, true))
            {
                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement actual;
                    actual = target.RootElement;

                    Assert.NotNull(actual.MCAttributes.Ignorable);

                    // get attribute, no exception thrown
                    OpenXmlAttribute attr = actual.GetAttribute("Ignorable", AlternateContent.MarkupCompatibilityNamespace);
                    Assert.Equal("w14 wp14", attr.Value);

                    var list = actual.GetAttributes();
                    Assert.True(list.Contains(attr));

                    // set attribute
                    actual.MCAttributes = null;

                    actual.FirstChild.MCAttributes = new MarkupCompatibilityAttributes();
                    actual.FirstChild.MCAttributes.PreserveAttributes = "w14:editId";
                    actual.FirstChild.SetAttribute(new OpenXmlAttribute("mc:PreserveElements", AlternateContent.MarkupCompatibilityNamespace, "w14:para"));

                    actual.FirstChild.FirstChild.MCAttributes           = new MarkupCompatibilityAttributes();
                    actual.FirstChild.FirstChild.MCAttributes.Ignorable = "w14";
                    actual.FirstChild.FirstChild.RemoveAllChildren();

                    actual.Save();
                }

                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement actual;
                    actual = target.RootElement;

                    Assert.Null(actual.MCAttributes);

                    Assert.NotNull(actual.FirstChild.MCAttributes.PreserveAttributes);

                    Assert.True(actual.FirstChild.HasChildren);

                    // get attribute, no exception thrown
                    OpenXmlAttribute attr = actual.FirstChild.GetAttribute("PreserveAttributes", AlternateContent.MarkupCompatibilityNamespace);
                    Assert.Equal("w14:editId", attr.Value);

                    var list = actual.FirstChild.GetAttributes();
                    Assert.True(list.Contains(attr));
                }
            }
        }
Esempio n. 22
0
        public static void PutXDocument(this OpenXmlPart part)
        {
            XDocument partXDocument = part.GetXDocument();

            if (partXDocument != null)
            {
                using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write))
                    using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
                        partXDocument.Save(partXmlWriter);
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Serializes the XDocument back into the package.
 /// </summary>
 /// <param name="part">The document part.</param>
 /// <param name="xdoc">The <see cref="XDocument" />.</param>
 public static void PutXDocument(this OpenXmlPart part, XDocument xdoc)
 {
     if (xdoc != null)
     {
         using (Stream stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite))
             using (XmlWriter partWriter = XmlWriter.Create(stream))
             {
                 xdoc.Save(partWriter);
             }
     }
 }
Esempio n. 24
0
        /// <summary>
        /// Save the xml document to the openxml part.
        /// </summary>
        /// <param name="part">The openxml part to save</param>
        protected void SaveXDocument(OpenXmlPart part)
        {
            XDocument xdoc = GetXDocument(part);

            if (xdoc != null)
            {
                // Serialize the XDocument object back to the package.
                using (XmlWriter xmlWriter = XmlWriter.Create(part.GetStream(FileMode.Create, FileAccess.ReadWrite)))
                    xdoc.Save(xmlWriter);
            }
        }
Esempio n. 25
0
 private void GenerateCoreFilePropertiesPart(OpenXmlPart part)
 {
     System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(part.GetStream(), System.Text.Encoding.UTF8);
     writer.WriteRaw(
         string.Format(
             "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><dc:creator>{0}</dc:creator><cp:lastModifiedBy>{0}</cp:lastModifiedBy><dcterms:created xsi:type=\"dcterms:W3CDTF\">{1:s}Z</dcterms:created><dcterms:modified xsi:type=\"dcterms:W3CDTF\">{1:s}Z</dcterms:modified></cp:coreProperties>",
             GetCreatingApplicationName(),
             DateTime.Now));
     writer.Flush();
     writer.Close();
 }
Esempio n. 26
0
        public static void TransformPartToSingleCharacterRuns(OpenXmlPart part)
        {
            // After transforming to single character runs, Rsid info will be invalid, so
            // remove from the part.
            XDocument xDoc    = part.GetXDocument();
            XElement  newRoot = (XElement)RemoveRsidTransform(xDoc.Root);

            newRoot = (XElement)SingleCharacterRunTransform(newRoot);
            xDoc.Elements().First().ReplaceWith(newRoot);
            part.PutXDocument();
        }
Esempio n. 27
0
        private static string GetSpreadsheetId(OpenXmlPart chartPart)
        {
            string   id      = null;
            XElement extData = chartPart.GetXDocument().Descendants(C.externalData).FirstOrDefault();

            if (extData?.Attribute(R.id) != null)
            {
                id = extData.Attribute(R.id)?.Value;
            }
            return(id);
        }
Esempio n. 28
0
        /// <summary>
        /// Replace the parser tags in docx document
        /// </summary>
        /// <param name="oxp">OpenXmlPart object</param>
        /// <param name="dct">Dictionary contains parser tags to replace</param>
        private static void parse(OpenXmlPart oxp, Dictionary <string, string> dct)
        {
            string xmlString = null;

            using (StreamReader sr = new StreamReader(oxp.GetStream())) { xmlString = sr.ReadToEnd(); }
            foreach (string key in dct.Keys)
            {
                xmlString = xmlString.Replace("[$" + key + "$]", dct[key]);
            }
            using (StreamWriter sw = new StreamWriter(oxp.GetStream(FileMode.Create))) { sw.Write(xmlString); }
        }
 async private static Task WriteXmlToPartAsync(OpenXmlPart openXmlPart, XElement element)
 {
     using (var xmlTextWriter = new XmlTextWriter(openXmlPart.GetStream(), Encoding.UTF8))
     {
         xmlTextWriter.Formatting = Formatting.Indented;
         xmlTextWriter.WriteStartDocument();
         element.WriteTo(xmlTextWriter);
         xmlTextWriter.WriteEndDocument();
         xmlTextWriter.Flush();
     }
 }
Esempio n. 30
0
        private void ValidatePart(OpenXmlPart part, ValidationContext context)
        {
            // if the part is not defined in the specified version, then do not validate the content.
            if (!part.IsInVersion(_validationSettings.FileFormat))
            {
                return;
            }

            /*******************
            * DOM traversal is not performance bottleneck.
            * Is this the good way that we separate the schema validation and the semantics validation?
            *******************/

            try
            {
                // Must be called before the call to PartRootElement { get; }
                bool partRootElementLoaded = part.IsRootElementLoaded;

                // schema validation
                context.Part    = part;
                context.Element = part.PartRootElement;

                var lastErrorCount = context.Errors.Count;

                if (part.PartRootElement != null)
                {
                    _schemaValidator.Validate(context);

                    context.Element = part.PartRootElement;
                    _semanticValidator.ClearConstraintState(SemanticValidationLevel.PartOnly);
                    _semanticValidator.Validate(context);
                }

                if (!partRootElementLoaded && context.Errors.Count == lastErrorCount)
                {
                    // No new errors in this part. Release the DOM to GC memory.
                    part.SetPartRootElementToNull();
                }
            }
            catch (System.Xml.XmlException e)
            {
                var errorInfo = new ValidationErrorInfo
                {
                    ErrorType   = ValidationErrorType.Schema,
                    Id          = "ExceptionError",
                    Part        = part,
                    Path        = new XmlPath(part),
                    Description = string.Format(CultureInfo.CurrentUICulture, ValidationResources.ExceptionError, e.Message)
                };

                context.AddError(errorInfo);
            }
        }
        /// <summary>
        /// From the Xml schema and other data, grab the ETN and OTC from the document
        /// </summary>
        /// <returns></returns>
        private void GetETNAndOTCFromDocument()
        {
            const string rootPath = @"urn:microsoft-crm/document-template/";

            string xmlBody = null;

            try {
                // open the file and read the contents
                using (var ms = new MemoryStream(this.FileContents)) {
                    // create a word doc from stream
                    WordprocessingDocument wordDoc     = WordprocessingDocument.Open(ms, true);
                    OpenXmlPart            mainDocPart = wordDoc.MainDocumentPart;

                    var custParts = wordDoc
                                    .MainDocumentPart
                                    .Parts
                                    .Where(p => p.OpenXmlPart is CustomXmlPart)
                                    .Select(c => (c.OpenXmlPart as CustomXmlPart).CustomXmlPropertiesPart);

                    foreach (var part in custParts)
                    {
                        if (part.RootElement.InnerXml.Contains(rootPath))
                        {
                            xmlBody = part.RootElement.InnerXml;
                            break;
                        }
                    }
                }

                if (xmlBody != null)
                {
                    // get the ETC from the first instance we can find of the ds:uri attribute.
                    var ns = @"{http://schemas.openxmlformats.org/officeDocument/2006/customXml}";
                    using (var textStream = new StringReader(xmlBody)) {
                        XDocument  doc    = XDocument.Load(textStream);
                        XAttribute attrib = doc
                                            .Descendants($"{ns}schemaRef")
                                            .Attributes($"{ns}uri")
                                            .Where <XAttribute>(a => a.Value.StartsWith(rootPath))
                                            .FirstOrDefault();

                        var etn_otc = attrib.Value.Substring(rootPath.Length).Split('/');

                        EntityTypeName = etn_otc[0];
                        ObjectTypeCode = int.Parse(etn_otc[1]);
                    }
                }
            }
            catch (NullReferenceException) {
                IsIgnored = true;
                Note      = "This does not appear to be a valid Word Document Template";
            }
        }
Esempio n. 32
0
        public void ValidateValid(OpenXmlPart part)
        {
            var availability = part.GetType().GetCustomAttribute <OfficeAvailabilityAttribute>().OfficeVersion;
            var versions     = Enum.GetValues(typeof(FileFormatVersions))
                               .Cast <FileFormatVersions>()
                               .Where(v => v != FileFormatVersions.None);

            foreach (var version in versions)
            {
                Assert.Equal(version.AtLeast(availability), part.IsInVersion(version));
            }
        }
        private XDocument LoadPart(OpenXmlPart source)
	    {
		    if (source == null) return null;

			var part = source.Annotation<XDocument>();
		    if (part != null) return part;

		    using (var str = source.GetStream())
		    using (var streamReader = new StreamReader(str))
		    using (var xr = XmlReader.Create(streamReader))
			    part = XDocument.Load(xr);
		    return part;
	    }
 public ValidationInfo(OpenXmlPowerToolsDocument doc, ValidationErrorInfo err)
 {
     Document = doc;
     FileName = doc.FileName;
     Description = err.Description;
     ErrorType = err.ErrorType;
     Id = err.Id;
     Node = err.Node;
     Part = err.Part;
     XPath = err.Path.XPath;
     RelatedNode = err.RelatedNode;
     RelatedPart = err.RelatedPart;
 }
        private static void ProcessTemplatePart(XElement data, TemplateError te, OpenXmlPart part)
        {
            XDocument xDoc = part.GetXDocument();

            XElement newRootElementWithMetadata = (XElement)TransformToMetadata(xDoc.Root, data, te);

            NormalizeTablesRepeatAndConditional(newRootElementWithMetadata, te);
            XElement newRootElement = newRootElementWithMetadata;

            // do the actual content replacement
            newRootElement = (XElement)ContentReplacementTransform(newRootElement, data, te);

            xDoc.Elements().First().ReplaceWith(newRootElement);
            part.PutXDocument();
            return;
        }
Esempio n. 36
0
 private static void FlushPart(OpenXmlPart part, HashSet<OpenXmlPart> visited)
 {
     visited.Add(part);
     XDocument xdoc = part.Annotation<XDocument>();
     if (xdoc != null && xdoc.Annotation<ChangedSemaphore>() != null)
     {
         using (XmlWriter xw = XmlWriter.Create(part.GetStream(FileMode.Create, FileAccess.Write)))
         {
             xdoc.Save(xw);
         }
         xdoc.RemoveAnnotations<ChangedSemaphore>();
         xdoc.Changing += ElementChanged;
         xdoc.Changed += ElementChanged;
     }
     foreach (IdPartPair item in part.Parts)
         if (!visited.Contains(item.OpenXmlPart))
             FlushPart(item.OpenXmlPart, visited);
 }
Esempio n. 37
0
 public static void AcceptRevisionsForPart(OpenXmlPart part)
 {
     XElement documentElement = part.GetXDocument().Root;
     documentElement = (XElement)AcceptMoveFromMoveToTransform(documentElement);
     documentElement = AcceptMoveFromRanges(documentElement);
     // AcceptParagraphEndTagsInMoveFromTransform needs rewritten similar to AcceptDeletedAndMoveFromParagraphMarks
     documentElement = (XElement)AcceptParagraphEndTagsInMoveFromTransform(documentElement);
     documentElement = AcceptDeletedAndMovedFromContentControls(documentElement);
     documentElement = AcceptDeletedAndMoveFromParagraphMarks(documentElement);
     documentElement = (XElement)RemoveRowsLeftEmptyByMoveFrom(documentElement);
     documentElement = (XElement)AcceptAllOtherRevisionsTransform(documentElement);
     documentElement = (XElement)AcceptDeletedCellsTransform(documentElement);
     documentElement = (XElement)MergeAdjacentTablesTransform(documentElement);
     documentElement.Descendants().Attributes().Where(a => a.Name == PT.UniqueId || a.Name == PT.RunIds).Remove();
     documentElement.Descendants(W.numPr).Where(np => !np.HasElements).Remove();
     XDocument newXDoc = new XDocument(documentElement);
     part.PutXDocument(newXDoc);
 }
Esempio n. 38
0
        /// <summary>
        /// Writes the element to custom XML part.
        /// </summary>
        /// <param name="customXmlPart">The custom XML part.</param>
        /// <param name="rootElement">The root element.</param>
        public static void WriteElementToCustomXmlPart(OpenXmlPart customXmlPart, XNode rootElement)
        {
            if (customXmlPart == null)
            {
                throw new ArgumentNullException("customXmlPart");
            }

            if (rootElement == null)
            {
                throw new ArgumentNullException("rootElement");
            }

            using (var writer = XmlWriter.Create(customXmlPart.GetStream(FileMode.Create, FileAccess.Write)))
            {
                rootElement.WriteTo(writer);
                writer.Flush();
            }
        }
Esempio n. 39
0
 public bool PartHasTrackedRevisions(OpenXmlPart part)
 {
     XmlDocument doc = GetXmlDocument(part);
     string wordNamespace =
         "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
     XmlNamespaceManager nsmgr =
         new XmlNamespaceManager(doc.NameTable);
     nsmgr.AddNamespace("w", wordNamespace);
     string xpathExpression =
         "descendant::w:cellDel|" +
         "descendant::w:cellIns|" +
         "descendant::w:cellMerge|" +
         "descendant::w:customXmlDelRangeEnd|" +
         "descendant::w:customXmlDelRangeStart|" +
         "descendant::w:customXmlInsRangeEnd|" +
         "descendant::w:customXmlInsRangeStart|" +
         "descendant::w:del|" +
         "descendant::w:delInstrText|" +
         "descendant::w:delText|" +
         "descendant::w:ins|" +
         "descendant::w:moveFrom|" +
         "descendant::w:moveFromRangeEnd|" +
         "descendant::w:moveFromRangeStart|" +
         "descendant::w:moveTo|" +
         "descendant::w:moveToRangeEnd|" +
         "descendant::w:moveToRangeStart|" +
         "descendant::w:moveTo|" +
         "descendant::w:numberingChange|" +
         "descendant::w:rPrChange|" +
         "descendant::w:pPrChange|" +
         "descendant::w:rPrChange|" +
         "descendant::w:sectPrChange|" +
         "descendant::w:tcPrChange|" +
         "descendant::w:tblGridChange|" +
         "descendant::w:tblPrChange|" +
         "descendant::w:tblPrExChange|" +
         "descendant::w:trPrChange";
     XmlNodeList descendants = doc.SelectNodes(xpathExpression, nsmgr);
     return descendants.Count > 0;
 }
        private static void CopyRelatedImage(OpenXmlPart oldContentPart, OpenXmlPart newContentPart, XElement imageReference, XName attributeName,
            List<ImageData> images)
        {
            string relId = (string)imageReference.Attribute(attributeName);
            if (string.IsNullOrEmpty(relId))
                return;

            // First look to see if this relId has already been added to the new document.
            // This is necessary for those parts that get processed with both old and new ids, such as the comments
            // part.  This is not necessary for parts such as the main document part, but this code won't malfunction
            // in that case.
            var tempPartIdPair5 = newContentPart.Parts.FirstOrDefault(p => p.RelationshipId == relId);
            if (tempPartIdPair5 != null)
                return;

            ExternalRelationship tempEr5 = newContentPart.ExternalRelationships.FirstOrDefault(er => er.Id == relId);
            if (tempEr5 != null)
                return;

            var ipp2 = oldContentPart.Parts.FirstOrDefault(ipp => ipp.RelationshipId == relId);
            if (ipp2 != null)
            {
                ImagePart oldPart = (ImagePart)ipp2.OpenXmlPart;
                ImageData temp = ManageImageCopy(oldPart, newContentPart, images);
                if (temp.ImagePart == null)
                {
                    ImagePart newPart = null;
                    if (newContentPart is MainDocumentPart)
                        newPart = ((MainDocumentPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is HeaderPart)
                        newPart = ((HeaderPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is FooterPart)
                        newPart = ((FooterPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is EndnotesPart)
                        newPart = ((EndnotesPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is FootnotesPart)
                        newPart = ((FootnotesPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is ThemePart)
                        newPart = ((ThemePart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is WordprocessingCommentsPart)
                        newPart = ((WordprocessingCommentsPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is DocumentSettingsPart)
                        newPart = ((DocumentSettingsPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is ChartPart)
                        newPart = ((ChartPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is NumberingDefinitionsPart)
                        newPart = ((NumberingDefinitionsPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is DiagramDataPart)
                        newPart = ((DiagramDataPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is ChartDrawingPart)
                        newPart = ((ChartDrawingPart)newContentPart).AddImagePart(oldPart.ContentType);
                    temp.ImagePart = newPart;
                    var id = newContentPart.GetIdOfPart(newPart);
                    temp.AddContentPartRelTypeResourceIdTupple(newContentPart, newPart.RelationshipType, id);
                    imageReference.Attribute(attributeName).Value = id;
                    temp.WriteImage(newPart);
                }
                else
                {
                    var refRel = newContentPart.Parts.FirstOrDefault(pip =>
                    {
                        var rel = temp.ContentPartRelTypeIdList.FirstOrDefault(cpr =>
                        {
                            var found = cpr.ContentPart == newContentPart;
                            return found;
                        });
                        return rel != null;
                    });
                    if (refRel != null)
                    {
                        imageReference.Attribute(attributeName).Value = temp.ContentPartRelTypeIdList.First(cpr =>
                        {
                            var found = cpr.ContentPart == newContentPart;
                            return found;
                        }).RelationshipId;
                        return;
                    }
                    var newId = "R" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16);
                    newContentPart.CreateRelationshipToPart(temp.ImagePart, newId);
                    imageReference.Attribute(R.id).Value = newId;
                }
            }
            else
            {
                ExternalRelationship er = oldContentPart.ExternalRelationships.FirstOrDefault(er1 => er1.Id == relId);
                if (er != null)
                {
                    ExternalRelationship newEr = newContentPart.AddExternalRelationship(er.RelationshipType, er.Uri);
                    imageReference.Attribute(R.id).Value = newEr.Id;
                }
                throw new DocumentBuilderInternalException("Source {0} is unsupported document - contains reference to NULL image");
            }
        }
 public static bool PartHasTrackedRevisions(OpenXmlPart part)
 {
     return part.GetXDocument()
         .Descendants()
         .Any(e => TrackedRevisionsElements.Contains(e.Name));
 }
        private static void SimplifyMarkupForPart(
            OpenXmlPart part,
            SimplifyMarkupSettings settings)
        {
            SimplifyMarkupParameters parameters = new SimplifyMarkupParameters();
            if (part.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")
            {
                WordprocessingDocument doc = (WordprocessingDocument)part.OpenXmlPackage;
                if (settings.RemoveGoBackBookmark == true)
                {
                    var goBackBookmark = doc
                        .MainDocumentPart
                        .GetXDocument()
                        .Root
                        .Descendants(W.bookmarkStart)
                        .FirstOrDefault(bm => (string)bm.Attribute(W.name) == "_GoBack");
                    if (goBackBookmark != null)
                        parameters.GoBackId = (int)goBackBookmark.Attribute(W.id);
                }
            }

            
            XDocument xdoc = part.GetXDocument();
            XElement newRoot = xdoc.Root;

            // Need to do this first to enable simplifying hyperlinks.
            if (settings.RemoveContentControls ||
                settings.RemoveSmartTags)
                newRoot = (XElement)
                    RemoveCustomXmlAndContentControlsTransform(
                        newRoot, settings);

            // This may touch many elements, so needs to be its own
            // transform.
            if (settings.RemoveRsidInfo)
                newRoot = (XElement)RemoveRsidTransform(newRoot);

            XDocument prevNewRoot = new XDocument(newRoot);
            while (true)
            {
                if (settings.RemoveComments ||
                    settings.RemoveEndAndFootNotes ||
                    settings.ReplaceTabsWithSpaces ||
                    settings.RemoveFieldCodes ||
                    settings.RemovePermissions ||
                    settings.RemoveProof ||
                    settings.RemoveBookmarks ||
                    settings.RemoveWebHidden ||
                    settings.RemoveGoBackBookmark)
                    newRoot = (XElement)SimplifyMarkupTransform(newRoot,
                        settings, parameters);

                // Remove runs and run properties that have become empty due to previous
                // transforms.
                newRoot = (XElement)
                    RemoveEmptyRunsAndRunPropertiesTransform(newRoot);

                // Merge adjacent runs that have identical run properties.
                newRoot = (XElement)MergeAdjacentRunsTransform(newRoot);

                // Merge adjacent instrText elements.
                newRoot = (XElement)MergeAdjacentInstrText(newRoot);

                // Separate run children into separate runs
                newRoot = (XElement)SeparateRunChildrenIntoSeparateRuns(newRoot);

                if (XNode.DeepEquals(prevNewRoot.Root, newRoot))
                    break;

                prevNewRoot = new XDocument(newRoot);
            }

            if (settings.NormalizeXml)
            {
                XAttribute[] ns_attrs =
                {
                    new XAttribute(XNamespace.Xmlns + "wpc", WPC.wpc),
                    new XAttribute(XNamespace.Xmlns + "mc", MC.mc),
                    new XAttribute(XNamespace.Xmlns + "o", O.o),
                    new XAttribute(XNamespace.Xmlns + "r", R.r),
                    new XAttribute(XNamespace.Xmlns + "m", M.m),
                    new XAttribute(XNamespace.Xmlns + "v", VML.vml),
                    new XAttribute(XNamespace.Xmlns + "wp14", WP14.wp14),
                    new XAttribute(XNamespace.Xmlns + "wp", WP.wp),
                    new XAttribute(XNamespace.Xmlns + "w10", W10.w10),
                    new XAttribute(XNamespace.Xmlns + "w", W.w),
                    new XAttribute(XNamespace.Xmlns + "w14", W14.w14),
                    new XAttribute(XNamespace.Xmlns + "wpg", WPG.wpg),
                    new XAttribute(XNamespace.Xmlns + "wpi", WPI.wpi),
                    new XAttribute(XNamespace.Xmlns + "wne", WNE.wne),
                    new XAttribute(XNamespace.Xmlns + "wps", WPS.wps),
                    new XAttribute(MC.Ignorable, "w14 wp14"),
                };

                XDocument newXDoc = Normalize(new XDocument(newRoot), null);
                foreach (var nsatt in ns_attrs)
                {
                    if (newXDoc.Root.Attribute(nsatt.Name) == null)
                        newXDoc.Root.Add(nsatt);
                }
                part.PutXDocument(newXDoc);
            }
            else
            {
                part.PutXDocument(new XDocument(newRoot));
            }
        }
 /// <summary>
 /// Initializes a new instance of the OpenXmlPartReader class using the supplied OpenXmlPart and Boolean values.
 /// </summary>
 /// <param name="openXmlPart">The OpenXmlPart to read.</param>
 /// <param name="readMiscNodes">Specify false to indicate to the reader to skip all miscellaneous nodes. The default value is false.</param>
 public OpenXmlPartReader(OpenXmlPart openXmlPart, bool readMiscNodes)
     : this(readMiscNodes)
 {
     if (openXmlPart == null)
     {
         throw new ArgumentNullException("openXmlPart");
     }
     // set MaxCharactersInDocument to limit the part size on loading DOM.
     this._elementContext.XmlReaderSettings.MaxCharactersInDocument = openXmlPart.MaxCharactersInPart;
     Stream partStream = openXmlPart.GetStream(FileMode.Open);
     this.Init(partStream, /*closeInput*/true);
 }
 /// <summary>
 /// Creates an OpenXmlReader from the specified OpenXmlPart and Boolean values.
 /// </summary>
 /// <param name="openXmlPart">The OpenXmlPart to read.</param>
 /// <param name="readMiscNodes">Specify false to indicate to the reader to skip all miscellaneous nodes. The default value is false.</param>
 /// <returns>The newly created OpenXmlReader.</returns>
 public static OpenXmlReader Create(OpenXmlPart openXmlPart, bool readMiscNodes)
 {
     return new OpenXmlPartReader(openXmlPart, readMiscNodes);
 }
 /// <summary>
 /// Creates an OpenXmlReader from the specified OpenXmlPart.
 /// </summary>
 /// <param name="openXmlPart">The OpenXmlPart to read.</param>
 /// <returns>The newly created OpenXmlReader.</returns>
 public static OpenXmlReader Create(OpenXmlPart openXmlPart)
 {
     return new OpenXmlPartReader(openXmlPart);
 }
Esempio n. 46
0
 /// <summary>
 /// Initlizes a new instance of the XmlPath from the specified OpenXmlPart.
 /// </summary>
 /// <param name="part">The OpenXmlPart.</param>
 internal XmlPath(OpenXmlPart part)
 {
     Debug.Assert(part != null);
     this.PartUri = part.Uri;
 }
 private static void AddPart(HashSet<OpenXmlPart> partList, OpenXmlPart part)
 {
     if (partList.Contains(part))
         return;
     partList.Add(part);
     foreach (IdPartPair p in part.Parts)
         AddPart(partList, p.OpenXmlPart);
 }
 public void AddContentPartRelTypeResourceIdTupple(OpenXmlPart contentPart, string relationshipType, string relationshipId)
 {
     ContentPartRelTypeIdList.Add(
         new ContentPartRelTypeIdTuple()
         {
             ContentPart = contentPart,
             RelationshipType = relationshipType,
             RelationshipId = relationshipId,
         });
 }
        private static void MergeCommentsInPart(OpenXmlPart part1, OpenXmlPart part2, 
            OpenXmlPart destinationPart, XDocument commentsPartXDoc)
        {
            XDocument xdoc1 = part1.GetXDocument();
            XDocument xdoc2 = part2.GetXDocument();

            XElement newRootElement = (XElement)MergeElementTransform(xdoc1.Root, xdoc2.Root, 
                commentsPartXDoc);
            destinationPart.PutXDocument(new XDocument(newRootElement));
        }
 // todo are there any other elements that need ids fixed?  see children of paragraph, run
 private static void FixIdsInPart(OpenXmlPart part, int nextCommentId, int nextBookmarkId)
 {
     if (part == null)
         return;
     foreach (var element in part.GetXDocument().Root.Descendants()
         .Where(e => e.Name == W.commentRangeStart ||
             e.Name == W.commentRangeEnd || 
             e.Name == W.commentReference))
         element.Attribute(W.id).Value = ((int)element.Attribute(W.id) + nextCommentId).ToString();
     foreach (var element in part.GetXDocument().Root.Descendants()
         .Where(e => e.Name == W.bookmarkStart || e.Name == W.bookmarkEnd))
         element.Attribute(W.id).Value = ((int)element.Attribute(W.id) + nextBookmarkId).ToString();
 }
 private static void TestPartForUnsupportedContent(OpenXmlPart part, int sourceNumber)
 {
     XNamespace[] obsoleteNamespaces = new[]
         {
             XNamespace.Get("http://schemas.microsoft.com/office/word/2007/5/30/wordml"),
             XNamespace.Get("http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing"),
             XNamespace.Get("http://schemas.microsoft.com/office/word/2009/2/wordml"),
         };
     XDocument xDoc = part.GetXDocument();
     XElement invalidElement = xDoc.Descendants()
         .FirstOrDefault(d =>
             {
                 bool b = d.Name == W.subDoc ||
                     d.Name == W.control ||
                     d.Name == W.altChunk ||
                     d.Name.LocalName == "contentPart" ||
                     obsoleteNamespaces.Contains(d.Name.Namespace);
                 bool b2 = b ||
                     d.Attributes().Any(a => obsoleteNamespaces.Contains(a.Name.Namespace));
                 return b2;
             });
     if (invalidElement != null)
     {
         if (invalidElement.Name == W.subDoc)
             throw new DocumentBuilderException(String.Format("Source {0} is unsupported document - contains sub document",
                 sourceNumber));
         if (invalidElement.Name == W.control)
             throw new DocumentBuilderException(String.Format("Source {0} is unsupported document - contains ActiveX controls",
                 sourceNumber));
         if (invalidElement.Name == W.altChunk)
             throw new DocumentBuilderException(String.Format("Source {0} is unsupported document - contains altChunk",
                 sourceNumber));
         if (invalidElement.Name.LocalName == "contentPart")
             throw new DocumentBuilderException(String.Format("Source {0} is unsupported document - contains contentPart content",
                 sourceNumber));
         if (obsoleteNamespaces.Contains(invalidElement.Name.Namespace) ||
             invalidElement.Attributes().Any(a => obsoleteNamespaces.Contains(a.Name.Namespace)))
             throw new DocumentBuilderException(String.Format("Source {0} is unsupported document - contains obsolete namespace",
                 sourceNumber));
     }
 }
 private static void AddRelationships(OpenXmlPart oldPart, OpenXmlPart newPart, IEnumerable<XElement> newContent)
 {
     var relevantElements = newContent.DescendantsAndSelf()
         .Where(d => RelationshipMarkup.ContainsKey(d.Name) &&
             d.Attributes().Any(a => RelationshipMarkup[d.Name].Contains(a.Name)))
         .ToList();
     foreach (var e in relevantElements)
     {
         if (e.Name == W.hyperlink)
         {
             string relId = (string)e.Attribute(R.id);
             if (string.IsNullOrEmpty(relId))
                 continue;
             var tempHyperlink = newPart.HyperlinkRelationships.FirstOrDefault(h => h.Id == relId);
             if (tempHyperlink != null)
                 continue;
             Guid g = Guid.NewGuid();
             string newRid = "R" + g.ToString().Replace("-", "");
             var oldHyperlink = oldPart.HyperlinkRelationships.FirstOrDefault(h => h.Id == relId);
             if (oldHyperlink == null)
                 continue;
             //throw new DocumentBuilderInternalException("Internal Error 0002");
             newPart.AddHyperlinkRelationship(oldHyperlink.Uri, oldHyperlink.IsExternal, newRid);
             UpdateContent(newContent, e.Name, relId, newRid);
         }
         if (e.Name == W.attachedTemplate || e.Name == W.saveThroughXslt)
         {
             string relId = (string)e.Attribute(R.id);
             if (string.IsNullOrEmpty(relId))
                 continue;
             var tempExternalRelationship = newPart.ExternalRelationships.FirstOrDefault(h => h.Id == relId);
             if (tempExternalRelationship != null)
                 continue;
             Guid g = Guid.NewGuid();
             string newRid = "R" + g.ToString().Replace("-", "");
             var oldRel = oldPart.ExternalRelationships.FirstOrDefault(h => h.Id == relId);
             if (oldRel == null)
                 throw new DocumentBuilderInternalException("Source {0} is invalid document - hyperlink contains invalid references");
             newPart.AddExternalRelationship(oldRel.RelationshipType, oldRel.Uri, newRid);
             UpdateContent(newContent, e.Name, relId, newRid);
         }
         if (e.Name == A.hlinkClick)
         {
             string relId = (string)e.Attribute(R.id);
             if (string.IsNullOrEmpty(relId))
                 continue;
             var tempHyperlink = newPart.HyperlinkRelationships.FirstOrDefault(h => h.Id == relId);
             if (tempHyperlink != null)
                 continue;
             Guid g = Guid.NewGuid();
             string newRid = "R" + g.ToString().Replace("-", "");
             var oldHyperlink = oldPart.HyperlinkRelationships.FirstOrDefault(h => h.Id == relId);
             if (oldHyperlink == null)
                 continue;
             newPart.AddHyperlinkRelationship(oldHyperlink.Uri, oldHyperlink.IsExternal, newRid);
             UpdateContent(newContent, e.Name, relId, newRid);
         }
         if (e.Name == VML.imagedata)
         {
             string relId = (string)e.Attribute(R.href);
             if (string.IsNullOrEmpty(relId))
                 continue;
             var tempExternalRelationship = newPart.ExternalRelationships.FirstOrDefault(h => h.Id == relId);
             if (tempExternalRelationship != null)
                 continue;
             Guid g = Guid.NewGuid();
             string newRid = "R" + g.ToString().Replace("-", "");
             var oldRel = oldPart.ExternalRelationships.FirstOrDefault(h => h.Id == relId);
             if (oldRel == null)
                 throw new DocumentBuilderInternalException("Internal Error 0006");
             newPart.AddExternalRelationship(oldRel.RelationshipType, oldRel.Uri, newRid);
             UpdateContent(newContent, e.Name, relId, newRid);
         }
         if (e.Name == A.blip)
         {
             string relId = (string)e.Attribute(R.link);
             if (string.IsNullOrEmpty(relId))
                 continue;
             var tempExternalRelationship = newPart.ExternalRelationships.FirstOrDefault(h => h.Id == relId);
             if (tempExternalRelationship != null)
                 continue;
             Guid g = Guid.NewGuid();
             string newRid = "R" + g.ToString().Replace("-", "");
             var oldRel = oldPart.ExternalRelationships.FirstOrDefault(h => h.Id == relId);
             if (oldRel == null)
                 continue;
             newPart.AddExternalRelationship(oldRel.RelationshipType, oldRel.Uri, newRid);
             UpdateContent(newContent, e.Name, relId, newRid);
         }
     }
 }
        private static void CopyRelatedPartsForContentParts(OpenXmlPart oldContentPart, OpenXmlPart newContentPart,
            IEnumerable<XElement> newContent, List<ImageData> images)
        {
            var relevantElements = newContent.DescendantsAndSelf()
                .Where(d => d.Name == VML.imagedata || d.Name == VML.fill || d.Name == VML.stroke || d.Name == A.blip)
                .ToList();
            foreach (XElement imageReference in relevantElements)
            {
                CopyRelatedImage(oldContentPart, newContentPart, imageReference, R.embed, images);
                CopyRelatedImage(oldContentPart, newContentPart, imageReference, R.pict, images);
                CopyRelatedImage(oldContentPart, newContentPart, imageReference, R.id, images);
            }

            foreach (XElement diagramReference in newContent.DescendantsAndSelf().Where(d => d.Name == DGM.relIds || d.Name == A.relIds))
            {
                // dm attribute
                string relId = diagramReference.Attribute(R.dm).Value;
                try
                {
                    OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                    continue;
                }
                catch (ArgumentOutOfRangeException)
                {
                    try
                    {
                        ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                        continue;
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }
                OpenXmlPart oldPart = oldContentPart.GetPartById(relId);
                OpenXmlPart newPart = newContentPart.AddNewPart<DiagramDataPart>();
                newPart.GetXDocument().Add(oldPart.GetXDocument().Root);
                diagramReference.Attribute(R.dm).Value = newContentPart.GetIdOfPart(newPart);
                AddRelationships(oldPart, newPart, new[] { newPart.GetXDocument().Root });
                CopyRelatedPartsForContentParts(oldPart, newPart, new[] { newPart.GetXDocument().Root }, images);

                // lo attribute
                relId = diagramReference.Attribute(R.lo).Value;
                try
                {
                    OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                    continue;
                }
                catch (ArgumentOutOfRangeException)
                {
                    try
                    {
                        ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                        continue;
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }
                oldPart = oldContentPart.GetPartById(relId);
                newPart = newContentPart.AddNewPart<DiagramLayoutDefinitionPart>();
                newPart.GetXDocument().Add(oldPart.GetXDocument().Root);
                diagramReference.Attribute(R.lo).Value = newContentPart.GetIdOfPart(newPart);
                AddRelationships(oldPart, newPart, new[] { newPart.GetXDocument().Root });
                CopyRelatedPartsForContentParts(oldPart, newPart, new[] { newPart.GetXDocument().Root }, images);

                // qs attribute
                relId = diagramReference.Attribute(R.qs).Value;
                try
                {
                    OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                    continue;
                }
                catch (ArgumentOutOfRangeException)
                {
                    try
                    {
                        ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                        continue;
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }
                oldPart = oldContentPart.GetPartById(relId);
                newPart = newContentPart.AddNewPart<DiagramStylePart>();
                newPart.GetXDocument().Add(oldPart.GetXDocument().Root);
                diagramReference.Attribute(R.qs).Value = newContentPart.GetIdOfPart(newPart);
                AddRelationships(oldPart, newPart, new[] { newPart.GetXDocument().Root });
                CopyRelatedPartsForContentParts(oldPart, newPart, new[] { newPart.GetXDocument().Root }, images);

                // cs attribute
                relId = diagramReference.Attribute(R.cs).Value;
                try
                {
                    OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                    continue;
                }
                catch (ArgumentOutOfRangeException)
                {
                    try
                    {
                        ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                        continue;
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }
                oldPart = oldContentPart.GetPartById(relId);
                newPart = newContentPart.AddNewPart<DiagramColorsPart>();
                newPart.GetXDocument().Add(oldPart.GetXDocument().Root);
                diagramReference.Attribute(R.cs).Value = newContentPart.GetIdOfPart(newPart);
                AddRelationships(oldPart, newPart, new[] { newPart.GetXDocument().Root });
                CopyRelatedPartsForContentParts(oldPart, newPart, new[] { newPart.GetXDocument().Root }, images);
            }

            foreach (XElement oleReference in newContent.DescendantsAndSelf(O.OLEObject))
            {
                string relId = oleReference.Attribute(R.id).Value;
                try
                {
                    // First look to see if this relId has already been added to the new document.
                    // This is necessary for those parts that get processed with both old and new ids, such as the comments
                    // part.  This is not necessary for parts such as the main document part, but this code won't malfunction
                    // in that case.
                    try
                    {
                        OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                        continue;
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        try
                        {
                            ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                            continue;
                        }
                        catch (KeyNotFoundException)
                        {
                            // nothing to do
                        }
                    }

                    OpenXmlPart oldPart = oldContentPart.GetPartById(relId);
                    OpenXmlPart newPart = null;
                    if (oldPart is EmbeddedObjectPart)
                    {
                        if (newContentPart is HeaderPart)
                            newPart = ((HeaderPart)newContentPart).AddEmbeddedObjectPart(oldPart.ContentType);
                        if (newContentPart is FooterPart)
                            newPart = ((FooterPart)newContentPart).AddEmbeddedObjectPart(oldPart.ContentType);
                        if (newContentPart is MainDocumentPart)
                            newPart = ((MainDocumentPart)newContentPart).AddEmbeddedObjectPart(oldPart.ContentType);
                        if (newContentPart is FootnotesPart)
                            newPart = ((FootnotesPart)newContentPart).AddEmbeddedObjectPart(oldPart.ContentType);
                        if (newContentPart is EndnotesPart)
                            newPart = ((EndnotesPart)newContentPart).AddEmbeddedObjectPart(oldPart.ContentType);
                        if (newContentPart is WordprocessingCommentsPart)
                            newPart = ((WordprocessingCommentsPart)newContentPart).AddEmbeddedObjectPart(oldPart.ContentType);
                    }
                    else if (oldPart is EmbeddedPackagePart)
                    {
                        if (newContentPart is HeaderPart)
                            newPart = ((HeaderPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                        if (newContentPart is FooterPart)
                            newPart = ((FooterPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                        if (newContentPart is MainDocumentPart)
                            newPart = ((MainDocumentPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                        if (newContentPart is FootnotesPart)
                            newPart = ((FootnotesPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                        if (newContentPart is EndnotesPart)
                            newPart = ((EndnotesPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                        if (newContentPart is WordprocessingCommentsPart)
                            newPart = ((WordprocessingCommentsPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                        if (newContentPart is ChartPart)
                            newPart = ((ChartPart)newContentPart).AddEmbeddedPackagePart(oldPart.ContentType);
                    }
                    using (Stream oldObject = oldPart.GetStream(FileMode.Open, FileAccess.Read))
                    using (Stream newObject = newPart.GetStream(FileMode.Create, FileAccess.ReadWrite))
                    {
                        int byteCount;
                        byte[] buffer = new byte[65536];
                        while ((byteCount = oldObject.Read(buffer, 0, 65536)) != 0)
                            newObject.Write(buffer, 0, byteCount);
                    }
                    oleReference.Attribute(R.id).Value = newContentPart.GetIdOfPart(newPart);
                }
                catch (ArgumentOutOfRangeException)
                {
                    ExternalRelationship er = oldContentPart.GetExternalRelationship(relId);
                    ExternalRelationship newEr = newContentPart.AddExternalRelationship(er.RelationshipType, er.Uri);
                    oleReference.Attribute(R.id).Value = newEr.Id;
                }
            }

            foreach (XElement chartReference in newContent.DescendantsAndSelf(C.chart))
            {
                try
                {
                    string relId = (string)chartReference.Attribute(R.id);
                    if (string.IsNullOrEmpty(relId))
                        continue;
                    try
                    {
                        OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                        continue;
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        try
                        {
                            ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                            continue;
                        }
                        catch (KeyNotFoundException)
                        {
                        }
                    }
                    ChartPart oldPart = (ChartPart)oldContentPart.GetPartById(relId);
                    XDocument oldChart = oldPart.GetXDocument();
                    ChartPart newPart = newContentPart.AddNewPart<ChartPart>();
                    XDocument newChart = newPart.GetXDocument();
                    newChart.Add(oldChart.Root);
                    chartReference.Attribute(R.id).Value = newContentPart.GetIdOfPart(newPart);
                    CopyChartObjects(oldPart, newPart);
                    CopyRelatedPartsForContentParts(oldPart, newPart, new[] { newChart.Root }, images);
                }
                catch (ArgumentOutOfRangeException)
                {
                    continue;
                }
            }

            foreach (XElement userShape in newContent.DescendantsAndSelf(C.userShapes))
            {
                try
                {
                    string relId = (string)userShape.Attribute(R.id);
                    if (string.IsNullOrEmpty(relId))
                        continue;
                    try
                    {
                        OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                        continue;
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        try
                        {
                            ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                            continue;
                        }
                        catch (KeyNotFoundException)
                        {
                        }
                    }
                    ChartDrawingPart oldPart = (ChartDrawingPart)oldContentPart.GetPartById(relId);
                    XDocument oldXDoc = oldPart.GetXDocument();
                    ChartDrawingPart newPart = newContentPart.AddNewPart<ChartDrawingPart>();
                    XDocument newXDoc = newPart.GetXDocument();
                    newXDoc.Add(oldXDoc.Root);
                    userShape.Attribute(R.id).Value = newContentPart.GetIdOfPart(newPart);
                    AddRelationships(oldPart, newPart, newContent);
                    CopyRelatedPartsForContentParts(oldPart, newPart, new[] { newXDoc.Root }, images);
                }
                catch (ArgumentOutOfRangeException)
                {
                    continue;
                }
            }
        }
 // General function for handling images that tries to use an existing image if they are the same
 private static ImageData ManageImageCopy(ImagePart oldImage, OpenXmlPart newContentPart, List<ImageData> images)
 {
     ImageData oldImageData = new ImageData(newContentPart, oldImage);
     foreach (ImageData item in images)
     {
         if (newContentPart != item.ContentPart)
             continue;
         if (item.Compare(oldImageData))
             return item;
     }
     images.Add(oldImageData);
     return oldImageData;
 }
        private static void CopyRelatedImage(OpenXmlPart oldContentPart, OpenXmlPart newContentPart, XElement imageReference, XName attributeName,
            List<ImageData> images)
        {
            string relId = (string)imageReference.Attribute(attributeName);
            if (string.IsNullOrEmpty(relId))
                return;
            try
            {
                // First look to see if this relId has already been added to the new document.
                // This is necessary for those parts that get processed with both old and new ids, such as the comments
                // part.  This is not necessary for parts such as the main document part, but this code won't malfunction
                // in that case.
                try
                {
                    OpenXmlPart tempPart = newContentPart.GetPartById(relId);
                    return;
                }
                catch (ArgumentOutOfRangeException)
                {
                    try
                    {
                        ExternalRelationship tempEr = newContentPart.GetExternalRelationship(relId);
                        return;
                    }
                    catch (KeyNotFoundException)
                    {
                        // nothing to do
                    }
                }

                ImagePart oldPart = (ImagePart)oldContentPart.GetPartById(relId);
                ImageData temp = ManageImageCopy(oldPart, newContentPart, images);
                if (temp.ResourceID == null)
                {
                    ImagePart newPart = null;
                    if (newContentPart is MainDocumentPart)
                        newPart = ((MainDocumentPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is HeaderPart)
                        newPart = ((HeaderPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is FooterPart)
                        newPart = ((FooterPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is EndnotesPart)
                        newPart = ((EndnotesPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is FootnotesPart)
                        newPart = ((FootnotesPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is ThemePart)
                        newPart = ((ThemePart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is WordprocessingCommentsPart)
                        newPart = ((WordprocessingCommentsPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is DocumentSettingsPart)
                        newPart = ((DocumentSettingsPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is ChartPart)
                        newPart = ((ChartPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is NumberingDefinitionsPart)
                        newPart = ((NumberingDefinitionsPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is DiagramDataPart)
                        newPart = ((DiagramDataPart)newContentPart).AddImagePart(oldPart.ContentType);
                    if (newContentPart is ChartDrawingPart)
                        newPart = ((ChartDrawingPart)newContentPart).AddImagePart(oldPart.ContentType);
                    temp.ResourceID = newContentPart.GetIdOfPart(newPart);
                    temp.WriteImage(newPart);
                    imageReference.Attribute(attributeName).Value = temp.ResourceID;
                }
                else
                    imageReference.Attribute(attributeName).Value = temp.ResourceID;
            }
            catch (ArgumentOutOfRangeException)
            {
                try
                {
                    ExternalRelationship er = oldContentPart.GetExternalRelationship(relId);
                    ExternalRelationship newEr = newContentPart.AddExternalRelationship(er.RelationshipType, er.Uri);
                    imageReference.Attribute(R.id).Value = newEr.Id;
                }
                catch (KeyNotFoundException)
                {
                    throw new DocumentBuilderInternalException("Source {0} is unsupported document - contains reference to NULL image");
                }
            }
        }
Esempio n. 56
0
        /// <summary>
        /// Create an instance of OpenXmlPart according to the given relationship type.
        /// </summary>
        /// <param name="openXmlPackage">The container OpenXmlPackage.</param>
        /// <param name="relationshipType">The relationship type of the target part.</param>
        /// <param name="openXmlPart">The created instance of OpenXmlPart.</param>
        /// <remarks>This partial method will be generated by code generaotr.</remarks>
        static partial void CreatePartCore(OpenXmlPackage openXmlPackage, string relationshipType, ref OpenXmlPart openXmlPart)
        {
            if (openXmlPackage == null)
            {
				throw new ArgumentNullException("openXmlPackage");
            }
            if (relationshipType == null)
            {
                throw new ArgumentNullException("relationshipType");
            }
            
            if (openXmlPackage is WordprocessingDocument)
            {
                switch (relationshipType)
                {
					case MainDocumentPart.RelationshipTypeConstant:
	openXmlPart = new MainDocumentPart();
	return;
case CustomXmlPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlPart();
	return;
case CustomXmlPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlPropertiesPart();
	return;
case GlossaryDocumentPart.RelationshipTypeConstant:
	openXmlPart = new GlossaryDocumentPart();
	return;
case WordprocessingCommentsPart.RelationshipTypeConstant:
	openXmlPart = new WordprocessingCommentsPart();
	return;
case AlternativeFormatImportPart.RelationshipTypeConstant:
	openXmlPart = new AlternativeFormatImportPart();
	return;
case ChartPart.RelationshipTypeConstant:
	openXmlPart = new ChartPart();
	return;
case ChartDrawingPart.RelationshipTypeConstant:
	openXmlPart = new ChartDrawingPart();
	return;
case ImagePart.RelationshipTypeConstant:
	openXmlPart = new ImagePart();
	return;
case EmbeddedPackagePart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedPackagePart();
	return;
case ThemeOverridePart.RelationshipTypeConstant:
	openXmlPart = new ThemeOverridePart();
	return;
case ChartStylePart.RelationshipTypeConstant:
	openXmlPart = new ChartStylePart();
	return;
case ChartColorStylePart.RelationshipTypeConstant:
	openXmlPart = new ChartColorStylePart();
	return;
case DiagramColorsPart.RelationshipTypeConstant:
	openXmlPart = new DiagramColorsPart();
	return;
case DiagramDataPart.RelationshipTypeConstant:
	openXmlPart = new DiagramDataPart();
	return;
case SlidePart.RelationshipTypeConstant:
	openXmlPart = new SlidePart();
	return;
case DiagramPersistLayoutPart.RelationshipTypeConstant:
	openXmlPart = new DiagramPersistLayoutPart();
	return;
case DiagramLayoutDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new DiagramLayoutDefinitionPart();
	return;
case DiagramStylePart.RelationshipTypeConstant:
	openXmlPart = new DiagramStylePart();
	return;
case EmbeddedObjectPart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedObjectPart();
	return;
case VmlDrawingPart.RelationshipTypeConstant:
	openXmlPart = new VmlDrawingPart();
	return;
case LegacyDiagramTextPart.RelationshipTypeConstant:
	openXmlPart = new LegacyDiagramTextPart();
	return;
case EmbeddedControlPersistenceBinaryDataPart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedControlPersistenceBinaryDataPart();
	return;
case NotesSlidePart.RelationshipTypeConstant:
	openXmlPart = new NotesSlidePart();
	return;
case NotesMasterPart.RelationshipTypeConstant:
	openXmlPart = new NotesMasterPart();
	return;
case ThemePart.RelationshipTypeConstant:
	openXmlPart = new ThemePart();
	return;
case UserDefinedTagsPart.RelationshipTypeConstant:
	openXmlPart = new UserDefinedTagsPart();
	return;
case SlideLayoutPart.RelationshipTypeConstant:
	openXmlPart = new SlideLayoutPart();
	return;
case SlideMasterPart.RelationshipTypeConstant:
	openXmlPart = new SlideMasterPart();
	return;
case EmbeddedControlPersistencePart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedControlPersistencePart();
	return;
case SlideSyncDataPart.RelationshipTypeConstant:
	openXmlPart = new SlideSyncDataPart();
	return;
case WorksheetPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetPart();
	return;
case DrawingsPart.RelationshipTypeConstant:
	openXmlPart = new DrawingsPart();
	return;
case WebExtensionPart.RelationshipTypeConstant:
	openXmlPart = new WebExtensionPart();
	return;
case PivotTablePart.RelationshipTypeConstant:
	openXmlPart = new PivotTablePart();
	return;
case PivotTableCacheDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new PivotTableCacheDefinitionPart();
	return;
case PivotTableCacheRecordsPart.RelationshipTypeConstant:
	openXmlPart = new PivotTableCacheRecordsPart();
	return;
case SingleCellTablePart.RelationshipTypeConstant:
	openXmlPart = new SingleCellTablePart();
	return;
case TableDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new TableDefinitionPart();
	return;
case QueryTablePart.RelationshipTypeConstant:
	openXmlPart = new QueryTablePart();
	return;
case ControlPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ControlPropertiesPart();
	return;
case CustomPropertyPart.RelationshipTypeConstant:
	openXmlPart = new CustomPropertyPart();
	return;
case WorksheetSortMapPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetSortMapPart();
	return;
case SlicersPart.RelationshipTypeConstant:
	openXmlPart = new SlicersPart();
	return;
case TimeLinePart.RelationshipTypeConstant:
	openXmlPart = new TimeLinePart();
	return;
case DocumentSettingsPart.RelationshipTypeConstant:
	openXmlPart = new DocumentSettingsPart();
	return;
case MailMergeRecipientDataPart.RelationshipTypeConstant:
	openXmlPart = new MailMergeRecipientDataPart();
	return;
case EndnotesPart.RelationshipTypeConstant:
	openXmlPart = new EndnotesPart();
	return;
case FontTablePart.RelationshipTypeConstant:
	openXmlPart = new FontTablePart();
	return;
case FontPart.RelationshipTypeConstant:
	openXmlPart = new FontPart();
	return;
case FootnotesPart.RelationshipTypeConstant:
	openXmlPart = new FootnotesPart();
	return;
case NumberingDefinitionsPart.RelationshipTypeConstant:
	openXmlPart = new NumberingDefinitionsPart();
	return;
case StyleDefinitionsPart.RelationshipTypeConstant:
	openXmlPart = new StyleDefinitionsPart();
	return;
case StylesWithEffectsPart.RelationshipTypeConstant:
	openXmlPart = new StylesWithEffectsPart();
	return;
case WebSettingsPart.RelationshipTypeConstant:
	openXmlPart = new WebSettingsPart();
	return;
case FooterPart.RelationshipTypeConstant:
	openXmlPart = new FooterPart();
	return;
case HeaderPart.RelationshipTypeConstant:
	openXmlPart = new HeaderPart();
	return;
case WordprocessingPrinterSettingsPart.RelationshipTypeConstant:
	openXmlPart = new WordprocessingPrinterSettingsPart();
	return;
case CustomizationPart.RelationshipTypeConstant:
	openXmlPart = new CustomizationPart();
	return;
case WordAttachedToolbarsPart.RelationshipTypeConstant:
	openXmlPart = new WordAttachedToolbarsPart();
	return;
case VbaProjectPart.RelationshipTypeConstant:
	openXmlPart = new VbaProjectPart();
	return;
case VbaDataPart.RelationshipTypeConstant:
	openXmlPart = new VbaDataPart();
	return;
case WordprocessingCommentsExPart.RelationshipTypeConstant:
	openXmlPart = new WordprocessingCommentsExPart();
	return;
case WordprocessingPeoplePart.RelationshipTypeConstant:
	openXmlPart = new WordprocessingPeoplePart();
	return;
case ThumbnailPart.RelationshipTypeConstant:
	openXmlPart = new ThumbnailPart();
	return;
case CoreFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CoreFilePropertiesPart();
	return;
case ExtendedFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ExtendedFilePropertiesPart();
	return;
case CustomFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomFilePropertiesPart();
	return;
case DigitalSignatureOriginPart.RelationshipTypeConstant:
	openXmlPart = new DigitalSignatureOriginPart();
	return;
case XmlSignaturePart.RelationshipTypeConstant:
	openXmlPart = new XmlSignaturePart();
	return;
case QuickAccessToolbarCustomizationsPart.RelationshipTypeConstant:
	openXmlPart = new QuickAccessToolbarCustomizationsPart();
	return;
case RibbonExtensibilityPart.RelationshipTypeConstant:
	openXmlPart = new RibbonExtensibilityPart();
	return;
case RibbonAndBackstageCustomizationsPart.RelationshipTypeConstant:
	openXmlPart = new RibbonAndBackstageCustomizationsPart();
	return;
case WebExTaskpanesPart.RelationshipTypeConstant:
	openXmlPart = new WebExTaskpanesPart();
	return;

				}
            }
            else if (openXmlPackage is SpreadsheetDocument)
            {
                switch (relationshipType)
                {
					case WorkbookPart.RelationshipTypeConstant:
	openXmlPart = new WorkbookPart();
	return;
case CustomXmlPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlPart();
	return;
case CustomXmlPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlPropertiesPart();
	return;
case CalculationChainPart.RelationshipTypeConstant:
	openXmlPart = new CalculationChainPart();
	return;
case CellMetadataPart.RelationshipTypeConstant:
	openXmlPart = new CellMetadataPart();
	return;
case ConnectionsPart.RelationshipTypeConstant:
	openXmlPart = new ConnectionsPart();
	return;
case CustomXmlMappingsPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlMappingsPart();
	return;
case SharedStringTablePart.RelationshipTypeConstant:
	openXmlPart = new SharedStringTablePart();
	return;
case WorkbookRevisionHeaderPart.RelationshipTypeConstant:
	openXmlPart = new WorkbookRevisionHeaderPart();
	return;
case WorkbookRevisionLogPart.RelationshipTypeConstant:
	openXmlPart = new WorkbookRevisionLogPart();
	return;
case WorkbookUserDataPart.RelationshipTypeConstant:
	openXmlPart = new WorkbookUserDataPart();
	return;
case WorkbookStylesPart.RelationshipTypeConstant:
	openXmlPart = new WorkbookStylesPart();
	return;
case ThemePart.RelationshipTypeConstant:
	openXmlPart = new ThemePart();
	return;
case ImagePart.RelationshipTypeConstant:
	openXmlPart = new ImagePart();
	return;
case ThumbnailPart.RelationshipTypeConstant:
	openXmlPart = new ThumbnailPart();
	return;
case VolatileDependenciesPart.RelationshipTypeConstant:
	openXmlPart = new VolatileDependenciesPart();
	return;
case ChartsheetPart.RelationshipTypeConstant:
	openXmlPart = new ChartsheetPart();
	return;
case SpreadsheetPrinterSettingsPart.RelationshipTypeConstant:
	openXmlPart = new SpreadsheetPrinterSettingsPart();
	return;
case DrawingsPart.RelationshipTypeConstant:
	openXmlPart = new DrawingsPart();
	return;
case ChartPart.RelationshipTypeConstant:
	openXmlPart = new ChartPart();
	return;
case ChartDrawingPart.RelationshipTypeConstant:
	openXmlPart = new ChartDrawingPart();
	return;
case EmbeddedPackagePart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedPackagePart();
	return;
case ThemeOverridePart.RelationshipTypeConstant:
	openXmlPart = new ThemeOverridePart();
	return;
case ChartStylePart.RelationshipTypeConstant:
	openXmlPart = new ChartStylePart();
	return;
case ChartColorStylePart.RelationshipTypeConstant:
	openXmlPart = new ChartColorStylePart();
	return;
case DiagramColorsPart.RelationshipTypeConstant:
	openXmlPart = new DiagramColorsPart();
	return;
case DiagramDataPart.RelationshipTypeConstant:
	openXmlPart = new DiagramDataPart();
	return;
case SlidePart.RelationshipTypeConstant:
	openXmlPart = new SlidePart();
	return;
case DiagramPersistLayoutPart.RelationshipTypeConstant:
	openXmlPart = new DiagramPersistLayoutPart();
	return;
case DiagramLayoutDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new DiagramLayoutDefinitionPart();
	return;
case DiagramStylePart.RelationshipTypeConstant:
	openXmlPart = new DiagramStylePart();
	return;
case EmbeddedObjectPart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedObjectPart();
	return;
case VmlDrawingPart.RelationshipTypeConstant:
	openXmlPart = new VmlDrawingPart();
	return;
case LegacyDiagramTextPart.RelationshipTypeConstant:
	openXmlPart = new LegacyDiagramTextPart();
	return;
case EmbeddedControlPersistenceBinaryDataPart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedControlPersistenceBinaryDataPart();
	return;
case NotesSlidePart.RelationshipTypeConstant:
	openXmlPart = new NotesSlidePart();
	return;
case NotesMasterPart.RelationshipTypeConstant:
	openXmlPart = new NotesMasterPart();
	return;
case UserDefinedTagsPart.RelationshipTypeConstant:
	openXmlPart = new UserDefinedTagsPart();
	return;
case SlideLayoutPart.RelationshipTypeConstant:
	openXmlPart = new SlideLayoutPart();
	return;
case SlideMasterPart.RelationshipTypeConstant:
	openXmlPart = new SlideMasterPart();
	return;
case EmbeddedControlPersistencePart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedControlPersistencePart();
	return;
case SlideSyncDataPart.RelationshipTypeConstant:
	openXmlPart = new SlideSyncDataPart();
	return;
case WorksheetPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetPart();
	return;
case WorksheetCommentsPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetCommentsPart();
	return;
case PivotTablePart.RelationshipTypeConstant:
	openXmlPart = new PivotTablePart();
	return;
case PivotTableCacheDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new PivotTableCacheDefinitionPart();
	return;
case PivotTableCacheRecordsPart.RelationshipTypeConstant:
	openXmlPart = new PivotTableCacheRecordsPart();
	return;
case SingleCellTablePart.RelationshipTypeConstant:
	openXmlPart = new SingleCellTablePart();
	return;
case TableDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new TableDefinitionPart();
	return;
case QueryTablePart.RelationshipTypeConstant:
	openXmlPart = new QueryTablePart();
	return;
case ControlPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ControlPropertiesPart();
	return;
case CustomPropertyPart.RelationshipTypeConstant:
	openXmlPart = new CustomPropertyPart();
	return;
case WorksheetSortMapPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetSortMapPart();
	return;
case SlicersPart.RelationshipTypeConstant:
	openXmlPart = new SlicersPart();
	return;
case TimeLinePart.RelationshipTypeConstant:
	openXmlPart = new TimeLinePart();
	return;
case WebExtensionPart.RelationshipTypeConstant:
	openXmlPart = new WebExtensionPart();
	return;
case DialogsheetPart.RelationshipTypeConstant:
	openXmlPart = new DialogsheetPart();
	return;
case ExternalWorkbookPart.RelationshipTypeConstant:
	openXmlPart = new ExternalWorkbookPart();
	return;
case ExcelAttachedToolbarsPart.RelationshipTypeConstant:
	openXmlPart = new ExcelAttachedToolbarsPart();
	return;
case VbaProjectPart.RelationshipTypeConstant:
	openXmlPart = new VbaProjectPart();
	return;
case VbaDataPart.RelationshipTypeConstant:
	openXmlPart = new VbaDataPart();
	return;
case MacroSheetPart.RelationshipTypeConstant:
	openXmlPart = new MacroSheetPart();
	return;
case InternationalMacroSheetPart.RelationshipTypeConstant:
	openXmlPart = new InternationalMacroSheetPart();
	return;
case CustomDataPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomDataPropertiesPart();
	return;
case CustomDataPart.RelationshipTypeConstant:
	openXmlPart = new CustomDataPart();
	return;
case SlicerCachePart.RelationshipTypeConstant:
	openXmlPart = new SlicerCachePart();
	return;
case TimeLineCachePart.RelationshipTypeConstant:
	openXmlPart = new TimeLineCachePart();
	return;
case CoreFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CoreFilePropertiesPart();
	return;
case ExtendedFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ExtendedFilePropertiesPart();
	return;
case CustomFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomFilePropertiesPart();
	return;
case DigitalSignatureOriginPart.RelationshipTypeConstant:
	openXmlPart = new DigitalSignatureOriginPart();
	return;
case XmlSignaturePart.RelationshipTypeConstant:
	openXmlPart = new XmlSignaturePart();
	return;
case QuickAccessToolbarCustomizationsPart.RelationshipTypeConstant:
	openXmlPart = new QuickAccessToolbarCustomizationsPart();
	return;
case RibbonExtensibilityPart.RelationshipTypeConstant:
	openXmlPart = new RibbonExtensibilityPart();
	return;
case RibbonAndBackstageCustomizationsPart.RelationshipTypeConstant:
	openXmlPart = new RibbonAndBackstageCustomizationsPart();
	return;
case WebExTaskpanesPart.RelationshipTypeConstant:
	openXmlPart = new WebExTaskpanesPart();
	return;

                }
            }
            else if (openXmlPackage is PresentationDocument)
            {
                switch (relationshipType)
                {
					case PresentationPart.RelationshipTypeConstant:
	openXmlPart = new PresentationPart();
	return;
case CustomXmlPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlPart();
	return;
case CustomXmlPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomXmlPropertiesPart();
	return;
case FontPart.RelationshipTypeConstant:
	openXmlPart = new FontPart();
	return;
case PresentationPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new PresentationPropertiesPart();
	return;
case TableStylesPart.RelationshipTypeConstant:
	openXmlPart = new TableStylesPart();
	return;
case ThemePart.RelationshipTypeConstant:
	openXmlPart = new ThemePart();
	return;
case ImagePart.RelationshipTypeConstant:
	openXmlPart = new ImagePart();
	return;
case ViewPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ViewPropertiesPart();
	return;
case SlidePart.RelationshipTypeConstant:
	openXmlPart = new SlidePart();
	return;
case ChartPart.RelationshipTypeConstant:
	openXmlPart = new ChartPart();
	return;
case ChartDrawingPart.RelationshipTypeConstant:
	openXmlPart = new ChartDrawingPart();
	return;
case EmbeddedPackagePart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedPackagePart();
	return;
case ThemeOverridePart.RelationshipTypeConstant:
	openXmlPart = new ThemeOverridePart();
	return;
case ChartStylePart.RelationshipTypeConstant:
	openXmlPart = new ChartStylePart();
	return;
case ChartColorStylePart.RelationshipTypeConstant:
	openXmlPart = new ChartColorStylePart();
	return;
case DiagramColorsPart.RelationshipTypeConstant:
	openXmlPart = new DiagramColorsPart();
	return;
case DiagramDataPart.RelationshipTypeConstant:
	openXmlPart = new DiagramDataPart();
	return;
case WorksheetPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetPart();
	return;
case DrawingsPart.RelationshipTypeConstant:
	openXmlPart = new DrawingsPart();
	return;
case DiagramPersistLayoutPart.RelationshipTypeConstant:
	openXmlPart = new DiagramPersistLayoutPart();
	return;
case DiagramLayoutDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new DiagramLayoutDefinitionPart();
	return;
case DiagramStylePart.RelationshipTypeConstant:
	openXmlPart = new DiagramStylePart();
	return;
case WebExtensionPart.RelationshipTypeConstant:
	openXmlPart = new WebExtensionPart();
	return;
case VmlDrawingPart.RelationshipTypeConstant:
	openXmlPart = new VmlDrawingPart();
	return;
case LegacyDiagramTextPart.RelationshipTypeConstant:
	openXmlPart = new LegacyDiagramTextPart();
	return;
case PivotTablePart.RelationshipTypeConstant:
	openXmlPart = new PivotTablePart();
	return;
case PivotTableCacheDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new PivotTableCacheDefinitionPart();
	return;
case PivotTableCacheRecordsPart.RelationshipTypeConstant:
	openXmlPart = new PivotTableCacheRecordsPart();
	return;
case SingleCellTablePart.RelationshipTypeConstant:
	openXmlPart = new SingleCellTablePart();
	return;
case TableDefinitionPart.RelationshipTypeConstant:
	openXmlPart = new TableDefinitionPart();
	return;
case QueryTablePart.RelationshipTypeConstant:
	openXmlPart = new QueryTablePart();
	return;
case EmbeddedControlPersistencePart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedControlPersistencePart();
	return;
case EmbeddedControlPersistenceBinaryDataPart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedControlPersistenceBinaryDataPart();
	return;
case ControlPropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ControlPropertiesPart();
	return;
case EmbeddedObjectPart.RelationshipTypeConstant:
	openXmlPart = new EmbeddedObjectPart();
	return;
case CustomPropertyPart.RelationshipTypeConstant:
	openXmlPart = new CustomPropertyPart();
	return;
case WorksheetSortMapPart.RelationshipTypeConstant:
	openXmlPart = new WorksheetSortMapPart();
	return;
case SlicersPart.RelationshipTypeConstant:
	openXmlPart = new SlicersPart();
	return;
case TimeLinePart.RelationshipTypeConstant:
	openXmlPart = new TimeLinePart();
	return;
case SlideCommentsPart.RelationshipTypeConstant:
	openXmlPart = new SlideCommentsPart();
	return;
case NotesSlidePart.RelationshipTypeConstant:
	openXmlPart = new NotesSlidePart();
	return;
case NotesMasterPart.RelationshipTypeConstant:
	openXmlPart = new NotesMasterPart();
	return;
case UserDefinedTagsPart.RelationshipTypeConstant:
	openXmlPart = new UserDefinedTagsPart();
	return;
case SlideLayoutPart.RelationshipTypeConstant:
	openXmlPart = new SlideLayoutPart();
	return;
case SlideMasterPart.RelationshipTypeConstant:
	openXmlPart = new SlideMasterPart();
	return;
case SlideSyncDataPart.RelationshipTypeConstant:
	openXmlPart = new SlideSyncDataPart();
	return;
case CommentAuthorsPart.RelationshipTypeConstant:
	openXmlPart = new CommentAuthorsPart();
	return;
case HandoutMasterPart.RelationshipTypeConstant:
	openXmlPart = new HandoutMasterPart();
	return;
case LegacyDiagramTextInfoPart.RelationshipTypeConstant:
	openXmlPart = new LegacyDiagramTextInfoPart();
	return;
case VbaProjectPart.RelationshipTypeConstant:
	openXmlPart = new VbaProjectPart();
	return;
case VbaDataPart.RelationshipTypeConstant:
	openXmlPart = new VbaDataPart();
	return;
case CoreFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CoreFilePropertiesPart();
	return;
case ExtendedFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new ExtendedFilePropertiesPart();
	return;
case CustomFilePropertiesPart.RelationshipTypeConstant:
	openXmlPart = new CustomFilePropertiesPart();
	return;
case ThumbnailPart.RelationshipTypeConstant:
	openXmlPart = new ThumbnailPart();
	return;
case DigitalSignatureOriginPart.RelationshipTypeConstant:
	openXmlPart = new DigitalSignatureOriginPart();
	return;
case XmlSignaturePart.RelationshipTypeConstant:
	openXmlPart = new XmlSignaturePart();
	return;
case QuickAccessToolbarCustomizationsPart.RelationshipTypeConstant:
	openXmlPart = new QuickAccessToolbarCustomizationsPart();
	return;
case RibbonExtensibilityPart.RelationshipTypeConstant:
	openXmlPart = new RibbonExtensibilityPart();
	return;
case RibbonAndBackstageCustomizationsPart.RelationshipTypeConstant:
	openXmlPart = new RibbonAndBackstageCustomizationsPart();
	return;
case WebExTaskpanesPart.RelationshipTypeConstant:
	openXmlPart = new WebExTaskpanesPart();
	return;

                }
            }
            else
            {
                System.Diagnostics.Debug.Assert(false);				
            }
            return;
        }
 private static void GenerateImagePart(OpenXmlPart part, byte[] imageFileBytes)
 {
     // Write the contents of the image to the ImagePart.
     using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
     {
         writer.Write(imageFileBytes);
         writer.Flush();
     }
 }
        private List<string> GetReferencedAttributes(ValidationContext context)
        {
            if (_referencedAttributes == null)
            {
                _referencedAttributes = new List<string>();

                OpenXmlPart part = GetReferencedPart(context, _partPath);

                this._relatedPart = part;

                if (part != null)
                {
                    ValidationContext partContext = new ValidationContext();

                    partContext.FileFormat = context.FileFormat;
                    partContext.Package = context.Package;
                    partContext.Part = part;
                    partContext.Element = part.RootElement;

                    ValidationTraverser.ValidatingTraverse(partContext, this.ElementTraverse, null, null);
                }
            }

            return _referencedAttributes;
        }
Esempio n. 59
-1
 public static XmlDocument GetXmlDocument(OpenXmlPart part)
 {
     XmlDocument xmlDoc = new XmlDocument();
     using (Stream partStream = part.GetStream())
     using (XmlReader partXmlReader = XmlReader.Create(partStream))
         xmlDoc.Load(partXmlReader);
     return xmlDoc;
 }
 public static void TransformPartToSingleCharacterRuns(OpenXmlPart part)
 {
     // After transforming to single character runs, Rsid info will be invalid, so
     // remove from the part.
     XDocument xDoc = part.GetXDocument();
     XElement newRoot = (XElement)RemoveRsidTransform(xDoc.Root);
     newRoot = (XElement)SingleCharacterRunTransform(newRoot);
     xDoc.Elements().First().ReplaceWith(newRoot);
     part.PutXDocument();
 }