コード例 #1
0
ファイル: WordUtility.cs プロジェクト: k741030ken/Attendant
        /// <summary>
        ///
        /// </summary>
        /// <param name="oxp"></param>
        /// <param name="message"></param>
        public static void Parse(OpenXmlPart oxp, InputMessage message)
        {
            string wordContent = null;

            using (StreamReader sr = new StreamReader(oxp.GetStream()))
            {
                wordContent = sr.ReadToEnd();
            }

            List <string> lists = GetAllKeys(wordContent);
            StringBuilder sb    = new StringBuilder(wordContent);

            foreach (var item in lists)
            {
                var field = message.Fields.Where(p => p.VariableID == item).FirstOrDefault();
                if (field != null)
                {
                    sb.Replace("[$" + item + "$]", field.VariableValue);
                }
                else
                {
                    sb.Replace("[$" + item + "$]", string.Empty);
                }
            }

            using (StreamWriter sw = new StreamWriter(oxp.GetStream(FileMode.Create)))
            {
                sw.Write(sb.ToString());
            }
        }
コード例 #2
0
ファイル: DocxHelper.cs プロジェクト: IreneGigabit/MyLibrary
        /// <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); }
        }
コード例 #3
0
        /// <summary>
        /// swaps out bad entity type codes for good ones in the given Word Doc part
        /// </summary>
        /// <param name="part">the Open Xml Part needing to be changed</param>
        /// <param name="sourceOTC">source type code needing to be changed</param>
        /// <param name="targetOTC">destination type code</param>
        private void UpdateDocumentPart(OpenXmlPart part, string sourceETC, int sourceOTC, int targetOTC)
        {
            string docText;

            using (StreamReader sr = new StreamReader(part.GetStream())) {
                docText = sr.ReadToEnd();
            }

            docText = docText.Replace($"{sourceETC}/{sourceOTC}/", $"{sourceETC}/{targetOTC}/");

            using (StreamWriter sw = new StreamWriter(part.GetStream())) {
                sw.Write(docText);
                sw.Flush();
            }
        }
