//public static SectionProperties CreateSectionProperties() //{ // SectionProperties sectionProperties = new SectionProperties(); // return sectionProperties; //} public static void SetSectionPage(SectionProperties sectionProperties) { // PageSize, <w:pgSz w:w="11907" w:h="16839"/>, 11907 1/20 point = 21 cm, 16839 1/20 point = 29.7 cm, unit = 1/20 point, 11907 1/20 point = 595.35 point sectionProperties.AppendChild(new PageSize { Width = 11907, Height = 16839 }); // top 1.27 cm, bottom 1.27 cm, left 2.5 cm, right 2.5 cm, header 0.5 cm, footer 0.5 cm // <w:pgMar w:top="720" w:right="1418" w:bottom="720" w:left="1418" w:header="284" w:footer="284" w:gutter="0"/> sectionProperties.AppendChild(new PageMargin { Top = 720, Bottom = 720, Left = 1418, Right = 1418, Header = 284, Footer = 284 }); }
/// <summary> /// Adds the image paragraph. /// Source: https://stackoverflow.com/questions/50645759/openxml-force-image-fit-in-parent-container /// </summary> /// <param name="pngBase64String">The PNG base64 string.</param> public void AddImageParagraph(string pngBase64String) { var html = $"<p><img src=\"data:image/png;base64,{pngBase64String}\" alt=\"Image\" /></p>"; var converter = new HtmlConverter(_wordProcessingDocument.MainDocumentPart); var compositeElements = converter.Parse(html); // Set Page Size and Page Margin so that we can place the image as desired. // Available Width = PageWidth - PageMarginLeft - PageMarginRight (= 17000 - 1000 - 1000 = 15000 for default values) var sectionProperties = new SectionProperties(); sectionProperties.AppendChild(new PageSize { Width = PageWidth, Height = PageHeight }); sectionProperties.AppendChild(new PageMargin { Left = PageMarginLeft, Bottom = PageMarginBottom, Top = PageMarginTop, Right = PageMarginRight }); _wordProcessingDocument.MainDocumentPart.Document.Body.AppendChild(sectionProperties); if (compositeElements[0] is Paragraph p) { // Search for Extents used by the word present in Drawing > Inline > Extent var inlineEnumerable = p.ChildElements.Where(e => e is Run) .Where(r => r.GetFirstChild <Drawing>() != null).Select(r => r.GetFirstChild <Drawing>()) .Where(r => r.GetFirstChild <Inline>() != null).Select(r => r.GetFirstChild <Inline>()); // Update Visible Extent var inlineChildren = inlineEnumerable as Inline[] ?? inlineEnumerable.ToArray(); foreach (var inlineChild in inlineChildren) { var inlineElement = inlineChild.Extent; UpdateExtent(inlineElement); } // Search for Extents used by the word present in Drawing > Inline > Graphic > GraphicData > Picture > ShapeProperties > Transform2D > Extents var extentsEnumerable = inlineChildren .Where(r => r.GetFirstChild <Graphic>() != null).Select(d => d.GetFirstChild <Graphic>()) .Where(r => r.GetFirstChild <GraphicData>() != null).Select(r => r.GetFirstChild <GraphicData>()) .Where(r => r.GetFirstChild <Picture>() != null) .Select(r => r.GetFirstChild <Picture>()) .Where(r => r.GetFirstChild <ShapeProperties>() != null) .Select(r => r.GetFirstChild <ShapeProperties>()) .Where(r => r.GetFirstChild <Transform2D>() != null).Select(r => r.GetFirstChild <Transform2D>()) .Where(r => r.GetFirstChild <Extents>() != null).Select(r => r.GetFirstChild <Extents>()); // Modify all images in Extents to the desired size here, to be stretched out on available page width foreach (var extents in extentsEnumerable) { // Set Image Size: We calculate Aspect Ratio of the image and then calculate the width and update the height as per aspect ratio var inlineElement = extents; UpdateExtent(inlineElement); } } _wordProcessingDocument.MainDocumentPart.Document.Body.Append(compositeElements); }
public static void SetSectionPageNumberType(SectionProperties sectionProperties, int start = 0) { // PageNumberType, <w:pgNumType w:start="0" /> sectionProperties.AppendChild(new PageNumberType { Start = start }); }
public void Transform(string firstName, string lastName, string city) { using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(LastConvertedWordFileName ?? LastWordFileName, true)) { Body body = wordprocessingDocument.MainDocumentPart.Document.Body; var firstParagraph = body.ChildElements.FirstOrDefault(c => c is Paragraph); if (firstParagraph != null) { AddPersonalRow(body, firstParagraph, firstName, lastName, city); } ApplyColorsFormat(body); Paragraph breakParagraph = new Paragraph(); ParagraphProperties breakProperties = new ParagraphProperties(); SectionProperties sectionProperties = new SectionProperties(); SectionType sectionType = new SectionType() { Val = SectionMarkValues.NextPage }; sectionProperties.AppendChild(sectionType); breakProperties.AppendChild(sectionProperties); breakParagraph.AppendChild(breakProperties); body.AppendChild(breakParagraph); AddSecondPageTable(body); } }
/// <summary> /// set section pagesize to portrait of given paper type /// </summary> public static void SetPaper(this SectionProperties section, PaperType paper) { var pageSize = section.Descendants <PageSize>().FirstOrDefault(); if (pageSize == null) { pageSize = section.AppendChild(new PageSize()); } int w = 0; int h = 0; switch (paper) { case PaperType.A4: { w = 210; h = 297; } break; default: throw new Exception($"unsupported paper type {paper}"); } pageSize.Width = (uint)w.MMToTwip(); pageSize.Height = (uint)h.MMToTwip(); pageSize.Orient = new EnumValue <PageOrientationValues>(PageOrientationValues.Portrait); }
/// <summary> /// Настройки страницы /// </summary> /// <returns></returns> private static SectionProperties CreateSectionProperties() { SectionProperties properties = new SectionProperties(); PageSize pageSize = new PageSize { Orient = PageOrientationValues.Portrait }; properties.AppendChild(pageSize); return(properties); }
//private void AddPage() //{ // _paragraph = _body.AppendChild(new Paragraph()); // _run = _paragraph.AppendChild(new Run()); //} private void AddDocSection(OXmlDocSectionElement element) { //Trace.WriteLine("OXmlDoc.AddDocSection()"); CreateSectionProperties(); // PageSize, <w:pgSz w:w="11907" w:h="16839"/>, 11907 1/20 point = 21 cm, 16839 1/20 point = 29.7 cm, unit = 1/20 point, 11907 1/20 point = 595.35 point PageSize pageSize = CreatePageSize(element.PageSize); if (pageSize != null) { _sectionProperties.AppendChild(pageSize); } // <w:pgMar w:top="720" w:right="1418" w:bottom="720" w:left="1418" w:header="284" w:footer="284" w:gutter="0"/> PageMargin pageMargin = CreatePageMargin(element.PageMargin); if (pageMargin != null) { _sectionProperties.AppendChild(pageMargin); } // PageNumberType, <w:pgNumType w:start="0" /> if (element.PageNumberStart != null) { _sectionProperties.AppendChild(new PageNumberType { Start = element.PageNumberStart }); } }
private static SectionProperties FillSectionProperties(WordprocessingDocument wpDocument, SectionProperties sectionProperties, Page page, PageLayout defaultPageLayout, Table defaultFooter) { var pageOrientation = page.Parameters.Orientation ?? defaultPageLayout.Orientation ?? PageOrientation.Portrait; var width = (uint)OpenXmlUnits.FromMmTo20thOfPoint(page.Parameters.Size.Width); var height = (uint)OpenXmlUnits.FromMmTo20thOfPoint(page.Parameters.Size.Height); sectionProperties.AppendChild(new PageSize { Orient = ConvertOrientation(pageOrientation), Width = pageOrientation == PageOrientation.Portrait ? width : height, Height = pageOrientation == PageOrientation.Portrait ? height : width }); sectionProperties.AppendChild(new PageMargin { Left = (uint?)GetMargin(page.Parameters.MarginLeft, defaultPageLayout.MarginLeft), Top = GetMargin(page.Parameters.MarginTop, defaultPageLayout.MarginTop), Right = (uint?)GetMargin(page.Parameters.MarginRight, defaultPageLayout.MarginRight), Bottom = GetMargin(page.Parameters.MarginBottom, defaultPageLayout.MarginBottom), Header = (uint?)GetMargin(page.Parameters.HeaderMargin, defaultPageLayout.HeaderMargin), Footer = (uint?)GetMargin(page.Parameters.FooterMargin, defaultPageLayout.FooterMargin) }); if (page.Parameters.Footer != null || defaultFooter != null) { var footerPart = wpDocument.MainDocumentPart.AddNewPart <FooterPart>(); var footerPartId = wpDocument.MainDocumentPart.GetIdOfPart(footerPart); sectionProperties.AppendChild(new FooterReference { Id = footerPartId, Type = HeaderFooterValues.Default }); var footer = new Footer(TableConverter.Convert(page.Parameters.Footer ?? defaultFooter, wpDocument)); footer.Save(footerPart); } return(sectionProperties); }
private void CreateFooter(SectionProperties sectionProperties, MainDocumentPart mainPart) { var footerPart = mainPart.AddNewPart <FooterPart>(); var partId = mainPart.GetIdOfPart(footerPart); footerPart.Footer = new Footer(Footer.Where(x => x != null).AsIndexed() .Select(x => x.Value.Render(x.Index, x.IsFirst, x.IsLast))); sectionProperties.AppendChild(new FooterReference { Id = partId, Type = HeaderFooterValues.Default }); footerPart.Footer.Save(); }
/// <summary> /// set section margin /// </summary> public static void SetMargin(this SectionProperties section, double marginLeftMM = 0, double marginTopMM = 0, double marginRightMM = 0, double marginBottomMM = 0) { var margin = section.Descendants <PageMargin>().FirstOrDefault(); if (margin == null) { margin = section.AppendChild(new PageMargin()); } margin.Left = (uint)marginLeftMM.MMToTwip(); margin.Top = marginTopMM.MMToTwip(); margin.Right = (uint)marginRightMM.MMToTwip(); margin.Bottom = marginBottomMM.MMToTwip(); }
//public static void AddSection(Body body, string defaultHeaderPartId = null, string defaultFooterPartId = null, string firstHeaderPartId = null, string firstFooterPartId = null) public static void SetSectionHeaders(SectionProperties sectionProperties, string defaultHeaderPartId = null, string defaultFooterPartId = null, string firstHeaderPartId = null, string firstFooterPartId = null, string evenHeaderPartId = null, string evenFooterPartId = null) { // TitlePage, <w:titlePg />, mandatory for first page header sectionProperties.AppendChild(new TitlePage { Val = true }); // EnumValue<HeaderFooterValues> Type : Even, Default, First if (defaultHeaderPartId != null) { sectionProperties.AppendChild(new HeaderReference { Id = defaultHeaderPartId, Type = HeaderFooterValues.Default }); } if (defaultFooterPartId != null) { sectionProperties.AppendChild(new FooterReference { Id = defaultFooterPartId, Type = HeaderFooterValues.Default }); } if (firstHeaderPartId != null) { sectionProperties.AppendChild(new HeaderReference { Id = firstHeaderPartId, Type = HeaderFooterValues.First }); } if (firstFooterPartId != null) { sectionProperties.AppendChild(new FooterReference { Id = firstFooterPartId, Type = HeaderFooterValues.First }); } if (evenHeaderPartId != null) { sectionProperties.AppendChild(new HeaderReference { Id = evenHeaderPartId, Type = HeaderFooterValues.Even }); } if (evenFooterPartId != null) { sectionProperties.AppendChild(new FooterReference { Id = evenFooterPartId, Type = HeaderFooterValues.Even }); } }
public static void Render(this Page page, Models.Document document, OpenXmlElement wdDoc, ContextModel context, MainDocumentPart mainDocumentPart, IFormatProvider formatProvider) { if (!string.IsNullOrWhiteSpace(page.ShowKey) && context.ExistItem <BooleanModel>(page.ShowKey) && !context.GetItem <BooleanModel>(page.ShowKey).Value) { return; } // add page content ((BaseElement)page).Render(document, wdDoc, context, mainDocumentPart, formatProvider); // add section to manage orientation. Last section is at the end of document var pageSize = new PageSize() { Orient = page.PageOrientation.ToOOxml(), Width = UInt32Value.FromUInt32(page.PageOrientation == PageOrientationValues.Landscape ? (uint)16839 : 11907), Height = UInt32Value.FromUInt32(page.PageOrientation == PageOrientationValues.Landscape ? (uint)11907 : 16839) }; var sectionProps = new SectionProperties(pageSize); // document margins if (page.Margin != null) { var pageMargins = new PageMargin() { Left = page.Margin.Left, Top = page.Margin.Top, Right = page.Margin.Right, Bottom = page.Margin.Bottom, Footer = page.Margin.Footer, Header = page.Margin.Header }; sectionProps.AppendChild(pageMargins); } var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); var ppr = new ParagraphProperties(); p.AppendChild(ppr); ppr.AppendChild(sectionProps); wdDoc.AppendChild(p); }
//public static void AddSection(Body body, string defaultHeaderPartId = null, string defaultFooterPartId = null, string firstHeaderPartId = null, string firstFooterPartId = null) public static void SetSectionHeaders(SectionProperties sectionProperties, string defaultHeaderPartId = null, string defaultFooterPartId = null, string firstHeaderPartId = null, string firstFooterPartId = null, string evenHeaderPartId = null, string evenFooterPartId = null) { // TitlePage, <w:titlePg />, mandatory for first page header sectionProperties.AppendChild(new TitlePage { Val = true }); // EnumValue<HeaderFooterValues> Type : Even, Default, First if (defaultHeaderPartId != null) sectionProperties.AppendChild(new HeaderReference { Id = defaultHeaderPartId, Type = HeaderFooterValues.Default }); if (defaultFooterPartId != null) sectionProperties.AppendChild(new FooterReference { Id = defaultFooterPartId, Type = HeaderFooterValues.Default }); if (firstHeaderPartId != null) sectionProperties.AppendChild(new HeaderReference { Id = firstHeaderPartId, Type = HeaderFooterValues.First }); if (firstFooterPartId != null) sectionProperties.AppendChild(new FooterReference { Id = firstFooterPartId, Type = HeaderFooterValues.First }); if (evenHeaderPartId != null) sectionProperties.AppendChild(new HeaderReference { Id = evenHeaderPartId, Type = HeaderFooterValues.Even }); if (evenFooterPartId != null) sectionProperties.AppendChild(new FooterReference { Id = evenFooterPartId, Type = HeaderFooterValues.Even }); }
private void TestSimpleGroup2(SdbSchemaDatas sdbSchemaDatas) { ValidationContext validationContext = new ValidationContext(); ValidationResult actual = new ValidationResult(); validationContext.ValidationErrorEventHandler += actual.OnValidationError; OpenXmlElement errorChild; SectionProperties sectPr = new SectionProperties(); var expected = sectPr; var particleConstraint = sdbSchemaDatas.GetSchemaTypeData(sectPr).ParticleConstraint; var target = particleConstraint.ParticleValidator as SequenceParticleValidator; validationContext.Element = sectPr; //<xsd:complexType name="CT_SectPr"> // <xsd:sequence> // <xsd:group ref="EG_HdrFtrReferences" minOccurs="0" maxOccurs="6"></xsd:group> // <xsd:group ref="EG_SectPrContents" minOccurs="0"></xsd:group> // <xsd:element name="sectPrChange" type="CT_SectPrChange" minOccurs="0"> // </xsd:sequence> // <xsd:attributeGroup ref="AG_SectPrAttributes"></xsd:attributeGroup> //</xsd:complexType> //<xsd:group name="EG_HdrFtrReferences"> // <xsd:choice> // <xsd:element name="headerReference" type="CT_HdrFtrRef" minOccurs="0"> // <xsd:element name="footerReference" type="CT_HdrFtrRef" minOccurs="0"> // </xsd:choice> //</xsd:group> //<xsd:group name="EG_SectPrContents"> // <xsd:sequence> // <xsd:element name="footnotePr" type="CT_FtnProps" minOccurs="0"> // <xsd:element name="endnotePr" type="CT_EdnProps" minOccurs="0"> // <xsd:element name="type" type="CT_SectType" minOccurs="0"> // <xsd:element name="pgSz" type="CT_PageSz" minOccurs="0"> // <xsd:element name="pgMar" type="CT_PageMar" minOccurs="0"> // <xsd:element name="paperSrc" type="CT_PaperSource" minOccurs="0"> // <xsd:element name="pgBorders" type="CT_PageBorders" minOccurs="0"> // <xsd:element name="lnNumType" type="CT_LineNumber" minOccurs="0"> // <xsd:element name="pgNumType" type="CT_PageNumber" minOccurs="0"> // <xsd:element name="cols" type="CT_Columns" minOccurs="0"> // <xsd:element name="formProt" type="CT_OnOff" minOccurs="0"> // <xsd:element name="vAlign" type="CT_VerticalJc" minOccurs="0"> // <xsd:element name="noEndnote" type="CT_OnOff" minOccurs="0"> // <xsd:element name="titlePg" type="CT_OnOff" minOccurs="0"> // <xsd:element name="textDirection" type="CT_TextDirection" minOccurs="0"> // <xsd:element name="bidi" type="CT_OnOff" minOccurs="0"> // <xsd:element name="rtlGutter" type="CT_OnOff" minOccurs="0"> // <xsd:element name="docGrid" type="CT_DocGrid" minOccurs="0"> // <xsd:element name="printerSettings" type="CT_Rel" minOccurs="0"> // </xsd:sequence> //</xsd:group> // ***** good case ****** // empty is ok target.Validate(validationContext); Assert.True(actual.Valid); // headerReference is ok sectPr.Append(new HeaderReference()); target.Validate(validationContext); Assert.True(actual.Valid); // headerReference and footerReference sectPr.Append(new FooterReference()); target.Validate(validationContext); Assert.True(actual.Valid); // footerReference sectPr.RemoveChild(sectPr.FirstChild); target.Validate(validationContext); Assert.True(actual.Valid); // 3 group <= 6, ok sectPr.Append(new HeaderReference(), new HeaderReference()); target.Validate(validationContext); Assert.True(actual.Valid); // 5 group <= 6, ok sectPr.Append(new HeaderReference(), new HeaderReference()); target.Validate(validationContext); Assert.True(actual.Valid); // 6 group <= 6, ok sectPr.Append(new HeaderReference()); target.Validate(validationContext); Assert.True(actual.Valid); // no EG_SectPrContents is ok sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new FooterReference(), new SectionPropertiesChange()); Assert.True(actual.Valid); // test EG_SectPrContents sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new FooterReference(), new SectionType()); Assert.True(actual.Valid); // sectPr.AppendChild(new PaperSource()); Assert.True(actual.Valid); sectPr.AppendChild(new TitlePage()); Assert.True(actual.Valid); sectPr.AppendChild(new PrinterSettingsReference()); Assert.True(actual.Valid); sectPr.AppendChild(new SectionPropertiesChange()); Assert.True(actual.Valid); sectPr.RemoveAllChildren(); sectPr.Append(new SectionPropertiesChange()); Assert.True(actual.Valid); // ***** error case ****** // 7 group > 6, error sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new HeaderReference(), new FooterReference(), new FooterReference(), new HeaderReference(), new HeaderReference()); errorChild = sectPr.AppendChild(new HeaderReference()); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", actual.Errors[0].Id); Assert.False(actual.Errors[0].Description.Contains(ValidationErrorStrings.Fmt_ListOfPossibleElements)); sectPr.RemoveChild(errorChild); actual.Clear(); //first is invalid errorChild = sectPr.PrependChild(new Paragraph()); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_InvalidElementContentExpectingComplex", actual.Errors[0].Id); Assert.True(actual.Errors[0].Description.Contains(":headerReference")); Assert.True(actual.Errors[0].Description.Contains(":footerReference")); Assert.False(actual.Errors[0].Description.Contains(":footnotePr")); Assert.False(actual.Errors[0].Description.Contains(":sectPrChange")); sectPr.RemoveChild(errorChild); actual.Clear(); //invalid child in middle errorChild = sectPr.InsertBefore(new Paragraph(), sectPr.LastChild); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_InvalidElementContentExpectingComplex", actual.Errors[0].Id); Assert.False(actual.Errors[0].Description.Contains(ValidationErrorStrings.Fmt_ListOfPossibleElements)); sectPr.RemoveChild(errorChild); actual.Clear(); // order wrong errorChild = sectPr.FirstChild; sectPr.PrependChild(new SectionType()); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", actual.Errors[0].Id); Assert.False(actual.Errors[0].Description.Contains(ValidationErrorStrings.Fmt_ListOfPossibleElements)); actual.Clear(); // dup error sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new PaperSource()); errorChild = sectPr.AppendChild( new PaperSource()); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", actual.Errors[0].Id); Assert.False(actual.Errors[0].Description.Contains(ValidationErrorStrings.Fmt_ListOfPossibleElements)); sectPr.RemoveChild(errorChild); actual.Clear(); // out of order error errorChild = sectPr.AppendChild(new SectionType()); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", actual.Errors[0].Id); Assert.False(actual.Errors[0].Description.Contains(ValidationErrorStrings.Fmt_ListOfPossibleElements)); sectPr.RemoveChild(errorChild); actual.Clear(); // out of order error sectPr.AppendChild(new SectionPropertiesChange()); errorChild = sectPr.AppendChild(new SectionType()); target.Validate(validationContext); Assert.False(actual.Valid); Assert.Equal(1, actual.Errors.Count); Assert.Same(expected, actual.Errors[0].Node); Assert.Same(errorChild, actual.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, actual.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", actual.Errors[0].Id); Assert.False(actual.Errors[0].Description.Contains(ValidationErrorStrings.Fmt_ListOfPossibleElements)); }
private void TestSimpleGroup2(SdbSchemaDatas sdbSchemaDatas) { ValidationContext validationContext = new ValidationContext(); OpenXmlElement errorChild; SectionProperties sectPr = new SectionProperties(); var expected = sectPr; var particleConstraint = sdbSchemaDatas.GetSchemaTypeData(sectPr).ParticleConstraint; var target = particleConstraint.ParticleValidator as SequenceParticleValidator; validationContext.Element = sectPr; //<xsd:complexType name="CT_SectPr"> // <xsd:sequence> // <xsd:group ref="EG_HdrFtrReferences" minOccurs="0" maxOccurs="6"></xsd:group> // <xsd:group ref="EG_SectPrContents" minOccurs="0"></xsd:group> // <xsd:element name="sectPrChange" type="CT_SectPrChange" minOccurs="0"> // </xsd:sequence> // <xsd:attributeGroup ref="AG_SectPrAttributes"></xsd:attributeGroup> //</xsd:complexType> //<xsd:group name="EG_HdrFtrReferences"> // <xsd:choice> // <xsd:element name="headerReference" type="CT_HdrFtrRef" minOccurs="0"> // <xsd:element name="footerReference" type="CT_HdrFtrRef" minOccurs="0"> // </xsd:choice> //</xsd:group> //<xsd:group name="EG_SectPrContents"> // <xsd:sequence> // <xsd:element name="footnotePr" type="CT_FtnProps" minOccurs="0"> // <xsd:element name="endnotePr" type="CT_EdnProps" minOccurs="0"> // <xsd:element name="type" type="CT_SectType" minOccurs="0"> // <xsd:element name="pgSz" type="CT_PageSz" minOccurs="0"> // <xsd:element name="pgMar" type="CT_PageMar" minOccurs="0"> // <xsd:element name="paperSrc" type="CT_PaperSource" minOccurs="0"> // <xsd:element name="pgBorders" type="CT_PageBorders" minOccurs="0"> // <xsd:element name="lnNumType" type="CT_LineNumber" minOccurs="0"> // <xsd:element name="pgNumType" type="CT_PageNumber" minOccurs="0"> // <xsd:element name="cols" type="CT_Columns" minOccurs="0"> // <xsd:element name="formProt" type="CT_OnOff" minOccurs="0"> // <xsd:element name="vAlign" type="CT_VerticalJc" minOccurs="0"> // <xsd:element name="noEndnote" type="CT_OnOff" minOccurs="0"> // <xsd:element name="titlePg" type="CT_OnOff" minOccurs="0"> // <xsd:element name="textDirection" type="CT_TextDirection" minOccurs="0"> // <xsd:element name="bidi" type="CT_OnOff" minOccurs="0"> // <xsd:element name="rtlGutter" type="CT_OnOff" minOccurs="0"> // <xsd:element name="docGrid" type="CT_DocGrid" minOccurs="0"> // <xsd:element name="printerSettings" type="CT_Rel" minOccurs="0"> // </xsd:sequence> //</xsd:group> // ***** good case ****** // empty is ok target.Validate(validationContext); Assert.True(validationContext.Valid); // headerReference is ok sectPr.Append(new HeaderReference()); target.Validate(validationContext); Assert.True(validationContext.Valid); // headerReference and footerReference sectPr.Append(new FooterReference()); target.Validate(validationContext); Assert.True(validationContext.Valid); // footerReference sectPr.RemoveChild(sectPr.FirstChild); target.Validate(validationContext); Assert.True(validationContext.Valid); // 3 group <= 6, ok sectPr.Append(new HeaderReference(), new HeaderReference()); target.Validate(validationContext); Assert.True(validationContext.Valid); // 5 group <= 6, ok sectPr.Append(new HeaderReference(), new HeaderReference()); target.Validate(validationContext); Assert.True(validationContext.Valid); // 6 group <= 6, ok sectPr.Append(new HeaderReference()); target.Validate(validationContext); Assert.True(validationContext.Valid); // no EG_SectPrContents is ok sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new FooterReference(), new SectionPropertiesChange()); Assert.True(validationContext.Valid); // test EG_SectPrContents sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new FooterReference(), new SectionType()); Assert.True(validationContext.Valid); // sectPr.AppendChild(new PaperSource()); Assert.True(validationContext.Valid); sectPr.AppendChild(new TitlePage()); Assert.True(validationContext.Valid); sectPr.AppendChild(new PrinterSettingsReference()); Assert.True(validationContext.Valid); sectPr.AppendChild(new SectionPropertiesChange()); Assert.True(validationContext.Valid); sectPr.RemoveAllChildren(); sectPr.Append(new SectionPropertiesChange()); Assert.True(validationContext.Valid); // ***** error case ****** // 7 group > 6, error sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new HeaderReference(), new FooterReference(), new FooterReference(), new HeaderReference(), new HeaderReference()); errorChild = sectPr.AppendChild(new HeaderReference()); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.DoesNotContain(ValidationErrorStrings.Fmt_ListOfPossibleElements, validationContext.Errors[0].Description); sectPr.RemoveChild(errorChild); validationContext.Clear(); //first is invalid errorChild = sectPr.PrependChild(new Paragraph()); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_InvalidElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.Contains(":headerReference", validationContext.Errors[0].Description); Assert.Contains(":footerReference", validationContext.Errors[0].Description); Assert.DoesNotContain(":footnotePr", validationContext.Errors[0].Description); Assert.DoesNotContain(":sectPrChange", validationContext.Errors[0].Description); sectPr.RemoveChild(errorChild); validationContext.Clear(); //invalid child in middle errorChild = sectPr.InsertBefore(new Paragraph(), sectPr.LastChild); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_InvalidElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.DoesNotContain(ValidationErrorStrings.Fmt_ListOfPossibleElements, validationContext.Errors[0].Description); sectPr.RemoveChild(errorChild); validationContext.Clear(); // order wrong errorChild = sectPr.FirstChild; sectPr.PrependChild(new SectionType()); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.DoesNotContain(ValidationErrorStrings.Fmt_ListOfPossibleElements, validationContext.Errors[0].Description); validationContext.Clear(); // dup error sectPr.RemoveAllChildren(); sectPr.Append(new HeaderReference(), new PaperSource()); errorChild = sectPr.AppendChild(new PaperSource()); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.DoesNotContain(ValidationErrorStrings.Fmt_ListOfPossibleElements, validationContext.Errors[0].Description); sectPr.RemoveChild(errorChild); validationContext.Clear(); // out of order error errorChild = sectPr.AppendChild(new SectionType()); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.DoesNotContain(ValidationErrorStrings.Fmt_ListOfPossibleElements, validationContext.Errors[0].Description); sectPr.RemoveChild(errorChild); validationContext.Clear(); // out of order error sectPr.AppendChild(new SectionPropertiesChange()); errorChild = sectPr.AppendChild(new SectionType()); target.Validate(validationContext); Assert.False(validationContext.Valid); Assert.Single(validationContext.Errors); Assert.Same(expected, validationContext.Errors[0].Node); Assert.Same(errorChild, validationContext.Errors[0].RelatedNode); Assert.Equal(ValidationErrorType.Schema, validationContext.Errors[0].ErrorType); Assert.Equal("Sch_UnexpectedElementContentExpectingComplex", validationContext.Errors[0].Id); Assert.DoesNotContain(ValidationErrorStrings.Fmt_ListOfPossibleElements, validationContext.Errors[0].Description); }
public void ExportWordDocument(string filepath) { using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); #region 标题文字(加粗居中) Paragraph para = body.AppendChild(new Paragraph()); ParagraphProperties pPr = para.AppendChild(new ParagraphProperties()); pPr.Append(new Justification() { Val = JustificationValues.Center }); Run run = para.AppendChild(new Run()); RunProperties rPr = new RunProperties(new RunFonts() { Ascii = "宋体", ComplexScript = "宋体", EastAsia = "宋体", HighAnsi = "宋体" }); rPr.Append(new FontSize() { Val = "40" }); rPr.Append(new Bold() { Val = true }); run.Append(rPr); run.Append(new Text("钢轨探伤仪探伤报告")); #endregion //rPr.FontSize.Val = "40"; //rPr.Append(new RunFonts() { ComplexScript = "宋体" }); //rPr.RunFonts.ComplexScript = "宋体"; //Run r = wordDocument.MainDocumentPart.Document.Descendants<Run>().First(); //r.PrependChild(rPr); #region 表格 Table table = new Table(); #region 表格样式 // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableBorders( new TopBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new BottomBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new LeftBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new RightBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new InsideHorizontalBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 }, new InsideVerticalBorder() { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 1 } ) ); tblProp.TableWidth = new TableWidth() { Width = "9639", Type = TableWidthUnitValues.Dxa }; tblProp.TableLayout = new TableLayout() { Type = TableLayoutValues.Fixed }; //固定列宽 tblProp.TableLook = new TableLook() { Val = "0000", FirstRow = false, LastRow = false, FirstColumn = false, LastColumn = false }; table.Append(tblProp); #endregion #region 成员模板 //Paragraph tblPara = new Paragraph(); //ParagraphProperties tblpPr = tblPara.AppendChild(new ParagraphProperties()); //tblpPr.AppendChild(new Justification() { Val = JustificationValues.Left }); //tblpPr.AppendChild( // new RunProperties( // new RunFonts() { Ascii = "宋体", ComplexScript = @"宋体", EastAsia = "宋体", HighAnsi = "宋体" }, // new FontSize() { Val = "24" }) // ); TableRow tr = new TableRow(); tr.AppendChild(new TableRowProperties(new TableRowHeight() { Val = 454 })); TableCell tc = new TableCell(); tc.AppendChild(new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center } //,new Shading() { Val = ShadingPatternValues.Clear, Fill = "auto" }// 阴影 )); tc.AppendChild(new TableCellMargin( new LeftMargin() { Width = "100" } )); Run tblRun = new Run(); tblRun.AppendChild(new RunProperties( new RunFonts() { Ascii = "宋体", ComplexScript = @"宋体", EastAsia = "宋体", HighAnsi = "宋体" }, new FontSize() { Val = "24" }, new Bold() { Val = true } )); #endregion #region 例1 { // Create a row. TableRow test1 = new TableRow(tr.OuterXml); // Create a cell. // Create a second table cell by copying the OuterXml value of the first table cell. TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("some text 1")); run2.Append(new Text("some text 2")); run3.Append(new Text("some text 3")); run4.Append(new Text("文字4:")); run5.Append(new Text("some text 5")); run6.Append(new Text("text 6")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); //Paragraph para1 = new Paragraph(tlbPara.OuterXml); //Paragraph para2 = new Paragraph(tlbPara.OuterXml); //Paragraph para3 = new Paragraph(tlbPara.OuterXml); //Paragraph para4 = new Paragraph(tlbPara.OuterXml); //Paragraph para5 = new Paragraph(tlbPara.OuterXml); //Paragraph para6 = new Paragraph(tlbPara.OuterXml); //para1.Append(new Run(new Text("some text 1"))); //para2.Append(new Run(new Text("some text 2"))); //para3.Append(new Run(new Text("some text 3"))); //para4.Append(new Run(new Text("some text 4"))); //para5.Append(new Run(new Text("some text 5"))); //para6.Append(new Run(new Text("some text 6"))); //tc1.Append(para1); //tc2.Append(para2); //tc3.Append(para3); //tc4.Append(para4); //tc5.Append(para5); //tc6.Append(para6); // Append the table cell to the table row. test1.Append(tc1); test1.Append(tc2); test1.Append(tc3); test1.Append(tc4); test1.Append(tc5); test1.Append(tc6); // Append the table row to the table. //table.Append(test1); } #endregion #region 第一行 { TableRow tr1 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("线名:")); run2.Append(new Text("000")); run3.Append(new Text("线别:")); run4.Append(new Text("正线")); run5.Append(new Text("股别:")); run6.Append(new Text("右")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); // Append the table cell to the table row. tr1.Append(tc1); tr1.Append(tc2); tr1.Append(tc3); tr1.Append(tc4); tr1.Append(tc5); tr1.Append(tc6); // Append the table row to the table. table.Append(tr1); } #endregion #region 第二行 { TableRow tr2 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("轨型:")); run2.Append(new Text("60")); run3.Append(new Text("伤损类型:")); run4.Append(new Text("")); run5.Append(new Text("生产厂商:")); run6.Append(new Text("")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); // Append the table cell to the table row. tr2.Append(tc1); tr2.Append(tc2); tr2.Append(tc3); tr2.Append(tc4); tr2.Append(tc5); tr2.Append(tc6); // Append the table row to the table. table.Append(tr2); } #endregion #region 第三行 { TableRow tr3 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCell tc5 = new TableCell(tc.OuterXml); TableCell tc6 = new TableCell(tc.OuterXml); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); Run run5 = new Run(tblRun.OuterXml); Run run6 = new Run(tblRun.OuterXml); run1.Append(new Text("伤损编号:")); run2.Append(new Text("")); run3.Append(new Text("探伤时间:")); run4.Append(new Text(DateTime.Now.ToString())); run5.Append(new Text("探伤人员:")); run6.Append(new Text("")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); tc5.Append(new Paragraph(run5)); tc6.Append(new Paragraph(run6)); // Append the table cell to the table row. tr3.Append(tc1); tr3.Append(tc2); tr3.Append(tc3); tr3.Append(tc4); tr3.Append(tc5); tr3.Append(tc6); // Append the table row to the table. table.Append(tr3); } #endregion #region 第四行 { TableRow tr4 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCellProperties tcPr = tc2.Descendants <TableCellProperties>().First(); tcPr.Append(new GridSpan() { Val = 5 }); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); run1.Append(new Text("增益:")); run2.Append(new Text("A:45.0dB B:45.5dB C:45.5dB")); run3.Append(new Text("D:45.5dB E:45.0dB F:45.0dB")); run4.Append(new Text("G:46.5dB H:46.5dB I:52.0dB")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc2.Append(new Paragraph(run3)); tc2.Append(new Paragraph(run4)); // Append the table cell to the table row. tr4.Append(tc1); tr4.Append(tc2); // Append the table row to the table. table.Append(tr4); } #endregion #region 第五行 { TableRow tr5 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableRowProperties tblPr4 = tr5.Descendants <TableRowProperties>().First(); tblPr4.AppendChild(new TableRowHeight() { Val = 9000 }); TableCellProperties tcPr = tc1.Descendants <TableCellProperties>().First(); tcPr.Append( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Top }, new GridSpan() { Val = 6 } ); tcPr.Append(new TableCellMargin(new TopMargin() { Width = "50" })); //new Shading() { Val = ShadingPatternValues.Clear, Fill = "auto" } // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); //地段:0 //当前里程:0km039m run1.Append(new Text("地段:")); run2.Append(new Text("0")); run3.Append(new Text("当前里程:")); run4.Append(new Text("0km039m")); tc1.Append(new Paragraph(run1, run2)); //tc1.Append(new Paragraph(run2)); tc1.Append(new Paragraph(run3, run4)); //tc1.Append(new Paragraph(run4)); ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); //Bitmap bitmap = new Bitmap(500, 500); //Graphics g = Graphics.FromImage(bitmap); //g.Clear(System.Drawing.Color.Pink); //using (MemoryStream stream = new MemoryStream()) //{ // bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); // imagePart.FeedData(stream); //} //////string fileName = @"?D:\Users\KETIZU2\Desktop\images\logo.jpg"; string fileName = @"D:\Users\KETIZU2\Desktop\images\logo.jpg"; using (FileStream stream = new FileStream(fileName, FileMode.Open)) { imagePart.FeedData(stream); } // Define the reference of the image. Paragraph paraImage = AddImageToParagraph(mainPart.GetIdOfPart(imagePart), 6120000L, 2160000L); //wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element))); tc1.AppendChild(paraImage); // Append the table cell to the table row. tr5.Append(tc1); // Append the table row to the table. table.Append(tr5); } #endregion #region 第六行 { TableRow tr6 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCellProperties tcPr = tc2.Descendants <TableCellProperties>().First(); tcPr.Append(new GridSpan() { Val = 5 }); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); run1.Append(new Text("单位名称:")); run2.Append(new Text("")); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); // Append the table cell to the table row. tr6.Append(tc1); tr6.Append(tc2); // Append the table row to the table. table.Append(tr6); } #endregion #region 第七行 { TableRow tr7 = new TableRow(tr.OuterXml); TableCell tc1 = new TableCell(tc.OuterXml); TableCell tc2 = new TableCell(tc.OuterXml); TableCell tc3 = new TableCell(tc.OuterXml); TableCell tc4 = new TableCell(tc.OuterXml); TableCellProperties tcPr = tc2.Descendants <TableCellProperties>().First(); tcPr.Append(new GridSpan() { Val = 3 }); // Specify the table cell content. Run run1 = new Run(tblRun.OuterXml); Run run2 = new Run(tblRun.OuterXml); Run run3 = new Run(tblRun.OuterXml); Run run4 = new Run(tblRun.OuterXml); run1.Append(new Text("操作人员:")); run2.Append(new Text("")); run3.Append(new Text("日期:")); run4.Append(new Text(DateTime.Now.ToString())); tc1.Append(new Paragraph(run1)); tc2.Append(new Paragraph(run2)); tc3.Append(new Paragraph(run3)); tc4.Append(new Paragraph(run4)); // Append the table cell to the table row. tr7.Append(tc1); tr7.Append(tc2); tr7.Append(tc3); tr7.Append(tc4); // Append the table row to the table. table.Append(tr7); } #endregion body.Append(table); #endregion #region 文档格式 SectionProperties sectPr = body.AppendChild(new SectionProperties()); sectPr.AppendChild(new PageMargin() { Top = 1134, Right = 1247, Bottom = 1134, Left = 1247, Header = 851, Footer = 992, Gutter = 0 }); #endregion } }
public static void Main1() { string fileName = @"f:\myDoc.docx"; using (WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { document.AddMainDocumentPart(); document.MainDocumentPart.Document = new Document(new Body()); HtmlConverter converter = new HtmlConverter(document.MainDocumentPart); var compositeElements = converter.Parse(Html); var p = compositeElements[0] as Paragraph; // Set Page Size and Page Margin so that we can place the image as desired. // Available Width = PageWidth - PageMarginLeft - PageMarginRight (= 17000 - 1000 - 1000 = 15000 for default values) var sectionProperties = new SectionProperties(); sectionProperties.AppendChild(new PageSize { Width = PageWidth, Height = PageHeight }); sectionProperties.AppendChild(new PageMargin { Left = PageMarginLeft, Bottom = PageMarginBottom, Top = PageMarginTop, Right = PageMarginRight }); document.MainDocumentPart.Document.Body.AppendChild(sectionProperties); if (p != null) { // Search for Extents used by the word present in Drawing > Inline > Extent var inlineEnumerable = p.ChildElements.Where(e => e is DocumentFormat.OpenXml.Wordprocessing.Run) .Where(r => r.GetFirstChild <Drawing>() != null).Select(r => r.GetFirstChild <Drawing>()) .Where(r => r.GetFirstChild <Inline>() != null).Select(r => r.GetFirstChild <Inline>()); // Update Visible Extent var inlineChildren = inlineEnumerable as Inline[] ?? inlineEnumerable.ToArray(); foreach (var inlineChild in inlineChildren) { var inlineElement = inlineChild.Extent; UpdateExtent(inlineElement); } // Search for Extents used by the word present in Drawing > Inline > Graphic > GraphicData > Picture > ShapeProperties > Transform2D > Extents var extentsEnumerable = inlineChildren .Where(r => r.GetFirstChild <Graphic>() != null).Select(d => d.GetFirstChild <Graphic>()) .Where(r => r.GetFirstChild <GraphicData>() != null).Select(r => r.GetFirstChild <GraphicData>()) .Where(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>() != null) .Select(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>()) .Where(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties>() != null) .Select(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties>()) .Where(r => r.GetFirstChild <Transform2D>() != null).Select(r => r.GetFirstChild <Transform2D>()) .Where(r => r.GetFirstChild <Extents>() != null).Select(r => r.GetFirstChild <Extents>()); // Modify all images in Extents to the desired size here, to be stretched out on available page width foreach (var extents in extentsEnumerable) { // Set Image Size: We calculate Aspect Ratio of the image and then calculate the width and update the height as per aspect ratio var inlineElement = extents; UpdateExtent(inlineElement); } } document.MainDocumentPart.Document.Body.Append(compositeElements); } }
public static byte[] GetOwnerVerification(OwnerVerificationReportModel reportModel, string name) { try { // ****************************************************** // get document template // ****************************************************** Assembly assembly = Assembly.GetExecutingAssembly(); byte[] byteArray; int ownerCount = 0; using (Stream templateStream = assembly.GetManifestResourceStream(ResourceName)) { byteArray = new byte[templateStream.Length]; templateStream.Read(byteArray, 0, byteArray.Length); templateStream.Close(); } using (MemoryStream documentStream = new MemoryStream()) { WordprocessingDocument wordDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true); // add a main document part wordDocument.AddMainDocumentPart(); using (MemoryStream templateStream = new MemoryStream()) { templateStream.Write(byteArray, 0, byteArray.Length); WordprocessingDocument wordTemplate = WordprocessingDocument.Open(templateStream, true); if (wordTemplate == null) { throw new Exception("Owner Verification template not found"); } // ****************************************************** // merge document content // ****************************************************** foreach (HetOwner owner in reportModel.Owners) { ownerCount++; using (MemoryStream ownerStream = new MemoryStream()) { WordprocessingDocument ownerDocument = (WordprocessingDocument)wordTemplate.Clone(ownerStream); ownerDocument.Save(); Dictionary <string, string> values = new Dictionary <string, string> { { "classification", owner.Classification }, { "districtAddress", reportModel.DistrictAddress }, { "districtContact", reportModel.DistrictContact }, { "organizationName", owner.OrganizationName }, { "address1", owner.Address1 }, { "address2", owner.Address2 }, { "reportDate", reportModel.ReportDate }, { "ownerCode", owner.OwnerCode }, { "sharedKeyHeader", owner.SharedKeyHeader }, { "sharedKey", owner.SharedKey }, { "workPhoneNumber", owner.PrimaryContact.WorkPhoneNumber } }; // update classification number first [ClassificationNumber] owner.Classification = owner.Classification.Replace("&", "&"); bool found = false; foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements()) { foreach (OpenXmlElement paragraphRun in paragraphs.Elements()) { foreach (OpenXmlElement text in paragraphRun.Elements()) { if (text.InnerText.Contains("ClassificationNumber")) { // replace text text.InnerXml = text.InnerXml.Replace("<w:t>ClassificationNumber</w:t>", $"<w:t xml:space='preserve'>ORCS: {owner.Classification}</w:t>"); found = true; break; } } if (found) { break; } } if (found) { break; } } ownerDocument.MainDocumentPart.Document.Save(); ownerDocument.Save(); // update merge fields MergeHelper.ConvertFieldCodes(ownerDocument.MainDocumentPart.Document); MergeHelper.MergeFieldsInElement(values, ownerDocument.MainDocumentPart.Document); ownerDocument.MainDocumentPart.Document.Save(); // setup table for equipment data Table equipmentTable = GenerateEquipmentTable(owner.HetEquipment); Paragraph tableParagraph = null; found = false; foreach (OpenXmlElement paragraphs in ownerDocument.MainDocumentPart.Document.Body.Elements()) { foreach (OpenXmlElement paragraphRun in paragraphs.Elements()) { foreach (OpenXmlElement text in paragraphRun.Elements()) { if (text.InnerText.Contains("Owner Equipment Table")) { // insert table here... text.RemoveAllChildren(); tableParagraph = (Paragraph)paragraphRun.Parent; found = true; break; } } if (found) { break; } } if (found) { break; } } // append table to document if (tableParagraph != null) { Run run = tableParagraph.AppendChild(new Run()); run.AppendChild(equipmentTable); } ownerDocument.MainDocumentPart.Document.Save(); ownerDocument.Save(); // merge owner into the master document if (ownerCount == 1) { // update document header foreach (HeaderPart headerPart in ownerDocument.MainDocumentPart.HeaderParts) { MergeHelper.ConvertFieldCodes(headerPart.Header); MergeHelper.MergeFieldsInElement(values, headerPart.Header); headerPart.Header.Save(); } wordDocument = (WordprocessingDocument)ownerDocument.Clone(documentStream); ownerDocument.Close(); ownerDocument.Dispose(); } else { // DELETE document header from owner document ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.HeaderParts); List <HeaderReference> headers = ownerDocument.MainDocumentPart.Document.Descendants <HeaderReference>().ToList(); foreach (HeaderReference header in headers) { header.Remove(); } // DELETE document footers from owner document ownerDocument.MainDocumentPart.DeleteParts(ownerDocument.MainDocumentPart.FooterParts); List <FooterReference> footers = ownerDocument.MainDocumentPart.Document.Descendants <FooterReference>().ToList(); foreach (FooterReference footer in footers) { footer.Remove(); } // DELETE section properties from owner document List <SectionProperties> properties = ownerDocument.MainDocumentPart.Document.Descendants <SectionProperties>().ToList(); foreach (SectionProperties property in properties) { property.Remove(); } ownerDocument.Save(); // insert section break in master MainDocumentPart mainPart = wordDocument.MainDocumentPart; Paragraph para = new Paragraph(); SectionProperties sectProp = new SectionProperties(); SectionType secSbType = new SectionType() { Val = SectionMarkValues.OddPage }; PageSize pageSize = new PageSize() { Width = 11900U, Height = 16840U, Orient = PageOrientationValues.Portrait }; PageMargin pageMargin = new PageMargin() { Top = 2642, Right = 23U, Bottom = 278, Left = 23U, Header = 714, Footer = 0, Gutter = 0 }; // page numbering throws out the "odd page" section breaks //PageNumberType pageNum = new PageNumberType() {Start = 1}; sectProp.AppendChild(secSbType); sectProp.AppendChild(pageSize); sectProp.AppendChild(pageMargin); //sectProp.AppendChild(pageNum); ParagraphProperties paragraphProperties = new ParagraphProperties(sectProp); para.AppendChild(paragraphProperties); mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild); mainPart.Document.Save(); // append document body string altChunkId = $"AltChunkId{ownerCount}"; AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); ownerDocument.Close(); ownerDocument.Dispose(); ownerStream.Seek(0, SeekOrigin.Begin); chunk.FeedData(ownerStream); AltChunk altChunk = new AltChunk { Id = altChunkId }; Paragraph para3 = new Paragraph(); Run run3 = para3.InsertAfter(new Run(), para3.LastChild); run3.AppendChild(altChunk); mainPart.Document.Body.InsertAfter(para3, mainPart.Document.Body.LastChild); mainPart.Document.Save(); } } } wordTemplate.Close(); wordTemplate.Dispose(); templateStream.Close(); } // ****************************************************** // secure & return completed document // ****************************************************** wordDocument.CompressionOption = CompressionOption.Maximum; SecurityHelper.PasswordProtect(wordDocument); wordDocument.Close(); wordDocument.Dispose(); documentStream.Seek(0, SeekOrigin.Begin); byteArray = documentStream.ToArray(); } return(byteArray); } catch (Exception e) { Console.WriteLine(e); throw; } }
static void Main() { string fileName = @"f:\myDoc.docx"; using (WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { document.AddMainDocumentPart(); document.MainDocumentPart.Document = new Document(new Body()); HtmlConverter conveter = new HtmlConverter(document.MainDocumentPart); var compositeElements = conveter.Parse(Html); var p = compositeElements[0] as Paragraph; // Set Page Size and Page Margin so that we can place the image as desired. // Available Width = PageWidth - PageMarginLeft - PageMarginRight (= 17000 - 1000 - 1000 = 15000 for default values) var sectionProperties = new SectionProperties(); sectionProperties.AppendChild(new PageSize { Width = PageWidth, Height = PageHeight }); sectionProperties.AppendChild(new PageMargin { Left = PageMarginLeft, Bottom = PageMarginBottom, Top = PageMarginTop, Right = PageMarginRight }); document.MainDocumentPart.Document.Body.AppendChild(sectionProperties); if (p != null) { // Search for Extents used by the word present in Drawing > Inine > Graphic > GraphicData > Picture > ShapeProperties > Transform2D > Extents var extentsEnumerable = p.ChildElements.Where(e => e is DocumentFormat.OpenXml.Wordprocessing.Run) .Where(r => r.GetFirstChild <Drawing>() != null).Select(r => r.GetFirstChild <Drawing>()) .Where(r => r.GetFirstChild <Inline>() != null).Select(r => r.GetFirstChild <Inline>()) .Where(r => r.GetFirstChild <Graphic>() != null).Select(d => d.GetFirstChild <Graphic>()) .Where(r => r.GetFirstChild <GraphicData>() != null).Select(r => r.GetFirstChild <GraphicData>()) .Where(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>() != null) .Select(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>()) .Where(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties>() != null) .Select(r => r.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties>()) .Where(r => r.GetFirstChild <Transform2D>() != null).Select(r => r.GetFirstChild <Transform2D>()) .Where(r => r.GetFirstChild <Extents>() != null).Select(r => r.GetFirstChild <Extents>()); // Modify all images in Extents to the desired size here, to be stretched out on available page width foreach (var extents in extentsEnumerable) { // Set Image Size: We calculate Aspect Ratio of the image and then calculate the width and update the height as per aspect ratio var inlineElement = extents; // Read Default Cx and Cy Values provided in Emu var extentCx = inlineElement.Cx; var extentCy = inlineElement.Cy; // Aspect ratio used to set image height after calculation of width double aspectRatioOfImage = (double)extentCy / extentCx; // We know 15 width of Page = 1 width of image in pixel = 9525 EMUs per pixel, and we convert document size to pixel and then to EMU // For Default Values Avalable page width = 15000 page width = 15000/ 15 pixels = 1000 pixels = 1000 * 9525 Emu = 9525000 Emu double newExtentCx = EmuPerPixel * ((PageWidth - PageMarginLeft - PageMarginRight) / DocumentSizePerPixel); // Maintain the Aspect Ratio for height double newExtentCy = aspectRatioOfImage * newExtentCx; // Update the values inlineElement.Cx = (long)Math.Round(newExtentCx); inlineElement.Cy = (long)Math.Round(newExtentCy); } } document.MainDocumentPart.Document.Body.Append(compositeElements); } }