Exemplo n.º 1
0
        private void OpenFooter(OXmlOpenFooterElement element)
        {
            CreateSectionProperties();
            //if (element.Header)
            //{
            //HeaderPart headerPart = _mainPart.AddNewPart<HeaderPart>();
            //OpenXmlCompositeElement header = new Header();
            //headerPart.Header = (Header)header;
            //string headerPartId = _mainPart.GetIdOfPart(headerPart);
            //_sectionProperties.AppendChild(new HeaderReference { Id = headerPartId, Type = element.HeaderType });
            //}
            //else
            //{
            FooterPart footerPart          = _mainPart.AddNewPart <FooterPart>();
            OpenXmlCompositeElement footer = new Footer();

            footerPart.Footer = (Footer)footer;
            string footerPartId = _mainPart.GetIdOfPart(footerPart);

            _sectionProperties.AppendChild(new FooterReference {
                Id = footerPartId, Type = element.FooterType
            });
            //}
            AddHeaderFooterNamespaceDeclaration((OpenXmlPartRootElement)footer);

            SetHeaderFooterProperties(element.FooterType);

            _element = footer;
            //_headerFooter = true;
            _currentElement = OXmlDocElementType.Footer;
        }
        private BookmarkEnd FindBookmarkEndInFooter(FooterPart footer, string idBkm)
        {
            var bkmEnd = footer.RootElement.Descendants <BookmarkEnd>()
                         .FirstOrDefault(b => string.Equals(b.Id, idBkm, StringComparison.OrdinalIgnoreCase));

            return(bkmEnd);
        }
Exemplo n.º 3
0
        private void ApplyFooter(WordprocessingDocument doc, string input)
        {
            if (!string.IsNullOrWhiteSpace(input))
            {
                MainDocumentPart mainDocPart = doc.MainDocumentPart;
                FooterPart       footerPart  = mainDocPart.AddNewPart <FooterPart>("r98");

                Footer    footer    = new Footer();
                Paragraph paragraph = new Paragraph()
                {
                };
                Run run = new Run();
                run.Append(ConvertHtmlToOpenXml(input));
                paragraph.Append(run);
                footer.Append(paragraph);
                footerPart.Footer = footer;

                SectionProperties sectionProperties = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault();
                if (sectionProperties == null)
                {
                    sectionProperties = new SectionProperties()
                    {
                    };
                    mainDocPart.Document.Body.Append(sectionProperties);
                }

                FooterReference footerReference = new FooterReference()
                {
                    Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = "r98"
                };
                sectionProperties.InsertAt(footerReference, 0);
            }
        }
Exemplo n.º 4
0
        public static ImagePart AddImagePart(this FooterPart footerPart, Stream stream)
        {
            var imagePart = footerPart.AddImagePart(ImagePartType.Jpeg);

            imagePart.FeedData(stream);
            return(imagePart);
        }
        private BookmarkStart FindBookmarkStartInFooter(FooterPart footer, string name)
        {
            var bkmStart = footer.RootElement.Descendants <BookmarkStart>()
                           .FirstOrDefault(b => string.Equals(b.Name.ToString(), name, StringComparison.OrdinalIgnoreCase));

            return(bkmStart);
        }
Exemplo n.º 6
0
        //gavdcodeend 11

        //gavdcodebegin 12
        public static void WordOpenXmlCreateFooter()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                MainDocumentPart docMainPart = myWordDoc.MainDocumentPart;

                docMainPart.DeleteParts(docMainPart.FooterParts);
                FooterPart defaultFooterPart = docMainPart.AddNewPart <FooterPart>();

                GenerateFooterPartContent(defaultFooterPart);

                string defaultFooterPartId = docMainPart.GetIdOfPart(defaultFooterPart);

                IEnumerable <SectionProperties> allSections =
                    docMainPart.Document.Body.Elements <SectionProperties>();

                foreach (var oneSection in allSections)
                {
                    oneSection.RemoveAllChildren <FooterReference>();
                    oneSection.RemoveAllChildren <TitlePage>();

                    oneSection.PrependChild <FooterReference>(new FooterReference()
                    {
                        Id = defaultFooterPartId, Type = HeaderFooterValues.Default
                    });
                    oneSection.PrependChild <TitlePage>(new TitlePage());
                }
                docMainPart.Document.Save();
            }
        }
Exemplo n.º 7
0
        internal Footer(FooterPart part, DocX document, HeaderFooterValues type)
        {
            footer     = part.Footer;
            footerPart = part;

            this.document = document;
            this.type     = type;
        }