コード例 #4
0
 public static XDocument GetXDocument(this OpenXmlPart part)
 {
     try
     {
         XDocument partXDocument = part.Annotation <XDocument>();
         if (partXDocument != null)
         {
             return(partXDocument);
         }
         using (Stream partStream = part.GetStream())
         {
             if (partStream.Length == 0)
             {
                 partXDocument             = new XDocument();
                 partXDocument.Declaration = new XDeclaration("1.0", "UTF-8", "yes");
             }
             else
             {
                 using (XmlReader partXmlReader = XmlReader.Create(partStream))
                     partXDocument = XDocument.Load(partXmlReader);
             }
         }
         part.AddAnnotation(partXDocument);
         return(partXDocument);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
コード例 #5
0
        private static void WriteRootElement(OpenXmlPart part, XElement partRootElement)
        {
            using Stream stream    = part.GetStream(FileMode.Create, FileAccess.Write);
            using XmlWriter writer = XmlWriter.Create(stream);

            partRootElement.WriteTo(writer);
        }
コード例 #6
0
 public void GenerateCoreFilePropertiesPart1(OpenXmlPart part)
 {
     System.IO.StreamWriter writer = new System.IO.StreamWriter(part.GetStream());
     writer.Write("<?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>Horacio Santoyo Liahut</dc:creator><cp:lastModifiedBy>Horacio Santoyo Liahut</cp:lastModifiedBy><dcterms:created xsi:type=\"dcterms:W3CDTF\">2009-09-11T18:43:48Z</dcterms:created><dcterms:modified xsi:type=\"dcterms:W3CDTF\">2009-09-11T18:44:25Z</dcterms:modified></cp:coreProperties>");
     writer.Flush();
     writer.Close();
 }
コード例 #7
0
        /// <summary>
        /// Get RootElement of the current part.
        /// </summary>
        /// <param name="part">Current Part</param>
        /// <returns>Return Root element of the pass-in part</returns>
        public static OpenXmlPartRootElement RootElement(this OpenXmlPart part)
        {
            if (null == part)
            {
                throw new ArgumentNullException(nameof(part));
            }

            if (part is CustomXmlPart)
            {
                XmlDocument xmlDoc = new XmlDocument();
                using (var stream = part.GetStream())
                    xmlDoc.Load(stream);
                if (part.IsBibliographyPart())
                {
                    return(new Sources(xmlDoc.DocumentElement.OuterXml));
                }

                else if (part.IsInkPart())
                {
                    return(new DocumentFormat.OpenXml.InkML.Ink(xmlDoc.DocumentElement.OuterXml));
                }
            }

            var flag       = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
            var properties = part.GetType().GetProperties(flag)
                             .Where(p => p.PropertyType.IsSubclassOf(typeof(OpenXmlPartRootElement)));

            return(null == properties.FirstOrDefault() ?
                   null : properties.First().GetValue(part, null) as OpenXmlPartRootElement);
        }
コード例 #8
0
        private static void CopyPartRecursive(OpenXmlPart destinationParent, OpenXmlPart part, string id, IDictionary <OpenXmlPart, OpenXmlPart> mapping)
        {
            if (part is IFixedContentTypePart)
            {
                OpenXmlPart parent = part.GetParentParts().Select(p => mapping.TryGetValue(p, out OpenXmlPart mappedParent) ? mappedParent : null).FirstOrDefault(p => p != null);

                if (mapping.TryGetValue(part, out OpenXmlPart existingPart))
                {
                    destinationParent.CreateRelationshipToPart(existingPart);
                }
                else
                {
                    MethodInfo  method  = typeof(OpenXmlPart).GetTypeInfo().GetMethod(nameof(OpenXmlPart.AddNewPart), new Type[] { typeof(string) }).MakeGenericMethod(part.GetType());
                    OpenXmlPart newPart = method.Invoke(parent, new object[] { id }) as OpenXmlPart;
                    mapping.Add(part, newPart);

                    using (Stream data = part.GetStream())
                    {
                        newPart.FeedData(data);
                    }

                    foreach (IdPartPair relationship in part.Parts)
                    {
                        CopyPartRecursive(newPart, relationship.OpenXmlPart, relationship.RelationshipId, mapping);
                    }
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Saves the cached <see cref="XDocument"/> to the the given <see cref="OpenXmlPart"/>,
        /// indending the XML markup and creating new lines for attributes.
        /// </summary>
        /// <param name="part">The <see cref="OpenXmlPart"/>.</param>
        public static void PutXDocumentWithFormatting(this OpenXmlPart part)
        {
            if (part == null)
            {
                throw new ArgumentNullException(nameof(part));
            }

            XDocument partXDocument = part.GetXDocument();

            if (partXDocument != null)
            {
                using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write))
                {
                    var settings = new XmlWriterSettings
                    {
                        Indent              = true,
                        OmitXmlDeclaration  = true,
                        NewLineOnAttributes = true
                    };

                    using (XmlWriter partXmlWriter = XmlWriter.Create(partStream, settings))
                    {
                        partXDocument.Save(partXmlWriter);
                    }
                }
            }
        }
コード例 #10
0
        public async Task ReplaceInternalImage(MemoryStream memoryStream, string oldImagesPlaceholderText, string image)
        {
            if (image != null)
            {
                string[] splitStringImage = image.Split(",");

                var newImageBytes = Convert.FromBase64String(splitStringImage[1]);

                using (WordprocessingDocument document = WordprocessingDocument.Open(memoryStream, true))
                {
                    IEnumerable <Drawing> drawings = document.MainDocumentPart.Document.Descendants <Drawing>().ToList();
                    foreach (Drawing drawing in drawings)
                    {
                        DocProperties dpr = drawing.Descendants <DocProperties>().FirstOrDefault();
                        if (dpr != null && dpr.Name == oldImagesPlaceholderText)
                        {
                            foreach (A.Blip b in drawing.Descendants <A.Blip>().ToList())
                            {
                                OpenXmlPart imagePart = document.MainDocumentPart.GetPartById(b.Embed);

                                if (newImageBytes != null)
                                {
                                    using (var writer = new BinaryWriter(imagePart.GetStream()))
                                    {
                                        writer.Write(newImageBytes);
                                    }
                                }
                            }
                        }
                    }
                    document.Close();
                }
            }
        }
コード例 #11
0
ファイル: MCSupport.cs プロジェクト: OfficeDev/Open-XML-SDK
        public void WriteExtraAttr()
        {
            using (var testStream = GetStream(TestFiles.HelloO14, true))
            {
                using (var doc = WordprocessingDocument.Open(testStream, true))
                {
                    // Touch the font table part.
                    var fontTablePart = doc.MainDocumentPart.GetPartsOfType <FontTablePart>().First();
                    var root          = fontTablePart.Fonts;

                    var docNode = doc.MainDocumentPart.Document;
                }

                testStream.Position = 0;

                // Open it again, mark sure in font part, the "w14" prefix is still recognized
                using (var testDocument = WordprocessingDocument.Open(testStream, true))
                {
                    OpenXmlPart target = testDocument.MainDocumentPart.FontTablePart;

                    using (var stream = target.GetStream())
                        using (var reader = System.Xml.XmlReader.Create(stream))
                        {
                            reader.Read();
                            reader.MoveToContent();

                            var ns = reader.LookupNamespace("w14");
                            Assert.NotNull(ns);
                        }
                }
            }
        }
コード例 #12
0
 public static MemoryStream CopyToMemoryStream(this OpenXmlPart part)
 {
     using (var stream = part.GetStream())
     {
         return(stream.CopyToMemoryStream());
     }
 }
コード例 #13
0
ファイル: MCSupport.cs プロジェクト: tarunchopra/Vs2017-Issue
        public void WriteExtraAttr()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.HelloO14, file);

            //open it using the sdk
            using (var doc = WordprocessingDocument.Open(file, true))
            {
                // Touch the font table part.
                var fontTablePart = doc.MainDocumentPart.GetPartsOfType <FontTablePart>().First();
                var root          = fontTablePart.Fonts;

                var docNode = doc.MainDocumentPart.Document;
            }


            //open it again, mark sure in font part, the "w14" prefix is still recognized
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart target = testDocument.MainDocumentPart.FontTablePart;
                using (Stream stream = target.GetStream())
                    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stream))
                    {
                        reader.Read();
                        reader.MoveToContent();

                        var ns = reader.LookupNamespace("w14");
                        Assert.NotEqual(null, ns);
                    }
            }
            System.IO.File.Delete(file);
        }
