예제 #1
0
파일: DocX.cs 프로젝트: xiaohszx/DocX
        /// <summary>
        /// Save this document back to the location it was loaded from.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document.
        /// using (var document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Add an Image from a file.
        ///     document.AddImage(@"C:\Example\Image.jpg");
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        /// <!--
        /// Bug found and fixed by krugs525 on August 12 2009.
        /// Use TFS compare to see exact code change.
        /// -->
        public override void Save()
        {
            // Save the main document
            using (TextWriter tw = new StreamWriter(new PackagePartStream(this.PackagePart.GetStream(FileMode.Create, FileAccess.Write))))
            {
                _mainDoc.Save(tw, SaveOptions.None);
            }

            if ((_settings == null) || !this.isProtected)
            {
                using (TextReader textReader = new StreamReader(_settingsPart.GetStream()))
                {
                    _settings = XDocument.Load(textReader);
                }
            }

            // Save the header/footer content.
            this.SaveHeadersFooters();

            // Save the settings document.
            using (TextWriter tw = new StreamWriter(new PackagePartStream(_settingsPart.GetStream(FileMode.Create, FileAccess.Write))))
            {
                _settings.Save(tw, SaveOptions.None);
            }

            if (_endnotesPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_endnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _endnotes.Save(tw, SaveOptions.None);
                }
            }

            if (_footnotesPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_footnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _footnotes.Save(tw, SaveOptions.None);
                }
            }

            if (_stylesPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_stylesPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _styles.Save(tw, SaveOptions.None);
                }
            }

            if (_stylesWithEffectsPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_stylesWithEffectsPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _stylesWithEffects.Save(tw, SaveOptions.None);
                }
            }

            if (_numberingPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_numberingPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _numbering.Save(tw, SaveOptions.None);
                }
            }

            if (_fontTablePart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_fontTablePart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _fontTable.Save(tw, SaveOptions.None);
                }
            }

            // Close the document so that it can be saved.
            _package.Flush();

            #region Save this document back to a file or stream, that was specified by the user at save time.
            if (_filename != null)
            {
                using (FileStream fs = new FileStream(_filename, FileMode.Create))
                {
                    if (_memoryStream.CanSeek)
                    {
                        // Write to the beginning of the stream
                        _memoryStream.Position = 0;
                        HelperFunctions.CopyStream(_memoryStream, fs);
                    }
                    else
                    {
                        fs.Write(_memoryStream.ToArray(), 0, (int)_memoryStream.Length);
                    }
                }
            }
            else if (_stream.CanSeek) //Check if stream can be seeked to support System.Web.HttpResponseStream.
            {
                // Set the length of this stream to 0
                _stream.SetLength(0);

                // Write to the beginning of the stream
                _stream.Position = 0;

                _memoryStream.WriteTo(_stream);
                _memoryStream.Flush();
            }
            #endregion
        }