Exemplo n.º 8
0
        public static void CreateDoc(string fileName, CommitteeVM data, byte part = 1)
        {
            // Create a Wordprocessing document.
            using (WordprocessingDocument myDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            {
                // Add a new main document part.
                MainDocumentPart mainPart = myDoc.AddMainDocumentPart();

                HeaderPart headerPart = mainPart.AddNewPart <HeaderPart>();
                FooterPart footerPart = mainPart.AddNewPart <FooterPart>();


                //Create DOM tree for simple document.
                mainPart.Document = new Document();
                Body body = new Body();
                mainPart.Document.Append(body);

                SectionProperties sectionProps = new SectionProperties();
                PageMargin        pageMargin   = new PageMargin()
                {
                    Top = 1008, Right = (UInt32Value)1008U, Bottom = 1008, Left = (UInt32Value)1008U, Header = (UInt32Value)720U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U
                };
                sectionProps.Append(pageMargin);
                mainPart.Document.Body.Append(sectionProps);


                switch (part)
                {
                case 1:
                    //Add master Table
                    AddMasterTable(data, mainPart);
                    ApplyHeader(myDoc, data);
                    break;

                case 2:
                    //Add third table
                    AddThirdTable(data, mainPart);
                    ApplyHeader2(myDoc, data);
                    break;

                case 3:
                    //Add second table
                    AddSecondTable(data, mainPart);
                    ApplyHeader2(myDoc, data);
                    break;
                }

                ApplyFooter(myDoc);



                // Save changes to the main document part.
                mainPart.Document.Save();
            }
        }
Exemplo n.º 9
0
        internal static void GenerateFooterPartContent(FooterPart part)
        {
            var footer = new DocumentFormat.OpenXml.Wordprocessing.Footer()
            {
                MCAttributes = MarkupCompatibilityAttributes
            };

            Schemas.AddNamespaceDeclarations(footer);

            part.Footer = footer;
        }
Exemplo n.º 10
0
        public void Print(string name, IEnumerable <string> data, string testDate, string qsId)
        {
            WordprocessingDocument doc = null;

            try
            {
                doc = WordprocessingDocument.Create(name, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
            }
            catch (OpenXmlPackageException)
            {
                return;
            }
            catch (System.IO.IOException)
            {
                return;
            }
            this.testDate = testDate;
            questSheetId  = qsId;
            MainDocumentPart mainPart = doc.AddMainDocumentPart();

            NumberingDefinitionsPart numberingDefinitionsPart = mainPart.AddNewPart <NumberingDefinitionsPart>("rId1");

            CreateNumberingDefinitionsPartContent(numberingDefinitionsPart);

            FooterPart footerPart1 = mainPart.AddNewPart <FooterPart>("rId7");

            GenerateFooterPartContent(footerPart1);

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

            body.Append(Create1stSection());
            body.Append(Create2ndSection());
            int i = 3;

            foreach (string s in data)
            {
                ++i;
                if (i < 4)
                {
                    body.AppendChild(CreateParagraph(s, 1));
                }
                else
                {
                    body.AppendChild(CreateParagraph(s, 0));
                    i = -1;
                }
            }
            body.Append(new Paragraph());
            body.Append(CreateLastSection());
            body.Append(CreateSectionProperties());
            doc.Close();
        }
Exemplo n.º 11
0
        public static void GenerateFooterPartContent(FooterPart part)
        {
            Footer footer1 = new Footer()
            {
                MCAttributes = new MarkupCompatibilityAttributes()
                {
                    Ignorable = "w14 wp14"
                }
            };

            footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            Paragraph paragraph1 = new Paragraph()
            {
                RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17"
            };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId    paragraphStyleId1    = new ParagraphStyleId()
            {
                Val = "Footer"
            };

            paragraphProperties1.Append(paragraphStyleId1);

            Run  run1  = new Run();
            Text text1 = new Text();

            text1.Text = "Footer";

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            footer1.Append(paragraph1);

            part.Footer = footer1;
        }
Exemplo n.º 12
0
        public static string CreateFooter(MainDocumentPart mainPart, OpenXmlCompositeElement element)
        {
            FooterPart footerPart = mainPart.AddNewPart <FooterPart>();
            Footer     footer     = new Footer();

            AddHeaderFooterNamespaceDeclaration(footer);
            if (element != null)
            {
                footer.AppendChild(element);
            }
            footerPart.Footer = footer;
            return(mainPart.GetIdOfPart(footerPart));
        }
Exemplo n.º 13
0
        public byte[] GetDocument()
        {
            FooterPart footerPart   = this._document.MainDocumentPart.GetPartsOfType <FooterPart>().First();
            string     footerPartId = this._document.MainDocumentPart.GetIdOfPart(footerPart);

            var sectionProperties = new SectionProperties(      // 1440 = 1 inch, 1728 = 1.2 inch
                new FooterReference()
            {
                Type = HeaderFooterValues.Default, Id = footerPartId
            },
                new FooterReference()
            {
                Type = HeaderFooterValues.Even, Id = footerPartId
            },
                new FooterReference()
            {
                Type = HeaderFooterValues.First, Id = footerPartId
            },
                new PageSize()
            {
                Width = 12240, Height = 15840
            },
                new PageMargin()
            {
                Left = 1080, Right = 1080, Top = 1440, Bottom = 1728, Gutter = 0, Header = 720, Footer = 720
            },
                new Columns()
            {
                Space = "720"
            },
                new DocGrid()
            {
                LinePitch = 360
            });

            this._document.MainDocumentPart.Document.Body.Append(sectionProperties);

            //OpenXmlValidator validator = new OpenXmlValidator(FileFormatVersions.Office2010);
            //List<ValidationErrorInfo> errors = validator.Validate(this._document).ToList();

            this._document.Close();

            // Get the data back from the reader now that the doc is saved/closed
            this._docStream.Position = 0;
            byte[] buffer = new byte[this._docStream.Length];
            this._docStream.Read(buffer, 0, (int)this._docStream.Length);

            return(buffer);
        }
Exemplo n.º 14
0
        /*
         * function:the first page and the second should have no header
         * params: list:the list of sectPrs
         * intlist:the location of sectPrs in body
         */
        protected void detectFirstSection(WordprocessingDocument docx)
        {
            Body body = docx.MainDocumentPart.Document.Body;
            IEnumerable <Paragraph>  paras = body.Elements <Paragraph>();
            MainDocumentPart         Mpart = docx.MainDocumentPart;
            List <SectionProperties> list  = secPrList(body);
            SectionProperties        s     = null;

            if (list.Count == 0)
            {
                return;
            }
            s = list[0];


            IEnumerable <HeaderReference> headrs = s.Elements <HeaderReference>();
            IEnumerable <FooterReference> footrs = s.Elements <FooterReference>();

            foreach (HeaderReference headr in headrs)
            {
                string     ID     = headr.Id.ToString();
                HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                Header     header = hp.Header;
                if (header != null && header.InnerText != null)
                {
                    if (header.InnerText.Trim().Length > 0)
                    {
                        PaperFormatDetection.Tools.Util.printError("论文封面和独创性声明应无页眉");
                        break;
                    }
                }
            }
            foreach (FooterReference footr in footrs)
            {
                string     ID     = footr.Id.ToString();
                FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                Footer     footer = fp.Footer;
                if (footer != null && footer.InnerText != null)
                {
                    if (footer.InnerText.Trim().Length > 0)
                    {
                        PaperFormatDetection.Tools.Util.printError("论文封面和独创性声明应无页脚");
                        break;
                    }
                }
            }
        }
Exemplo n.º 15
0
        public static void ChangeHeader(String documentPath)
        {
            // Replace header in target document with header of source document.
            using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true))
            {
                // Get the main document part
                MainDocumentPart mainDocumentPart = document.MainDocumentPart;

                // Delete the existing header and footer parts
                mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts);
                mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);

                // Create a new header and footer part
                HeaderPart headerPart = mainDocumentPart.AddNewPart <HeaderPart>();
                FooterPart footerPart = mainDocumentPart.AddNewPart <FooterPart>();

                // Get Id of the headerPart and footer parts
                string headerPartId = mainDocumentPart.GetIdOfPart(headerPart);
                string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);

                GenerateHeaderPartContent(headerPart);

                GenerateFooterPartContent(footerPart);

                // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id
                IEnumerable <SectionProperties> sections = mainDocumentPart.Document.Body.Elements <SectionProperties>();

                foreach (var section in sections)
                {
                    // Delete existing references to headers and footers
                    section.RemoveAllChildren <HeaderReference>();
                    section.RemoveAllChildren <FooterReference>();

                    // Create the new header and footer reference node
                    section.PrependChild <HeaderReference>(new HeaderReference()
                    {
                        Id = headerPartId
                    });
                    section.PrependChild <FooterReference>(new FooterReference()
                    {
                        Id = footerPartId
                    });
                }
            }
        }
        //.....................................................................
        /// <summary>
        ///
        /// </summary>
        /// <param name="doc"></param>
        private static void AddFooter(WordprocessingDocument doc)
        {
            // Declare a string for the header text.
            string newFooterText =
                "New footer via Open XML Format SDK 2.0 classes";

            // Get the main document part.
            MainDocumentPart mainDocPart = doc.MainDocumentPart;

            // Delete the existing footer parts.
            mainDocPart.DeleteParts(mainDocPart.FooterParts);

            // Create a new footer part and get its relationship id.
            FooterPart newFooterPart = mainDocPart.AddNewPart <FooterPart>( );
            string     rId           = mainDocPart.GetIdOfPart(newFooterPart);

            // Call the GeneratePageFooterPart helper method, passing in
            // the footer text, to create the footer markup and then save
            // that markup to the footer part.
            GeneratePageFooterPart(newFooterText).Save(newFooterPart);

            // Loop through all section properties in the document
            // which is where footer references are defined.
            foreach (SectionProperties sectProperties in mainDocPart.Document.Descendants <SectionProperties>( ))
            {
                //  Delete any existing references to footers.
                foreach (FooterReference footerReference in
                         sectProperties.Descendants <FooterReference>( ))
                {
                    sectProperties.RemoveChild(footerReference);
                }

                //  Create a new footer reference that points to the new
                // footer part and add it to the section properties.
                FooterReference newFooterReference = new FooterReference( )
                {
                    Id = rId, Type = HeaderFooterValues.Default
                };

                sectProperties.Append(newFooterReference);
            }

            //  Save the changes to the main document part.
            mainDocPart.Document.Save( );
        }