コード例 #14
0
        private List <string> GetCellStrValues(C.Formula formula, OpenXmlPart xlsxPackagePart) //EmbeddedPackagePart : OpenXmlPart
        {
            var exist = _spContext.PreSettings.XlsxDocuments.TryGetValue(xlsxPackagePart, out var xlsxDoc);

            if (!exist)
            {
                xlsxDoc = SpreadsheetDocument.Open(xlsxPackagePart.GetStream(), false);
                _spContext.PreSettings.XlsxDocuments.Add(xlsxPackagePart, xlsxDoc);
            }
            var filteredFormula = formula.Text.Replace("'", string.Empty, StringComparison.Ordinal)
                                  .Replace("$", string.Empty, StringComparison.Ordinal); //eg: Sheet1!$A$2:$A$5 -> Sheet1!A2:A5
            var    sheetNameAndCellsFormula = filteredFormula.Split('!');                //eg: Sheet1!A2:A5 -> ['Sheet1', 'A2:A5']
            var    wbPart    = xlsxDoc.WorkbookPart;
            string sheetId   = wbPart.Workbook.Descendants <Sheet>().First(s => sheetNameAndCellsFormula[0].Equals(s.Name, StringComparison.Ordinal)).Id;
            var    wsPart    = (WorksheetPart)wbPart.GetPartById(sheetId);
            var    sdkCells  = wsPart.Worksheet.Descendants <Cell>();                                 //TODO: use HashSet
            var    addresses = new CellFormulaParser(sheetNameAndCellsFormula[1]).GetCellAddresses(); //eg: [1] = 'A2:A5'

            var strValues = new List <string>(addresses.Count);

            foreach (var address in addresses)
            {
                var sdkCellValueStr = sdkCells.First(c => c.CellReference == address).InnerText;
                strValues.Add(sdkCellValueStr);
            }

            xlsxDoc.Close();
            return(strValues);
        }