예제 #2
0
        /// <summary>
        /// Save this document back to the location it was loaded from.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document.
        /// using (var document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Add an Image from a file.
        ///     document.AddImage(@"C:\Example\Image.jpg");
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        /// <!--
        /// Bug found and fixed by krugs525 on August 12 2009.
        /// Use TFS compare to see exact code change.
        /// -->
        public override void Save()
        {
            var headers = this.Headers;
            var footers = this.Footers;

            // Save the main document
            using (TextWriter tw = new StreamWriter(new PackagePartStream(this.PackagePart.GetStream(FileMode.Create, FileAccess.Write))))
            {
                _mainDoc.Save(tw, SaveOptions.None);
            }

            if ((_settings == null) || !this.isProtected)
            {
                using (TextReader textReader = new StreamReader(_settingsPart.GetStream()))
                {
                    _settings = XDocument.Load(textReader);
                }
            }

            var body   = _mainDoc.Root.Element(w + "body");
            var sectPr = body.Descendants(w + "sectPr").FirstOrDefault();

            if (sectPr != null)
            {
                var evenHeaderRef =
                    (
                        from e in _mainDoc.Descendants(w + "headerReference")
                        let type = e.Attribute(w + "type")
                                   where type != null && type.Value.Equals("even", StringComparison.CurrentCultureIgnoreCase)
                                   select e.Attribute(r + "id").Value
                    ).LastOrDefault();

                if (evenHeaderRef != null)
                {
                    var even = headers.Even.Xml;

                    var target = PackUriHelper.ResolvePartUri
                                 (
                        this.PackagePart.Uri,
                        this.PackagePart.GetRelationship(evenHeaderRef).TargetUri
                                 );

                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            even
                        ).Save(tw, SaveOptions.None);
                    }
                }

                var oddHeaderRef =
                    (
                        from e in _mainDoc.Descendants(w + "headerReference")
                        let type = e.Attribute(w + "type")
                                   where type != null && type.Value.Equals("default", StringComparison.CurrentCultureIgnoreCase)
                                   select e.Attribute(r + "id").Value
                    ).LastOrDefault();

                if (oddHeaderRef != null)
                {
                    var odd = headers.Odd.Xml;

                    var target = PackUriHelper.ResolvePartUri
                                 (
                        this.PackagePart.Uri,
                        this.PackagePart.GetRelationship(oddHeaderRef).TargetUri
                                 );

                    // Save header1
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            odd
                        ).Save(tw, SaveOptions.None);
                    }
                }

                var firstHeaderRef =
                    (
                        from e in _mainDoc.Descendants(w + "headerReference")
                        let type = e.Attribute(w + "type")
                                   where type != null && type.Value.Equals("first", StringComparison.CurrentCultureIgnoreCase)
                                   select e.Attribute(r + "id").Value
                    ).LastOrDefault();

                if (firstHeaderRef != null)
                {
                    var first  = headers.First.Xml;
                    var target = PackUriHelper.ResolvePartUri
                                 (
                        this.PackagePart.Uri,
                        this.PackagePart.GetRelationship(firstHeaderRef).TargetUri
                                 );

                    // Save header3
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            first
                        ).Save(tw, SaveOptions.None);
                    }
                }

                var oddFooterRef =
                    (
                        from e in _mainDoc.Descendants(w + "footerReference")
                        let type = e.Attribute(w + "type")
                                   where type != null && type.Value.Equals("default", StringComparison.CurrentCultureIgnoreCase)
                                   select e.Attribute(r + "id").Value
                    ).LastOrDefault();

                if (oddFooterRef != null)
                {
                    var odd    = footers.Odd.Xml;
                    var target = PackUriHelper.ResolvePartUri
                                 (
                        this.PackagePart.Uri,
                        this.PackagePart.GetRelationship(oddFooterRef).TargetUri
                                 );

                    // Save header1
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            odd
                        ).Save(tw, SaveOptions.None);
                    }
                }

                var evenFooterRef =
                    (
                        from e in _mainDoc.Descendants(w + "footerReference")
                        let type = e.Attribute(w + "type")
                                   where type != null && type.Value.Equals("even", StringComparison.CurrentCultureIgnoreCase)
                                   select e.Attribute(r + "id").Value
                    ).LastOrDefault();

                if (evenFooterRef != null)
                {
                    var even   = footers.Even.Xml;
                    var target = PackUriHelper.ResolvePartUri
                                 (
                        this.PackagePart.Uri,
                        this.PackagePart.GetRelationship(evenFooterRef).TargetUri
                                 );

                    // Save header2
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            even
                        ).Save(tw, SaveOptions.None);
                    }
                }

                var firstFooterRef =
                    (
                        from e in _mainDoc.Descendants(w + "footerReference")
                        let type = e.Attribute(w + "type")
                                   where type != null && type.Value.Equals("first", StringComparison.CurrentCultureIgnoreCase)
                                   select e.Attribute(r + "id").Value
                    ).LastOrDefault();

                if (firstFooterRef != null)
                {
                    var first  = footers.First.Xml;
                    var target = PackUriHelper.ResolvePartUri
                                 (
                        this.PackagePart.Uri,
                        this.PackagePart.GetRelationship(firstFooterRef).TargetUri
                                 );

                    // Save header3
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_package.GetPart(target).GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        new XDocument
                        (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            first
                        ).Save(tw, SaveOptions.None);
                    }
                }

                // Save the settings document.
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_settingsPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _settings.Save(tw, SaveOptions.None);
                }

                if (_endnotesPart != null)
                {
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_endnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        _endnotes.Save(tw, SaveOptions.None);
                    }
                }

                if (_footnotesPart != null)
                {
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_footnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        _footnotes.Save(tw, SaveOptions.None);
                    }
                }

                if (_stylesPart != null)
                {
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_stylesPart.GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        _styles.Save(tw, SaveOptions.None);
                    }
                }

                if (_stylesWithEffectsPart != null)
                {
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_stylesWithEffectsPart.GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        _stylesWithEffects.Save(tw, SaveOptions.None);
                    }
                }

                if (_numberingPart != null)
                {
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_numberingPart.GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        _numbering.Save(tw, SaveOptions.None);
                    }
                }

                if (_fontTablePart != null)
                {
                    using (TextWriter tw = new StreamWriter(new PackagePartStream(_fontTablePart.GetStream(FileMode.Create, FileAccess.Write))))
                    {
                        _fontTable.Save(tw, SaveOptions.None);
                    }
                }
            }

            // Close the document so that it can be saved.
            _package.Flush();
            _package.Close();

            #region Save this document back to a file or stream, that was specified by the user at save time.
            if (_filename != null)
            {
                using (FileStream fs = new FileStream(_filename, FileMode.Create))
                {
                    if (_memoryStream.CanSeek)
                    {
                        // Write to the beginning of the stream
                        _memoryStream.Position = 0;
                        HelperFunctions.CopyStream(_memoryStream, fs);
                    }
                    else
                    {
                        fs.Write(_memoryStream.ToArray(), 0, (int)_memoryStream.Length);
                    }
                }
            }
            else if (_stream.CanSeek) //Check if stream can be seeked to support System.Web.HttpResponseStream.
            {
                // Set the length of this stream to 0
                _stream.SetLength(0);

                // Write to the beginning of the stream
                _stream.Position = 0;

                _memoryStream.WriteTo(_stream);
                _memoryStream.Flush();
            }
            #endregion
        }