Exemplo n.º 17
0
        protected void detectLastSection(WordprocessingDocument docx)
        {
            Body             body  = docx.MainDocumentPart.Document.Body;
            MainDocumentPart Mpart = docx.MainDocumentPart;
            int l = body.ChildElements.Count;

            if (body.ChildElements.GetItem(l - 1).GetType().ToString() == "DocumentFormat.OpenXml.Wordprocessing.SectionProperties")
            {
                SectionProperties             s      = body.GetFirstChild <SectionProperties>();
                IEnumerable <FooterReference> footrs = s.Elements <FooterReference>();
                foreach (FooterReference footr in footrs)
                {
                    string     ID     = footr.Id.ToString();
                    FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                    Footer     footer = fp.Footer;
                    if (footer != null && footer.InnerText != null)
                    {
                        if (footer.InnerText.Trim().Length > 0)
                        {
                            Util.printError("论文版权使用授权书应无页脚");
                            break;
                        }
                    }
                }
                IEnumerable <HeaderReference> headrs = s.Elements <HeaderReference>();
                foreach (HeaderReference headr in headrs)
                {
                    string     ID     = headr.Id.ToString();
                    HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                    Header     header = hp.Header;
                    if (header != null && header.InnerText != null)
                    {
                        if (header.InnerText.Trim().Length > 0)
                        {
                            if (header.InnerText.Trim() != oddHeaderText)
                            {
                                Util.printError("论文版权使用授权书内容错误,应为:" + oddHeaderText);
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 18
0
        //static void Main(string[] args)
        //{
        //    //CreateWordDoc("C:/Users/Trevor/Documents/test.docx", "This is Text, ya ya ya.");
        //    // AddSignatureFooter("C:/Users/Trevor/Documents/test.docx", "-by Nelson Mandela");

        //    //Test statistics
        //    Console.Write(BasicStats("C:/Users/Trevor/Documents/testGAO.docx"));
        //    Console.ReadLine();
        //}

        //Add footer with string signature to existing document
        public static void AddSignatureFooter(string filepath, string signature)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(filepath, true))
            {
                MainDocumentPart mainDocPart = doc.MainDocumentPart;

                if (mainDocPart.Document == null)
                {
                    mainDocPart.Document = new Document();
                }

                mainDocPart.DeleteParts(mainDocPart.FooterParts);
                FooterPart footerPart1 = mainDocPart.AddNewPart <FooterPart>("r98");

                Footer footer1 = new Footer();

                Paragraph paragraph1 = new Paragraph();

                Run  run1  = new Run();
                Text text1 = new Text {
                    Text = signature
                };

                run1.Append(text1);
                paragraph1.Append(run1);

                footer1.Append(paragraph1);
                footerPart1.Footer = footer1;

                SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault();
                if (sectionProperties1 == null)
                {
                    sectionProperties1 = new SectionProperties();
                    mainDocPart.Document.Body.Append(sectionProperties1);
                }
                FooterReference footerReference1 = new FooterReference {
                    Type = HeaderFooterValues.Default, Id = "r98"
                };

                sectionProperties1.InsertAt(footerReference1, 0);
            }
        }
Exemplo n.º 19
0
        private void ApplyFooter(FooterPart footerPart)
        {
            var footer1 = new Footer();

            footer1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            footer1.AddNamespaceDeclaration("wp",
                                            "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");

            var paragraph1 = new Paragraph {
                RsidParagraphAddition = "005641D2", RsidRunAdditionDefault = "005641D2"
            };

            var paragraphProperties1 = new ParagraphProperties();
            var paragraphStyleId1    = new ParagraphStyleId {
                Val = "Footer"
            };

            paragraphProperties1.Append(paragraphStyleId1);

            var run1  = new Run();
            var text1 = new Text();

            text1.Text = "Generated with Pickles " + Assembly.GetExecutingAssembly().GetName().Version;

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            footer1.Append(paragraph1);

            footerPart.Footer = footer1;
        }
Exemplo n.º 20
0
        public void ChangeOrReplaceHeaderAndFooterFeature()
        {
            // Replace a header in the target document with a header from the source document.
            using (WordprocessingDocument document = WordprocessingDocument.Create(
                       ArtifactsDir + "Change or replace header and footer - OpenXML.docx",
                       WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainDocumentPart = document.MainDocumentPart;

                mainDocumentPart.DeleteParts(mainDocumentPart.HeaderParts);
                mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);

                HeaderPart headerPart = mainDocumentPart.AddNewPart <HeaderPart>();
                FooterPart footerPart = mainDocumentPart.AddNewPart <FooterPart>();

                string headerPartId = mainDocumentPart.GetIdOfPart(headerPart);
                string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);

                GenerateHeaderPartContent(headerPart);

                GenerateFooterPartContent(footerPart);

                // Give the HeaderReference and FooterReference of each section property the new Id.
                IEnumerable <SectionProperties> sections = mainDocumentPart.Document.Body.Elements <SectionProperties>();

                foreach (var section in sections)
                {
                    section.RemoveAllChildren <HeaderReference>();
                    section.RemoveAllChildren <FooterReference>();

                    section.PrependChild(new HeaderReference {
                        Id = headerPartId
                    });
                    section.PrependChild(new FooterReference {
                        Id = footerPartId
                    });
                }
            }
        }
Exemplo n.º 21
0
        public byte[] GetDocument()
        {
            FooterPart footerPart   = this.document.MainDocumentPart.GetPartsOfType <FooterPart>().First();
            string     footerPartId = this.document.MainDocumentPart.GetIdOfPart(footerPart);

            var sectionProperties = new SectionProperties(      // 1440 = 1 inch, 1728 = 1.2 inch
                new FooterReference()
            {
                Type = HeaderFooterValues.Default, Id = footerPartId
            },
                new FooterReference()
            {
                Type = HeaderFooterValues.Even, Id = footerPartId
            },
                new FooterReference()
            {
                Type = HeaderFooterValues.First, Id = footerPartId
            },
                new PageSize()
            {
                Width = 12240, Height = 15840
            },
                new PageMargin()
            {
                Left = 1080, Right = 1080, Top = 1440, Bottom = 1728, Gutter = 0, Header = 720, Footer = 720
            },
                new Columns()
            {
                Space = "720"
            },
                new DocGrid()
            {
                LinePitch = 360
            });

            this.document.MainDocumentPart.Document.Body.Append(sectionProperties);

            // Bug in DocumentFormat.OpenXml adding <numberingIdMacAtClean> at an incorrect location in the document
            var numberingPart           = this.document.MainDocumentPart.NumberingDefinitionsPart;
            var numberingIdMacAtCleanup = numberingPart.Numbering.OfType <NumberingIdMacAtCleanup>().FirstOrDefault();

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

            DocumentFormat.OpenXml.Validation.OpenXmlValidator           validator = new DocumentFormat.OpenXml.Validation.OpenXmlValidator(FileFormatVersions.Office2010);
            List <DocumentFormat.OpenXml.Validation.ValidationErrorInfo> errors    = validator.Validate(this.document).ToList();

            if (errors.Count > 0)
            {
                Log.For(this).Error("Exporting IG with id " + this.implementationGuide.Id + " produced the following OpenXml validation errors: ");

                foreach (var error in errors)
                {
                    Log.For(this).Error("Description: " + error.Description + "\r\nPath: " + error.Path + "\r\n");
                }
            }

            this.document.Close();

            // Get the data back from the reader now that the doc is saved/closed
            this.docStream.Position = 0;
            byte[] buffer = new byte[this.docStream.Length];
            this.docStream.Read(buffer, 0, (int)this.docStream.Length);

            return(buffer);
        }
        public static void GenerateFooterPart1Content(FooterPart footerPart1)
        {
            var footer1 = new Footer {
                MCAttributes = new MarkupCompatibilityAttributes {
                    Ignorable = "w14 w15 w16se w16cid wp14"
                }
            };

            footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            footer1.AddNamespaceDeclaration("cx", "http://schemas.microsoft.com/office/drawing/2014/chartex");
            footer1.AddNamespaceDeclaration("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex");
            footer1.AddNamespaceDeclaration("cx2", "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex");
            footer1.AddNamespaceDeclaration("cx3", "http://schemas.microsoft.com/office/drawing/2016/5/9/chartex");
            footer1.AddNamespaceDeclaration("cx4", "http://schemas.microsoft.com/office/drawing/2016/5/10/chartex");
            footer1.AddNamespaceDeclaration("cx5", "http://schemas.microsoft.com/office/drawing/2016/5/11/chartex");
            footer1.AddNamespaceDeclaration("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex");
            footer1.AddNamespaceDeclaration("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex");
            footer1.AddNamespaceDeclaration("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex");
            footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            footer1.AddNamespaceDeclaration("aink", "http://schemas.microsoft.com/office/drawing/2016/ink");
            footer1.AddNamespaceDeclaration("am3d", "http://schemas.microsoft.com/office/drawing/2017/model3d");
            footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            footer1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
            footer1.AddNamespaceDeclaration("w16cid", "http://schemas.microsoft.com/office/word/2016/wordml/cid");
            footer1.AddNamespaceDeclaration("w16se", "http://schemas.microsoft.com/office/word/2015/wordml/symex");
            footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            var paragraph273 = new Paragraph {
                RsidParagraphAddition = "009B2C1D", RsidRunAdditionDefault = "009E39C2", ParagraphId = "71F3416E", TextId = "77777777"
            };

            var paragraphProperties176 = new ParagraphProperties();
            var paragraphStyleId1      = new ParagraphStyleId {
                Val = "leftRight"
            };

            paragraphProperties176.Append(paragraphStyleId1);

            var run396  = new Run();
            var text366 = new Text {
                Text = "Confidential Candidate CV"
            };

            run396.Append(text366);

            var run397   = new Run();
            var tabChar1 = new TabChar();

            run397.Append(tabChar1);

            var run398     = new Run();
            var fieldChar1 = new FieldChar {
                FieldCharType = FieldCharValues.Begin
            };

            run398.Append(fieldChar1);

            var run399     = new Run();
            var fieldCode1 = new FieldCode {
                Text = "PAGE"
            };

            run399.Append(fieldCode1);

            var run400     = new Run();
            var fieldChar2 = new FieldChar {
                FieldCharType = FieldCharValues.Separate
            };

            run400.Append(fieldChar2);

            var run401 = new Run();

            var runProperties394 = new RunProperties();
            var noProof30        = new NoProof();

            runProperties394.Append(noProof30);
            var text367 = new Text {
                Text = "2"
            };

            run401.Append(runProperties394);
            run401.Append(text367);

            var run402     = new Run();
            var fieldChar3 = new FieldChar {
                FieldCharType = FieldCharValues.End
            };

            run402.Append(fieldChar3);

            paragraph273.Append(paragraphProperties176);
            paragraph273.Append(run396);
            paragraph273.Append(run397);
            paragraph273.Append(run398);
            paragraph273.Append(run399);
            paragraph273.Append(run400);
            paragraph273.Append(run401);
            paragraph273.Append(run402);

            footer1.Append(paragraph273);

            footerPart1.Footer = footer1;
        }
Exemplo n.º 23
0
        /// <summary>
        /// Set a new footer in a document
        /// </summary>
        /// <param name="footer">XDocument containing the footer to add in the document</param>
        /// <param name="type">The footer part type</param>
        public static OpenXmlPowerToolsDocument SetFooter(WmlDocument doc, XDocument footer, FooterType type, int sectionIndex)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    //  Removes the reference in the document.xml and the footer part if those already
                    //  exist
                    XElement footerReferenceElement = GetFooterReference(document, type, sectionIndex);
                    if (footerReferenceElement != null)
                    {
                        GetFooterPart(document, type, sectionIndex).RemovePart();
                        footerReferenceElement.Remove();
                    }

                    //  Add the new footer
                    FooterPart footerPart = document.MainDocumentPart.AddNewPart <FooterPart>();
                    footerPart.PutXDocument(footer);

                    //  If the document does not have a property section a new one must be created
                    if (SectionPropertiesElements(document).Count() == 0)
                    {
                        AddDefaultSectionProperties(document);
                    }

                    //  Creates the relationship of the footer inside the section properties in the document
                    string relID    = document.MainDocumentPart.GetIdOfPart(footerPart);
                    string kindName = "";
                    switch ((FooterType)type)
                    {
                    case FooterType.First:
                        kindName = "first";
                        break;

                    case FooterType.Even:
                        kindName = "even";
                        break;

                    case FooterType.Default:
                        kindName = "default";
                        break;
                    }

                    XElement sectionPropertyElement = SectionPropertiesElements(document).Skip(sectionIndex).FirstOrDefault();
                    if (sectionPropertyElement != null)
                    {
                        sectionPropertyElement.Add(
                            new XElement(ns + "footerReference",
                                         new XAttribute(ns + "type", kindName),
                                         new XAttribute(relationshipns + "id", relID)));

                        if (sectionPropertyElement.Element(ns + "titlePg") == null)
                        {
                            sectionPropertyElement.Add(
                                new XElement(ns + "titlePg")
                                );
                        }
                    }
                    document.MainDocumentPart.PutXDocument();

                    // add in the settings part the EvendAndOddHeaders. this element
                    // allow to see the odd and even footers and headers in the document.
                    SettingAccessor.AddEvenAndOddHeadersElement(document);
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
Exemplo n.º 24
0
        private void SetupStyles()
        {
            WordprocessingCommentsPart commentsPart        = AddTemplatePart <WordprocessingCommentsPart>(this.document, CommentsStyleResource);
            EndnotesPart             endNotesPart          = AddTemplatePart <EndnotesPart>(this.document, EndNotesStyleResource);
            FontTablePart            fontTablePart         = AddTemplatePart <FontTablePart>(this.document, FontsTableStyleResource);
            FootnotesPart            footnotesPart         = AddTemplatePart <FootnotesPart>(this.document, FootNotesStyleResource);
            HeaderPart               headerPart            = AddTemplatePart <HeaderPart>(this.document, HeaderStyleResource);
            DocumentSettingsPart     settingsPart          = AddTemplatePart <DocumentSettingsPart>(this.document, SettingsStyleResource);
            StyleDefinitionsPart     styles                = AddTemplatePart <StyleDefinitionsPart>(this.document, StylesStyleResource);
            StylesWithEffectsPart    stylesWithEffectsPart = AddTemplatePart <StylesWithEffectsPart>(this.document, StylesWithEffectsStyleResource);
            WebSettingsPart          webSettingsPart       = AddTemplatePart <WebSettingsPart>(this.document, WebSettingsStyleResource);
            ThemePart                themePart             = AddTemplatePart <ThemePart>(this.document, ThemeStyleResource);
            NumberingDefinitionsPart numberingPart         = AddTemplatePart <NumberingDefinitionsPart>(this.document, NumberingStyleResource);

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

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

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

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

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

                numberingPart.Numbering.Append(ni);
            }
        }
Exemplo n.º 25
0
        private void CreateParts(WordprocessingDocument document)
        {
            DocxBase.CurrentTitle = DocxServiceProvinceRes.Title;

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

            DocxBase.GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

            MainDocumentPart mainDocumentPart1 = document.AddMainDocumentPart();

            GenerateMainDocumentPart1Content(mainDocumentPart1);

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

            DocxBase.GenerateFontTablePart1Content(fontTablePart1);

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

            DocxBase.GenerateStyleDefinitionsPart1Content(styleDefinitionsPart1);

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

            DocxBase.GenerateEndnotesPart1Content(endnotesPart1);

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

            DocxBase.GenerateFooterPart1Content(footerPart1);

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

            DocxBase.GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);

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

            DocxBase.GenerateCustomXmlPart1Content(customXmlPart1);

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

            DocxBase.GenerateCustomXmlPropertiesPart1Content(customXmlPropertiesPart1);

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

            DocxBase.GenerateFootnotesPart1Content(footnotesPart1);

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

            DocxBase.GenerateHeaderPart1Content(headerPart1);

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

            DocxBase.GenerateWebSettingsPart1Content(webSettingsPart1);

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

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

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

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

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

            DocxBase.GenerateDocumentSettingsPart1Content(documentSettingsPart1);

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

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

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

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

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

            DocxBase.GenerateThemePart1Content(themePart1);

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

            DocxBase.SetPackageProperties(document);
        }
Exemplo n.º 26
0
        protected void detectHeaderFooter(WordprocessingDocument docx)
        {
            Body body = docx.MainDocumentPart.Document.Body;
            IEnumerable <Paragraph>  paras = body.Elements <Paragraph>();
            MainDocumentPart         Mpart = docx.MainDocumentPart;
            List <SectionProperties> list  = secPrList(body);
            List <int>        intlist      = secPrListInt(body);
            SectionProperties scetpr       = body.GetFirstChild <SectionProperties>();
            //list.Add(scetpr);
            //intlist.Add(body.ChildElements.Count() - 1);
            SectionProperties s = null;

            for (int i = 2; i <= list.Count <SectionProperties>(); i++)
            {
                s = list[i - 1];
                string chapter = null;
                if (intlist[i - 1] < body.ChildElements.Count)
                {
                    chapter = getPicMassage(intlist[i - 1], body) + "---所在章的";
                }

                //页眉
                IEnumerable <HeaderReference> headrs = s.Elements <HeaderReference>();

                foreach (HeaderReference headr in headrs)
                {
                    string headertype = null;
                    if (headr.Type == HeaderFooterValues.Default)
                    {
                        headertype = "奇数页";
                    }
                    if (headr.Type == HeaderFooterValues.Even)
                    {
                        headertype = "偶数页";
                    }
                    string     ID     = headr.Id.ToString();
                    HeaderPart hp     = (HeaderPart)Mpart.GetPartById(ID);
                    Header     header = hp.Header;
                    Paragraph  p      = header.GetFirstChild <Paragraph>();
                    if (header.InnerText != null)
                    {
                        if (Util.correctfonts(p, docx, CNheaderFonts, ENHeaderFonts) == false)
                        {
                            PaperFormatDetection.Tools.Util.printError("页眉字体错误,应为:" + CNheaderFonts + "----" + chapter + headertype);
                        }
                        if (Util.correctsize(p, docx, headerFontsize) == false)
                        {
                            PaperFormatDetection.Tools.Util.printError("页眉字号错误,应为:" + headerFontsize + "----" + headertype);
                        }
                        if (JustificationCenter(p, Mpart) == false)
                        {
                            PaperFormatDetection.Tools.Util.printError("页眉未居中" + "----" + chapter + headertype);
                        }
                    }
                }
                //页脚
                IEnumerable <FooterReference> footrs = s.Elements <FooterReference>();
                foreach (FooterReference footr in footrs)
                {
                    string type = null;
                    if (footr.Type == HeaderFooterValues.Default)
                    {
                        type = "奇数页";
                    }
                    if (footr.Type == HeaderFooterValues.Even)
                    {
                        type = "偶数页";
                    }
                    string     ID     = footr.Id.ToString();
                    FooterPart fp     = (FooterPart)Mpart.GetPartById(ID);
                    Footer     footer = fp.Footer;
                    Paragraph  p      = footer.GetFirstChild <Paragraph>();

                    if (footer.InnerText.Trim() != "")
                    {
                        if (Util.correctfonts(p, docx, CNFooterFonts, ENFooterFonts) == false)
                        {
                            Util.printError("页脚字体错误,应为:" + CNFooterFonts + "----" + chapter + type);
                        }
                        if (Util.correctsize(p, docx, footerFontsize) == false)
                        {
                            Util.printError("页脚字号错误,应为:" + footerFontsize + "----" + chapter + type);
                        }
                        if (JustificationCenter(p, Mpart) == false)
                        {
                            Util.printError("页脚未居中" + "----" + chapter + type);
                        }
                    }
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Создать ссылку на колонтитулу
        /// </summary>
        /// <param name="mainDocument">Документ</param>
        /// <returns></returns>
        public static FooterPart AddFotters(MainDocumentPart mainDocument)
        {
            FooterPart foters = mainDocument.AddNewPart <FooterPart>();

            return(foters);
        }
Exemplo n.º 28
0
        public static void ApplyFooter(WordprocessingDocument doc)
        {
            // Get the main document part.
            MainDocumentPart mainDocPart = doc.MainDocumentPart;

            FooterPart footerPart1 = mainDocPart.AddNewPart <FooterPart>("r98");



            Footer footer1 = new Footer();

            Table table = new Table();

            TableProperties props = new TableProperties(
                new TableWidth()
            {
                Width = "100%", Type = TableWidthUnitValues.Auto
            });

            props.BiDiVisual = new BiDiVisual();

            table.AppendChild <TableProperties>(props);
            var tr = new TableRow();
            //cell 1
            var tc = new TableCell();

            tc.Append(CreateParagraph("أملاه:	"));
            tc.Append(CreateParagraph("كتبه :	"));
            var tableWidth = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "50%"
            };

            tc.Append(new TableCellProperties(tableWidth));

            //cell 2
            var tc2 = new TableCell();

            tc2.Append(CreateParagraph(" راجع الأمـلاء  :  "));
            tc2.Append(CreateParagraph("راجع الكتابة   : "));
            tc2.Append(CreateParagraph("رئيس لجنة الإدارة         : "));

            var tableWidth2 = new TableCellWidth
            {
                Type  = TableWidthUnitValues.Auto,
                Width = "50%"
            };

            tc2.Append(new TableCellProperties(tableWidth2));


            tr.Append(tc);
            tr.Append(tc2);
            table.Append(tr);

            footer1.Append(table);


            footerPart1.Footer = footer1;



            SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants <SectionProperties>().FirstOrDefault();

            if (sectionProperties1 == null)
            {
                sectionProperties1 = new SectionProperties()
                {
                };
                mainDocPart.Document.Body.Append(sectionProperties1);
            }
            FooterReference footerReference1 = new FooterReference()
            {
                Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = "r98"
            };


            sectionProperties1.InsertAt(footerReference1, 0);
        }
Exemplo n.º 29
0
 public FooterMapping(ConversionContext ctx, FooterPart part, CharacterRange ftr)
     : base(ctx, part)
 {
     _ftr = ftr;
 }
        /// <summary>
        /// Converts the given SectionPropertyExceptions
        /// </summary>
        /// <param name="sepx"></param>
        public void Apply(SectionPropertyExceptions sepx)
        {
            XmlElement pgMar      = _nodeFactory.CreateElement("w", "pgMar", OpenXmlNamespaces.WordprocessingML);
            XmlElement pgSz       = _nodeFactory.CreateElement("w", "pgSz", OpenXmlNamespaces.WordprocessingML);
            XmlElement docGrid    = _nodeFactory.CreateElement("w", "docGrid", OpenXmlNamespaces.WordprocessingML);
            XmlElement cols       = _nodeFactory.CreateElement("w", "cols", OpenXmlNamespaces.WordprocessingML);
            XmlElement pgBorders  = _nodeFactory.CreateElement("w", "pgBorders", OpenXmlNamespaces.WordprocessingML);
            XmlElement paperSrc   = _nodeFactory.CreateElement("w", "paperSrc", OpenXmlNamespaces.WordprocessingML);
            XmlElement footnotePr = _nodeFactory.CreateElement("w", "footnotePr", OpenXmlNamespaces.WordprocessingML);
            XmlElement pgNumType  = _nodeFactory.CreateElement("w", "pgNumType", OpenXmlNamespaces.WordprocessingML);

            //convert headers of this section
            if (_ctx.Doc.HeaderAndFooterTable.OddHeaders.Count > 0)
            {
                CharacterRange evenHdr = _ctx.Doc.HeaderAndFooterTable.EvenHeaders[_sectNr];
                if (evenHdr != null)
                {
                    HeaderPart evenPart = _ctx.Docx.MainDocumentPart.AddHeaderPart();
                    _ctx.Doc.Convert(new HeaderMapping(_ctx, evenPart, evenHdr));
                    appendRef(_sectPr, "headerReference", "even", evenPart.RelIdToString);
                }

                CharacterRange oddHdr = _ctx.Doc.HeaderAndFooterTable.OddHeaders[_sectNr];
                if (oddHdr != null)
                {
                    HeaderPart oddPart = _ctx.Docx.MainDocumentPart.AddHeaderPart();
                    _ctx.Doc.Convert(new HeaderMapping(_ctx, oddPart, oddHdr));
                    appendRef(_sectPr, "headerReference", "default", oddPart.RelIdToString);
                }

                CharacterRange firstHdr = _ctx.Doc.HeaderAndFooterTable.FirstHeaders[_sectNr];
                if (firstHdr != null)
                {
                    HeaderPart firstPart = _ctx.Docx.MainDocumentPart.AddHeaderPart();
                    _ctx.Doc.Convert(new HeaderMapping(_ctx, firstPart, firstHdr));
                    appendRef(_sectPr, "headerReference", "first", firstPart.RelIdToString);
                }
            }

            //convert footers of this section
            if (_ctx.Doc.HeaderAndFooterTable.OddFooters.Count > 0)
            {
                CharacterRange evenFtr = _ctx.Doc.HeaderAndFooterTable.EvenFooters[_sectNr];
                if (evenFtr != null)
                {
                    FooterPart evenPart = _ctx.Docx.MainDocumentPart.AddFooterPart();
                    _ctx.Doc.Convert(new FooterMapping(_ctx, evenPart, evenFtr));
                    appendRef(_sectPr, "footerReference", "even", evenPart.RelIdToString);
                }

                CharacterRange oddFtr = _ctx.Doc.HeaderAndFooterTable.OddFooters[_sectNr];
                if (oddFtr != null)
                {
                    FooterPart oddPart = _ctx.Docx.MainDocumentPart.AddFooterPart();
                    _ctx.Doc.Convert(new FooterMapping(_ctx, oddPart, oddFtr));
                    appendRef(_sectPr, "footerReference", "default", oddPart.RelIdToString);
                }


                CharacterRange firstFtr = _ctx.Doc.HeaderAndFooterTable.FirstFooters[_sectNr];
                if (firstFtr != null)
                {
                    FooterPart firstPart = _ctx.Docx.MainDocumentPart.AddFooterPart();
                    _ctx.Doc.Convert(new FooterMapping(_ctx, firstPart, firstFtr));
                    appendRef(_sectPr, "footerReference", "first", firstPart.RelIdToString);
                }
            }

            foreach (SinglePropertyModifier sprm in sepx.grpprl)
            {
                switch (sprm.OpCode)
                {
                //page margins
                case SinglePropertyModifier.OperationCode.sprmSDxaLeft:
                    //left margin
                    _marLeft = System.BitConverter.ToInt16(sprm.Arguments, 0);
                    appendValueAttribute(pgMar, "left", _marLeft.ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDxaRight:
                    //right margin
                    _marRight = System.BitConverter.ToInt16(sprm.Arguments, 0);
                    appendValueAttribute(pgMar, "right", _marRight.ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDyaTop:
                    //top margin
                    appendValueAttribute(pgMar, "top", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDyaBottom:
                    //bottom margin
                    appendValueAttribute(pgMar, "bottom", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDzaGutter:
                    //gutter margin
                    appendValueAttribute(pgMar, "gutter", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDyaHdrTop:
                    //header margin
                    appendValueAttribute(pgMar, "header", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDyaHdrBottom:
                    //footer margin
                    appendValueAttribute(pgMar, "footer", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                //page size and orientation
                case SinglePropertyModifier.OperationCode.sprmSXaPage:
                    //width
                    _pgWidth = System.BitConverter.ToInt16(sprm.Arguments, 0);
                    appendValueAttribute(pgSz, "w", _pgWidth.ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSYaPage:
                    //height
                    appendValueAttribute(pgSz, "h", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSBOrientation:
                    //orientation
                    appendValueAttribute(pgSz, "orient", ((PageOrientation)sprm.Arguments[0]).ToString());
                    break;

                //paper source
                case SinglePropertyModifier.OperationCode.sprmSDmBinFirst:
                    appendValueAttribute(paperSrc, "first", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDmBinOther:
                    appendValueAttribute(paperSrc, "other", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                //page borders
                case SinglePropertyModifier.OperationCode.sprmSBrcTop80:
                case SinglePropertyModifier.OperationCode.sprmSBrcTop:
                    //top
                    XmlElement topBorder = _nodeFactory.CreateElement("w", "top", OpenXmlNamespaces.WordprocessingML);
                    appendBorderAttributes(new BorderCode(sprm.Arguments), topBorder);
                    addOrSetBorder(pgBorders, topBorder);
                    break;

                case SinglePropertyModifier.OperationCode.sprmSBrcLeft80:
                case SinglePropertyModifier.OperationCode.sprmSBrcLeft:
                    //left
                    XmlElement leftBorder = _nodeFactory.CreateElement("w", "left", OpenXmlNamespaces.WordprocessingML);
                    appendBorderAttributes(new BorderCode(sprm.Arguments), leftBorder);
                    addOrSetBorder(pgBorders, leftBorder);
                    break;

                case SinglePropertyModifier.OperationCode.sprmSBrcBottom80:
                case SinglePropertyModifier.OperationCode.sprmSBrcBottom:
                    //left
                    XmlElement bottomBorder = _nodeFactory.CreateElement("w", "bottom", OpenXmlNamespaces.WordprocessingML);
                    appendBorderAttributes(new BorderCode(sprm.Arguments), bottomBorder);
                    addOrSetBorder(pgBorders, bottomBorder);
                    break;

                case SinglePropertyModifier.OperationCode.sprmSBrcRight80:
                case SinglePropertyModifier.OperationCode.sprmSBrcRight:
                    //left
                    XmlElement rightBorder = _nodeFactory.CreateElement("w", "right", OpenXmlNamespaces.WordprocessingML);
                    appendBorderAttributes(new BorderCode(sprm.Arguments), rightBorder);
                    addOrSetBorder(pgBorders, rightBorder);
                    break;

                //footnote porperties
                case SinglePropertyModifier.OperationCode.sprmSRncFtn:
                    //restart code
                    FootnoteRestartCode fncFtn = FootnoteRestartCode.continuous;

                    //open office uses 1 byte values instead of 2 bytes values:
                    if (sprm.Arguments.Length == 2)
                    {
                        fncFtn = (FootnoteRestartCode)System.BitConverter.ToInt16(sprm.Arguments, 0);
                    }
                    if (sprm.Arguments.Length == 1)
                    {
                        fncFtn = (FootnoteRestartCode)sprm.Arguments[0];
                    }

                    appendValueElement(footnotePr, "numRestart", fncFtn.ToString(), true);
                    break;

                case SinglePropertyModifier.OperationCode.sprmSFpc:
                    //position code
                    Int16 fpc = 0;
                    if (sprm.Arguments.Length == 2)
                    {
                        fpc = System.BitConverter.ToInt16(sprm.Arguments, 0);
                    }
                    else
                    {
                        fpc = (Int16)sprm.Arguments[0];
                    }
                    if (fpc == 2)
                    {
                        appendValueElement(footnotePr, "pos", "beneathText", true);
                    }
                    break;

                case SinglePropertyModifier.OperationCode.sprmSNfcFtnRef:
                    //number format
                    Int16 nfc = System.BitConverter.ToInt16(sprm.Arguments, 0);
                    appendValueElement(footnotePr, "numFmt", NumberingMapping.GetNumberFormat(nfc), true);
                    break;

                case SinglePropertyModifier.OperationCode.sprmSNFtn:
                    Int16 nFtn = System.BitConverter.ToInt16(sprm.Arguments, 0);
                    appendValueElement(footnotePr, "numStart", nFtn.ToString(), true);
                    break;

                //doc grid
                case SinglePropertyModifier.OperationCode.sprmSDyaLinePitch:
                    appendValueAttribute(docGrid, "linePitch", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDxtCharSpace:
                    appendValueAttribute(docGrid, "charSpace", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSClm:
                    appendValueAttribute(docGrid, "type", ((DocGridType)System.BitConverter.ToInt16(sprm.Arguments, 0)).ToString());
                    break;

                //columns
                case SinglePropertyModifier.OperationCode.sprmSCcolumns:
                    _colNumber = (int)(System.BitConverter.ToInt16(sprm.Arguments, 0) + 1);
                    _colSpace  = new Int16[_colNumber];
                    appendValueAttribute(cols, "num", _colNumber.ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDxaColumns:
                    //evenly spaced columns
                    appendValueAttribute(cols, "space", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDxaColWidth:
                    //there is at least one width set, so create the array
                    if (_colWidth == null)
                    {
                        _colWidth = new Int16[_colNumber];
                    }

                    byte  index = sprm.Arguments[0];
                    Int16 w     = System.BitConverter.ToInt16(sprm.Arguments, 1);
                    _colWidth[index] = w;
                    break;

                case SinglePropertyModifier.OperationCode.sprmSDxaColSpacing:
                    //there is at least one space set, so create the array
                    if (_colSpace == null)
                    {
                        _colSpace = new Int16[_colNumber];
                    }

                    _colSpace[sprm.Arguments[0]] = System.BitConverter.ToInt16(sprm.Arguments, 1);
                    break;

                //bidi
                case SinglePropertyModifier.OperationCode.sprmSFBiDi:
                    appendFlagElement(_sectPr, sprm, "bidi", true);
                    break;

                //title page
                case SinglePropertyModifier.OperationCode.sprmSFTitlePage:
                    appendFlagElement(_sectPr, sprm, "titlePg", true);
                    break;

                //RTL gutter
                case SinglePropertyModifier.OperationCode.sprmSFRTLGutter:
                    appendFlagElement(_sectPr, sprm, "rtlGutter", true);
                    break;

                //type
                case SinglePropertyModifier.OperationCode.sprmSBkc:
                    _type = (SectionType)sprm.Arguments[0];
                    break;

                //align
                case SinglePropertyModifier.OperationCode.sprmSVjc:
                    appendValueElement(_sectPr, "vAlign", sprm.Arguments[0].ToString(), true);
                    break;

                //pgNumType
                case SinglePropertyModifier.OperationCode.sprmSNfcPgn:
                    PageNumberFormatCode pgnFc = (PageNumberFormatCode)sprm.Arguments[0];
                    appendValueAttribute(pgNumType, "fmt", pgnFc.ToString());
                    break;

                case SinglePropertyModifier.OperationCode.sprmSPgnStart:
                    appendValueAttribute(pgNumType, "start", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString());
                    break;
                }
            }


            //build the columns
            if (_colWidth != null)
            {
                //set to unequal width
                XmlAttribute equalWidth = _nodeFactory.CreateAttribute("w", "equalWidth", OpenXmlNamespaces.WordprocessingML);
                equalWidth.Value = "0";
                cols.Attributes.Append(equalWidth);

                //calculate the width of the last column:
                //the last column width is not written to the document because it can be calculated.
                if (_colWidth[_colWidth.Length - 1] == 0)
                {
                    Int16 lastColWidth = (Int16)(_pgWidth - _marLeft - _marRight);
                    for (int i = 0; i < _colWidth.Length - 1; i++)
                    {
                        lastColWidth -= _colSpace[i];
                        lastColWidth -= _colWidth[i];
                    }
                    _colWidth[_colWidth.Length - 1] = lastColWidth;
                }

                //append the xml elements
                for (int i = 0; i < _colWidth.Length; i++)
                {
                    XmlElement   col   = _nodeFactory.CreateElement("w", "col", OpenXmlNamespaces.WordprocessingML);
                    XmlAttribute w     = _nodeFactory.CreateAttribute("w", "w", OpenXmlNamespaces.WordprocessingML);
                    XmlAttribute space = _nodeFactory.CreateAttribute("w", "space", OpenXmlNamespaces.WordprocessingML);
                    w.Value     = _colWidth[i].ToString();
                    space.Value = _colSpace[i].ToString();
                    col.Attributes.Append(w);
                    col.Attributes.Append(space);
                    cols.AppendChild(col);
                }
            }

            //append the section type
            appendValueElement(_sectPr, "type", _type.ToString(), true);

            //append footnote properties
            if (footnotePr.ChildNodes.Count > 0)
            {
                _sectPr.AppendChild(footnotePr);
            }

            //append page size
            if (pgSz.Attributes.Count > 0)
            {
                _sectPr.AppendChild(pgSz);
            }

            //append borders
            if (pgBorders.ChildNodes.Count > 0)
            {
                _sectPr.AppendChild(pgBorders);
            }

            //append margin
            if (pgMar.Attributes.Count > 0)
            {
                _sectPr.AppendChild(pgMar);
            }

            //append paper info
            if (paperSrc.Attributes.Count > 0)
            {
                _sectPr.AppendChild(paperSrc);
            }

            //append columns

            if (cols.Attributes.Count > 0 || cols.ChildNodes.Count > 0)
            {
                _sectPr.AppendChild(cols);
            }

            //append doc grid
            if (docGrid.Attributes.Count > 0)
            {
                _sectPr.AppendChild(docGrid);
            }

            //numType
            if (pgNumType.Attributes.Count > 0)
            {
                _sectPr.AppendChild(pgNumType);
            }

            if (_writer != null)
            {
                //write the properties
                _sectPr.WriteTo(_writer);
            }
        }