コード例 #15
0
        private void VerifyDocumentStart(OpenXmlPart part, bool?standalone)
        {
            var reader = XmlReader.Create(part.GetStream());

            reader.Read();

            Log.Comment("verify the part contains XmlDeclaration");
            Log.VerifyTrue(reader.NodeType == XmlNodeType.XmlDeclaration, "expected: XmlDeclaration <> actual: {0}", reader.NodeType);
            Log.Comment("verify the version is 1.0");
            Log.VerifyTrue(reader.GetAttribute("version") == "1.0", "expected: 1.0 <> actual:{0}", reader.GetAttribute("version"));

            var standaloneValue = reader.GetAttribute("standalone");

            if (standalone.HasValue)
            {
                Log.Comment("verify if the standalone is set correctly");
                Log.VerifyTrue(
                    standaloneValue.Equals(standalone.Value == true ? "yes" : "no", StringComparison.OrdinalIgnoreCase),
                    "expected: {0} <> actual: {1}", standalone.Value == true ? "yes" : "no", standaloneValue);
            }
            else
            {
                Log.Comment("verify the standalone is not presented");
                Log.VerifyTrue(standaloneValue == null, "expected: null <> actual: {0}", standaloneValue);
            }
        }
コード例 #16
0
        /// <summary>
        /// Gets the XDocument for a part
        /// </summary>
        public static XDocument GetXDocument(this OpenXmlPart part)
        {
            XDocument xdoc = part.Annotation <XDocument>();

            if (xdoc != null)
            {
                return(xdoc);
            }
            try
            {
                using (StreamReader sr = new StreamReader(part.GetStream()))
                    using (XmlReader xr = XmlReader.Create(sr))
                    {
                        xdoc           = XDocument.Load(xr);
                        xdoc.Changed  += ElementChanged;
                        xdoc.Changing += ElementChanged;
                    }
            }
            catch (XmlException)
            {
                xdoc = new XDocument();
                xdoc.AddAnnotation(new ChangedSemaphore());
            }
            part.AddAnnotation(xdoc);
            return(xdoc);
        }
コード例 #17
0
        /// <summary>
        /// Gets the first element from custom XML part.
        /// </summary>
        /// <param name="customXmlPart">The custom XML part.</param>
        /// <param name="elementName">Name of the element.</param>
        /// <returns>Returns the first element that matches the element name and the custom xml part</returns>
        public XElement GetFirstElementFromCustomXmlPart(OpenXmlPart customXmlPart, string elementName)
        {
            if (customXmlPart == null)
            {
                throw new ArgumentNullException("customXmlPart");
            }

            if (string.IsNullOrEmpty(elementName))
            {
                throw new ArgumentNullException("elementName");
            }

            XDocument customPartDoc;

            using (var reader = XmlReader.Create(customXmlPart.GetStream(FileMode.Open, FileAccess.Read)))
            {
                customPartDoc = XDocument.Load(reader);
            }

            var elementXName = XName.Get(elementName, this.NamespaceUri.ToString());
            var element      = (from e in customPartDoc.Descendants(elementXName)
                                select e).FirstOrDefault();

            return(element);
        }
コード例 #18
0
 /// <summary>
 /// Load the DOM tree from the Open XML part.
 /// </summary>
 /// <param name="openXmlPart">The part this root element to be loaded from.</param>
 /// <exception cref="InvalidDataException">Thrown when the part contains an incorrect root element.</exception>
 internal void LoadFromPart(OpenXmlPart openXmlPart)
 {
     using (Stream partStream = openXmlPart.GetStream(FileMode.Open))
     {
         this.LoadFromPart(openXmlPart, partStream);
     }
 }
コード例 #19
0
        public static XDocument GetXDocument(this OpenXmlPart part)
        {
            if (part == null)
            {
                throw new ArgumentNullException(nameof(part));
            }

            var partXDocument = part.Annotation <XDocument>();

            if (partXDocument != null)
            {
                return(partXDocument);
            }

            using (Stream partStream = part.GetStream())
            {
                if (partStream.Length == 0)
                {
                    partXDocument = new XDocument {
                        Declaration = new XDeclaration("1.0", "UTF-8", "yes")
                    };
                }
                else
                {
                    using (XmlReader partXmlReader = XmlReader.Create(partStream))
                    {
                        partXDocument = XDocument.Load(partXmlReader);
                    }
                }
            }

            part.AddAnnotation(partXDocument);
            return(partXDocument);
        }