예제 #3
0
        /// <summary>
        /// Save this document back to the location it was loaded from.
        /// </summary>
        /// <example>
        /// <code>
        /// // Load a document.
        /// using (var document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // Add an Image from a file.
        ///     document.AddImage(@"C:\Example\Image.jpg");
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        /// <seealso cref="DocX.Load(System.IO.Stream)"/>
        /// <seealso cref="DocX.Load(string)"/>
        /// <!--
        /// Bug found and fixed by krugs525 on August 12 2009.
        /// Use TFS compare to see exact code change.
        /// -->
        public override void Save(string password = "")
        {
            ValidatePasswordProtection(password);

            if (this.IsPackageClosed(_package))
            {
                // When package is closed (already saved), reload the package and restart Save();
                var initialDoc = !string.IsNullOrEmpty(_filename) ? DocX.Load(_filename) : DocX.Load(_stream);
                initialDoc.Save();
                return;
            }

            // Save the main document
            using (TextWriter tw = new StreamWriter(new PackagePartStream(this.PackagePart.GetStream(FileMode.Create, FileAccess.Write))))
            {
                _mainDoc.Save(tw, SaveOptions.None);
            }

            if ((_settings == null))
            {
                using (TextReader textReader = new StreamReader(_settingsPart.GetStream()))
                {
                    _settings = XDocument.Load(textReader);
                }
            }

            // Save the header/footer content.
            this.SaveHeadersFooters();

            // Save the settings document.
            using (TextWriter tw = new StreamWriter(new PackagePartStream(_settingsPart.GetStream(FileMode.Create, FileAccess.Write))))
            {
                _settings.Save(tw, SaveOptions.None);
            }

            if (_endnotesPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_endnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _endnotes.Save(tw, SaveOptions.None);
                }
            }

            if (_footnotesPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_footnotesPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _footnotes.Save(tw, SaveOptions.None);
                }
            }

            if (_stylesPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_stylesPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _styles.Save(tw, SaveOptions.None);
                }
            }

            if (_stylesWithEffectsPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_stylesWithEffectsPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _stylesWithEffects.Save(tw, SaveOptions.None);
                }
            }

            if (_numberingPart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_numberingPart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _numbering.Save(tw, SaveOptions.None);
                }
            }

            if (_fontTablePart != null)
            {
                using (TextWriter tw = new StreamWriter(new PackagePartStream(_fontTablePart.GetStream(FileMode.Create, FileAccess.Write))))
                {
                    _fontTable.Save(tw, SaveOptions.None);
                }
            }

            // Close the document so that it can be saved in .NETStandard.
            _package.Close();

            #region Save this document back to a file or stream, that was specified by the user at save time.
            if (_filename != null)
            {
                var saveFileName = _filename.EndsWith(".docx") || _filename.EndsWith(".doc") ? _filename : _filename + ".docx";
                using (FileStream fs = new FileStream(saveFileName, FileMode.Create))
                {
                    if (_memoryStream.CanSeek)
                    {
                        // Write to the beginning of the stream
                        _memoryStream.Position = 0;
                        HelperFunctions.CopyStream(_memoryStream, fs);
                    }
                    else
                    {
                        fs.Write(_memoryStream.ToArray(), 0, ( int )_memoryStream.Length);
                    }
                }
            }
            else if (_stream.CanSeek) //Check if stream can be seeked to support System.Web.HttpResponseStream.
            {
                // Set the length of this stream to 0
                _stream.SetLength(0);

                // Write to the beginning of the stream
                _stream.Position = 0;

                _memoryStream.WriteTo(_stream);
                _memoryStream.Flush();
            }
            #endregion
        }