コード例 #20
0
ファイル: DataExtensions.cs プロジェクト: lulzzz/CMS-Packages
 public static XElement GetXElement(this OpenXmlPart part)
 {
     return(XElement.Load(
                XmlReader.Create(
                    new StreamReader(part.GetStream())
                    )
                ));
 }
コード例 #21
0
ファイル: Export.cs プロジェクト: radtek/DigitalTvBilling
 protected void AddPartXml(OpenXmlPart part, string xml)
 {
     using (Stream stream = part.GetStream())
     {
         byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
         stream.Write(buffer, 0, buffer.Length);
     }
 }
コード例 #22
0
        /// <summary>
        /// TODO: move into utilities
        /// </summary>
        /// <param name="oxp"></param>
        /// <param name="Text"></param>

        internal void WriteToPart(OpenXmlPart oxp, string Text)
        {
            using (Stream stream = oxp.GetStream())
            {
                byte[] buf = (new UTF8Encoding()).GetBytes(Text);
                stream.Write(buf, 0, buf.Length);
            }
        }
コード例 #23
0
 private static void AssertXmlContentEquals(OpenXmlPart part, string expected)
 {
     using (Stream stream = part.GetStream(FileMode.Open))
         using (var reader = new StreamReader(stream))
         {
             Assert.Equal(expected, reader.ReadToEnd().Trim());
         }
 }
コード例 #24
0
 protected void WriteToPart(OpenXmlPart oxp, string text)
 {
     using (var stream = oxp.GetStream())
     {
         var bytes = new UTF8Encoding().GetBytes(text);
         stream.Write(bytes, 0, bytes.Length);
     }
 }
コード例 #25
0
 public static void PutXDocument(this OpenXmlPart part, XDocument document)
 {
     using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write))
         using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
             document.Save(partXmlWriter);
     part.RemoveAnnotations <XDocument>();
     part.AddAnnotation(document);
 }
コード例 #26
0
 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();
     }
 }
コード例 #27
0
        public static void SavePartAs(OpenXmlPart part, string filePath)
        {
            Stream partStream = part.GetStream(FileMode.Open, FileAccess.Read);

            byte[] partContent = new byte[partStream.Length];
            partStream.Read(partContent, 0, (int)partStream.Length);

            File.WriteAllBytes(filePath, partContent);
        }
コード例 #28
0
        /// <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) : this()
        {
            if (openXmlPart == null)
            {
                throw new ArgumentNullException(nameof(openXmlPart));
            }

            _xmlReader = CreateReader(openXmlPart.GetStream(FileMode.Open), true, openXmlPart.MaxCharactersInPart, out _standalone, out _encoding);
        }
コード例 #29
0
        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);
        }
コード例 #30
0
    public static void GenerateImagePart(OpenXmlPart part)
    {
        using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
        {
            writer.Write(System.Convert.FromBase64String(EmbedExcelIntoWordDoc.Properties.Resource1.BASE64_STRING_EXCEL_ICON));

            writer.Flush();
        }
    }
コード例 #31
0
        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;
	    }
コード例 #32
0
ファイル: DocumentExtensions.cs プロジェクト: huamouse/Taoqi
 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);
 }
コード例 #33
0
        /// <summary>
        /// Gets the first element from custom XML part.
        /// </summary>
        /// <param name="customXmlPart">The custom XML part.</param>
        /// <param name="elementName">Name of the element.</param>
        /// <returns>Returns the first element that matches the element name and the custom xml part</returns>
        public XElement GetFirstElementFromCustomXmlPart(OpenXmlPart customXmlPart, string elementName)
        {
            if (customXmlPart == null)
            {
                throw new ArgumentNullException("customXmlPart");
            }

            if (string.IsNullOrEmpty(elementName))
            {
                throw new ArgumentNullException("elementName");
            }

            XDocument customPartDoc;

            using (var reader = XmlReader.Create(customXmlPart.GetStream(FileMode.Open, FileAccess.Read)))
            {
                customPartDoc = XDocument.Load(reader);
            }

            var elementXName = XName.Get(elementName, this.NamespaceUri.ToString());
            var element = (from e in customPartDoc.Descendants(elementXName)
                                select e).FirstOrDefault();

            return element;
        }
コード例 #34
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("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);
 }
コード例 #35
0
 /// <summary>
 /// Load the DOM tree from the Open XML part.
 /// </summary>
 /// <param name="openXmlPart">The part this root element to be loaded from.</param>
 /// <exception cref="InvalidDataException">Thrown when the part contains an incorrect root element.</exception>
 internal void LoadFromPart(OpenXmlPart openXmlPart)
 {
     using (Stream partStream = openXmlPart.GetStream(FileMode.Open))
     {
         this.LoadFromPart(openXmlPart, partStream);
     }
 }
コード例 #36
0
 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();
     }
 }
コード例 #37
0
ファイル: OpenXmlWriter.cs プロジェクト: eriawan/Open-XML-SDK
        /// <summary>
        /// Initializes a new instance of the OpenXmlPartWriter.
        /// </summary>
        /// <param name="openXmlPart">The OpenXmlPart to be written to.</param>
        /// <param name="encoding">The encoding for the XML stream.</param>
        public OpenXmlPartWriter(OpenXmlPart openXmlPart, Encoding encoding)
        {
            if (openXmlPart == null)
            {
                throw new ArgumentNullException("openXmlPart");
            }

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

            Stream partStream = openXmlPart.GetStream(FileMode.Create);
            this.Init(partStream, /*closeOutput*/true, encoding);
        }
コード例 #38
0
 public static void PutXmlDocument(OpenXmlPart part, XmlDocument xmlDoc)
 {
     using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write))
     using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
         xmlDoc.Save(partXmlWriter);
 }
コード例 #39
0
        /// <summary>
        /// Save the DOM into the OpenXML part.
        /// </summary>
        internal void SaveToPart(OpenXmlPart openXmlPart)
        {
            if (openXmlPart == null)
            {
                throw new ArgumentNullException("openXmlPart");
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.CloseOutput = true;
            // default is UTF8, Indent=false, OmitXmlDeclaration=false, NewLineOnAttributes=false
            // settings.Indent = false;
            // settings.Encoding = Encoding.UTF8;
            // settings.OmitXmlDeclaration = false;
            // settings.NewLineOnAttributes = false;

            using (Stream partStream = openXmlPart.GetStream(FileMode.Create))
            using (XmlWriter xmlWriter = XmlWriter.Create(partStream, settings))
            {
                if (this._standaloneDeclaration != null)
                {
                    xmlWriter.WriteStartDocument(this._standaloneDeclaration.Value);
                }

                this.WriteTo(xmlWriter);

                // fix bug #242463.
                // Do not call WriteEndDocument if this root element is not parsed.
                // In that case, the WriteTo() just call WriteRaw() with the raw xml, so no WriteStartElement() be called.
                // So, the XmlWriter still on document start state. Call WriteEndDocument() will cause exception.

                if (this.XmlParsed)
                {
                    xmlWriter.WriteEndDocument();
                }
            }
        }
コード例 #40
0
        public static void SavePartAs(OpenXmlPart part, string filePath)
        {
            Stream partStream = part.GetStream(FileMode.Open, FileAccess.Read);
            byte[] partContent = new byte[partStream.Length];
            partStream.Read(partContent, 0, (int)partStream.Length);

            File.WriteAllBytes(filePath, partContent);
        }
コード例 #41
0
    private void GenerateImagePart(OpenXmlPart part, string imagePath, ref long imageWidthEMU, ref long imageHeightEMU)
    {
        byte[] imageFileBytes;
        Bitmap imageFile;

        using (FileStream fsImageFile = File.OpenRead(imagePath))
        {
            imageFileBytes = new byte[fsImageFile.Length];
            fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

            imageFile = new Bitmap(fsImageFile);
        }

        imageWidthEMU = (long)((imageFile.Width / imageFile.HorizontalResolution) * 914400L * 7);
        imageHeightEMU = (long)((imageFile.Height / imageFile.VerticalResolution) * 914400L * 7);

        using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
        {
            writer.Write(imageFileBytes);
            writer.Flush();
        }
    }
コード例 #42
0
 private XDocument LoadXDocument(OpenXmlPart part)
 {
     XDocument xdoc;
     using (StreamReader reader = new StreamReader(part.GetStream()))
         xdoc = XDocument.Load(XmlReader.Create(reader));
     return xdoc;
 }
コード例 #43
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();
            }
        }
コード例 #44
-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;
 }