public static void InsertText(String text, String styleXml, OpenXmlElement parentNode) { // Разделить строку на подстроки //String[] runs = macroVarValue.Split(new char[] { '\r', '\n' }); //String[] runs = Regex.Split(macroVarValue, "\r\n|\r|\n"); String[] runs = Regex.Split(text, "\r\n"); // Вставить текст foreach (String run in runs) { // Создать новый Paragraph Paragraph newParagraph = parentNode.AppendChild(new Paragraph()); // Вернуть старый стиль в Paragraph ParagraphProperties newParagraphProperties = newParagraph.AppendChild(new ParagraphProperties()); newParagraphProperties.InnerXml = styleXml; // Создать новый Run Run newRun = newParagraph.AppendChild(new Run()); // Вернуть старый стиль в Run RunProperties newRunProperties = newRun.AppendChild(new RunProperties()); newRunProperties.InnerXml = styleXml; // Вставить в него текст newRun.AppendChild(new Text(run)); } }
public static void SetIndent(ParagraphProperties pp, int?leftChars, FirstLineOrHangingChars firstLineOrhangingChars) { var indent = new Indentation(); if (leftChars != null) { indent.LeftChars = leftChars.Value; } if (firstLineOrhangingChars != null) { switch (firstLineOrhangingChars.Floh) { case FirstLineOrHanging.FirstLine: indent.FirstLineChars = firstLineOrhangingChars.Chars; break; case FirstLineOrHanging.Hanging: indent.HangingChars = firstLineOrhangingChars.Chars; break; default: throw new InvalidEnumArgumentException(firstLineOrhangingChars.Floh.ToString()); } } OpenXmlElementHelper.SetChild(pp, indent); }
public Paragraph CreateParagraph(ParaProperties properties) { ParagraphProperties paraProp = new ParagraphProperties(); if (properties.StyleName != null) { paraProp.Append(new ParagraphStyleId() { Val = properties.StyleName }); } if (properties.Alignment != JustificationValues.Left) { paraProp.Append(new Justification() { Val = properties.Alignment }); } Indentation ind = new Indentation(); if (properties.FirstLineIndent == 0) { ind.FirstLine = (properties.FirstLineIndent * 567).ToString("n0").Replace(",", ""); } if (properties.LeftIndent == 0) { ind.FirstLine = (properties.LeftIndent * 567).ToString("n0").Replace(",", ""); } if (properties.RightIndent == 0) { ind.FirstLine = (properties.RightIndent * 567).ToString("n0").Replace(",", ""); } var para = CreateParagraph(); para.Append(paraProp); return(para); }
public Word.Paragraph GenerateParagraph(string val, bool bold = false, string sz = "12", string s = "style22", string f = "Courier New", Word.JustificationValues align = Word.JustificationValues.Left) { Word.ParagraphStyleId pstyle = new Word.ParagraphStyleId { Val = s }; Word.Justification jut = new Word.Justification { Val = new EnumValue <Word.JustificationValues>(align) }; Word.ParagraphProperties pprop = new Word.ParagraphProperties(pstyle, jut); Word.RunProperties rprop = new Word.RunProperties( new Word.RunFonts { Ascii = f, ComplexScript = f, HighAnsi = f }, new Word.Bold { Val = new OnOffValue(bold) }, new Word.BoldComplexScript { Val = new OnOffValue(bold) }, new Word.FontSize { Val = sz }); Word.Text text = new Word.Text(val); Word.Run run = new Word.Run(rprop, text); return(new Word.Paragraph(pprop, run)); }
/**public void getFooterWithPageNumber() * { * foreach (Section wordSection in this.adoc.Sections) * { * Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; * footerRange.InlineShapes.AddHorizontalLineStandard(); * footerRange.Font.ColorIndex = WdColorIndex.wdDarkRed; * footerRange.Font.Size = 10; * footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; * adoc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(); * } * }**/ public void generateCoverPage(string data) { body.Append(new Paragraph(new Run(new Break()))); body.Append(new Paragraph(new Run(new Break()))); body.Append(new Paragraph(new Run(new Break()))); body.Append(new Paragraph(new Run(new Break()))); //heading Paragraph heading = new Paragraph(); ParagraphProperties hp = new ParagraphProperties(); hp.Justification = new Justification() { Val = JustificationValues.Center }; heading.Append(hp); Run r = new Run(); RunProperties runProperties = r.AppendChild(new RunProperties()); Bold bold = new Bold(); bold.Val = OnOffValue.FromBoolean(true); FontSize size = new FontSize(); size.Val = "60"; runProperties.AppendChild(bold); runProperties.AppendChild(size); Text t = new Text(data); r.Append(t); heading.Append(r); body.Append(heading); //subheading Paragraph subheading = new Paragraph(); ParagraphProperties shp = new ParagraphProperties(); shp.Justification = new Justification() { Val = JustificationValues.Center }; subheading.Append(shp); Run rs = new Run(); RunProperties rhProperties = rs.AppendChild(new RunProperties()); Bold bs = new Bold(); bs.Val = OnOffValue.FromBoolean(true); FontSize sh = new FontSize(); sh.Val = "40"; rhProperties.AppendChild(bs); rhProperties.AppendChild(sh); Text subhead = new Text("BUSINESS PLAN"); rs.Append(subhead); subheading.Append(rs); body.Append(subheading); addPageBreak(); }
public static WP.Paragraph CenterBigTextParagraph(string text) { var pp = new WP.ParagraphProperties(new WP.Justification { Val = WP.JustificationValues.Center }); var rp = new WP.RunProperties(new WP.FontSize() { Val = "32" }, new WP.Bold()); return(new WP.Paragraph(pp, new WP.Run(rp, new WP.Text(text)))); }
public Paragraph(uint leftIntendation = 0, uint rightIntendation = 0, JUSTIFICATION justification = JUSTIFICATION.NONE) { _Paragraph = new Wp.Paragraph() { RsidParagraphMarkRevision = "00297913", RsidParagraphAddition = "00297913", RsidParagraphProperties = "00297913", RsidRunAdditionDefault = "0074062A", ParagraphId = "29551F12", TextId = "11181D94" }; Wp.ParagraphProperties _pp = new Wp.ParagraphProperties(); Wp.Indentation _i = new Wp.Indentation() { Left = leftIntendation.ToString(), Right = rightIntendation.ToString() }; _pp.Append(_i); if (justification.Equals(JUSTIFICATION.NONE) is false) { Wp.Justification _j; if (justification.Equals(JUSTIFICATION.CENTER) is true) { _j = new Wp.Justification() { Val = Wp.JustificationValues.Center } } ; else if (justification.Equals(JUSTIFICATION.LEFT) is true) { _j = new Wp.Justification() { Val = Wp.JustificationValues.Left } } ; else { _j = new Wp.Justification() { Val = Wp.JustificationValues.Right } }; _pp.Append(_j); } _Paragraph.Append(_pp); }
public static void SetParagraphProperties(ParagraphProperties p, int?leftChars, FirstLineOrHangingChars firstLineOrhangingChars, int?spaceBetweenLines, JustificationValues?jv) { var oxes = new List <OpenXmlElement>(); if (leftChars != null || firstLineOrhangingChars != null) { var indent = new Indentation(); if (leftChars != null) { indent.LeftChars = leftChars.Value; } if (firstLineOrhangingChars != null) { switch (firstLineOrhangingChars.Floh) { case FirstLineOrHanging.FirstLine: indent.FirstLineChars = firstLineOrhangingChars.Chars; break; case FirstLineOrHanging.Hanging: indent.HangingChars = firstLineOrhangingChars.Chars; break; default: throw new InvalidEnumArgumentException(firstLineOrhangingChars.Floh.ToString()); } } oxes.Add(indent); } if (spaceBetweenLines.HasValue) { oxes.Add(new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Auto, Line = spaceBetweenLines.Value.ToString() }); } if (jv.HasValue) { oxes.Add(new Justification { Val = jv }); } OpenXmlElementHelper.SetChild(p, new ParagraphProperties(oxes)); }
private void SetParagraphProperties(ParagraphProperties paragraphProperties) { if (paragraphProperties == null) { return; } if (paragraphProperties.ParagraphStyleId != null) { SetParagraphByStyles(_documentContext.Styles[paragraphProperties.ParagraphStyleId.Val]); } if (paragraphProperties.Indentation != null) { _pdfParagraph.Format.LeftIndent = GetPdfUnitLength(Convert.ToInt32(paragraphProperties.Indentation.Left.Value)); } }
/// <summary> /// Append SubDocument at end of current doc /// </summary> /// <param name="content"></param> /// <param name="withPageBreak">If true insert a page break before.</param> public void AppendSubDocument(Stream content, bool withPageBreak) { if (wdDoc == null) { throw new InvalidOperationException("Document not loaded"); } AlternativeFormatImportPart formatImportPart = wdMainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML); formatImportPart.FeedData(content); AltChunk altChunk = new AltChunk(); altChunk.Id = wdMainDocumentPart.GetIdOfPart(formatImportPart); OpenXmlElement lastElement = wdMainDocumentPart.Document.Body.LastChild; if (lastElement is SectionProperties) { lastElement.InsertBeforeSelf(altChunk); if (withPageBreak) { SectionProperties sectionProps = (SectionProperties)lastElement.Clone(); var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); var ppr = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties(); p.AppendChild(ppr); ppr.AppendChild(sectionProps); altChunk.InsertBeforeSelf(p); } } else { lastElement.InsertAfterSelf(altChunk); if (withPageBreak) { Paragraph p = new Paragraph( new Run( new Break() { Type = BreakValues.Page })); altChunk.InsertBeforeSelf(p); } } }
public Paragraph CreateNonBodyParagraph(JustificationValues alignment) { if (alignment == JustificationValues.Left) { return(CreateNonBodyParagraph()); } ParagraphProperties paraProp = new ParagraphProperties(); paraProp.Append(new Justification() { Val = alignment }); var para = CreateNonBodyParagraph(); para.Append(paraProp); return(para); }
public Paragraph CreateParagraph(string paragraphStyleName) { if (string.IsNullOrEmpty(paragraphStyleName)) { return(CreateParagraph()); } ParagraphProperties paraProp = new ParagraphProperties(); paraProp.Append(new ParagraphStyleId() { Val = paragraphStyleName }); var para = new Paragraph(); para.Append(paraProp); _body.Append(para); return(para); }
public static Wordprocessing.TableCell AddCell(this Wordprocessing.TableRow tableRow, string value) { Wordprocessing.TableCell tableCell = new Wordprocessing.TableCell(); Wordprocessing.Paragraph par = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties parprop = new Wordprocessing.ParagraphProperties(); Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0"}; parprop.Append(spacingBetweenLines2); parprop.Append(justification1); par.Append(parprop); Wordprocessing.Run run = new Wordprocessing.Run() ; Wordprocessing.Text text = new Wordprocessing.Text(value); run.Append(text); par.Append(run); tableCell.Append(par); tableRow.Append(tableCell); return tableCell; }
/// <summary> /// The create paragraph. /// </summary> /// <param name="content">The content.</param> /// <param name="styleId">The style id.</param> /// <returns>The paragraph.</returns> private static DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateParagraph(string content, string styleId = null) { var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); if (styleId != null) { var pp = new ParagraphProperties { ParagraphStyleId = new ParagraphStyleId { Val = styleId } }; p.AppendChild(pp); } var text = new Text(content); var run = new Run(text); p.AppendChild(run); return(p); }
private Paragraph ExamTitleHeader() { var paragraphWithExamTitle = new Paragraph(); var run = new Run(); var paragraphProperties = new ParagraphProperties(); var justification = new Justification() { Val = JustificationValues.Center }; paragraphProperties.Append(justification); run.Append(new Text($"Exam: {exam.Subject}")); run.Append(new Break()); run.Append(new Text($"Teacher: {exam.Teacher}")); paragraphWithExamTitle.Append(paragraphProperties); paragraphWithExamTitle.Append(run); return(paragraphWithExamTitle); }
public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedSection(MultiColumnSection section) { List<DocumentFormat.OpenXml.OpenXmlElement> formattedSection = new List<DocumentFormat.OpenXml.OpenXmlElement>(); Element[] elements = section.SubElements; foreach (var element in elements) { formattedSection.AddRange(ElementFactory.GetElement(element)); } Word.Columns cols = new Word.Columns() { ColumnCount = (Int16Value)section.NumberOfColumns }; Word.SectionProperties secProps = new Word.SectionProperties(cols); Word.ParagraphProperties paraProp = new Word.ParagraphProperties(secProps); Word.Paragraph para = new Word.Paragraph(paraProp); formattedSection.Add(para); return formattedSection.ToArray(); }
public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedSection(Section section) { List<DocumentFormat.OpenXml.OpenXmlElement> formattedSection = new List<DocumentFormat.OpenXml.OpenXmlElement>(); Element[] elements = section.SubElements; foreach (var element in elements) { if (section.CanContain(element.GetElementType())) formattedSection.AddRange(ElementFactory.GetElement(element)); else throw new InvalidSubFeatureException( section.GetElementType().ToString(), element.GetElementType().ToString() ); } Word.Columns cols = new Word.Columns() { ColumnCount = (Int16Value)1 }; Word.SectionProperties secProps = new Word.SectionProperties(cols); Word.ParagraphProperties paraProp = new Word.ParagraphProperties(secProps); Word.Paragraph para = new Word.Paragraph(paraProp); formattedSection.Add(para); return formattedSection.ToArray(); }
/// <summary> /// The create paragraph. /// </summary> /// <param name="content"> /// The content. /// </param> /// <param name="styleID"> /// The style id. /// </param> /// <returns> /// </returns> private static DocumentFormat.OpenXml.Wordprocessing.Paragraph CreateParagraph( string content, string styleID = null) { var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); if (styleID != null) { var pp = new ParagraphProperties { ParagraphStyleId = new ParagraphStyleId { Val = styleID } }; p.Append(pp); } var text = new Text(content); var run = new Run(text); p.Append(run); return p; }
public static void Fill(OpenXmlElement docNode, XmlElement macroListXml, WordprocessingDocument wdDoc) { /* Форматированный текст для встроенных элементов */ IEnumerable <Paragraph> paragraphs = docNode.Elements <Paragraph>(); foreach (Paragraph paragraph in paragraphs) { IEnumerable <SdtRun> sdtRuns = paragraph.Elements <SdtRun>(); foreach (SdtRun sdtRun in sdtRuns) { // Из SdtProperties взять Tag для идентификации Content Control SdtProperties sdtProperties = sdtRun.GetFirstChild <SdtProperties>(); Tag tag = sdtProperties.GetFirstChild <Tag>(); // Найти в macroListXml Node макропеременной String macroVarValue = FindMacroVar(macroListXml, tag.Val); if (macroVarValue != null) { // Сохранить старый стиль Run SdtContentRun sdtContentRun = sdtRun.GetFirstChild <SdtContentRun>(); OpenXmlElement oldRunProps = sdtContentRun.GetFirstChild <Run>().GetFirstChild <RunProperties>().CloneNode(true); // Очистить Node Content Control sdtContentRun.RemoveAllChildren(); // Создать новую Run Node Run newRun = sdtContentRun.AppendChild(new Run()); // Вернуть старый стиль newRun.AppendChild(oldRunProps); // Вставить текст (без переносов строк!!!) newRun.AppendChild(new Text(macroVarValue)); } } } /* Получить остальные Content Control */ IEnumerable <SdtBlock> sdtBlocks = docNode.Elements <SdtBlock>(); foreach (SdtBlock sdtBlock in sdtBlocks) { // Получить параметры(SdtProperties) Content Control SdtProperties sdtProperties = sdtBlock.GetFirstChild <SdtProperties>(); // Получить Tag для идентификации Content Control Tag tag = sdtProperties.GetFirstChild <Tag>(); // Получить значение макроперенной из macroListXml Console.WriteLine("Tag: " + tag.Val); String macroVarValue = FindMacroVar(macroListXml, tag.Val); // Если макропеременная есть в MacroListXml if (macroVarValue != null) { Console.WriteLine("Value: " + macroVarValue); // Получить блок содержимого Content Control SdtContentBlock sdtContentBlock = sdtBlock.GetFirstChild <SdtContentBlock>(); /* Форматированный текст для абзацев */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Paragraph>() != null) { // Сохранить старый стиль параграфа ParagraphProperties oldParagraphProperties = sdtContentBlock.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().CloneNode(true) as ParagraphProperties; String oldParagraphPropertiesXml = oldParagraphProperties.InnerXml; // Очистить ноду с контентом sdtContentBlock.RemoveAllChildren(); InsertText(macroVarValue, oldParagraphPropertiesXml, sdtContentBlock); } /* Таблицы */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Table>() != null) { // Получить ноду таблицы Table table = sdtContentBlock.GetFirstChild <Table>(); // Получить все строки таблицы IEnumerable <TableRow> tableRows = table.Elements <TableRow>(); // Получить вторую строку из таблицы TableRow tableRow = tableRows.ElementAt(1) as TableRow; Type tableRowType = tableRow.GetType(); // Получить все стили столбцов List <String> paragraphCellStyles = new List <string>(); IEnumerable <OpenXmlElement> tableCells = tableRow.Elements <TableCell>(); foreach (OpenXmlElement tableCell in tableCells) { String paragraphCellStyleXml = tableCell.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().InnerXml; paragraphCellStyles.Add(paragraphCellStyleXml); } // Удалить все строки, после первой while (tableRows.Count <TableRow>() > 1) { TableRow lastTableRows = tableRows.Last <TableRow>(); lastTableRows.Remove(); } // Удалить последний элемент, если это не TableRow OpenXmlElement lastNode = table.LastChild; if (lastNode.GetType() != tableRowType) { lastNode.Remove(); } string[] rowDelimiters = new string[] { "|||" }; string[] columnDelimiters = new string[] { "^^^" }; // Получить массив строк из макропеременной String[] rowsXml = macroVarValue.Split(rowDelimiters, StringSplitOptions.None); int i = 0; while (i < rowsXml.Length) { // Получить строку String rowXml = rowsXml[i]; // Добавить ноду строки таблицы TableRow newTableRow = table.AppendChild(new TableRow()); // Получить из строки массив ячеек String[] cellsXml = rowXml.Split(columnDelimiters, StringSplitOptions.None); int j = 0; while (j < cellsXml.Length) { // Получить ячейку String cellXml = cellsXml[j]; // Убрать символ CRLF в конце строки cellXml = cellXml.TrimEnd(new char[] { '\n', '\r' }); // Добавить ноду ячейку в строку таблицы TableCell newTableCell = newTableRow.AppendChild(new TableCell()); // Вставить текст InsertText(cellXml, paragraphCellStyles[j], newTableCell); j++; } i++; } } /* Картинки */ if (sdtProperties.GetFirstChild <SdtContentPicture>() != null) { // Получить путь к файлу String imageFilePath = macroVarValue; // Получить расширение файла String extension = System.IO.Path.GetExtension(imageFilePath).ToLower(); ImagePartType imagePartType; switch (extension) { case "jpeg": imagePartType = ImagePartType.Jpeg; break; case "jpg": imagePartType = ImagePartType.Jpeg; break; case "png": imagePartType = ImagePartType.Png; break; case "bmp": imagePartType = ImagePartType.Bmp; break; case "gif": imagePartType = ImagePartType.Gif; break; default: imagePartType = ImagePartType.Jpeg; break; } ; // Добавить ImagePart в документ ImagePart imagePart = wdDoc.MainDocumentPart.AddImagePart(imagePartType); // Получить картинку using (FileStream stream = new FileStream(imageFilePath, FileMode.Open)) { imagePart.FeedData(stream); } // Вычислить width и height Bitmap img = new Bitmap(imageFilePath); var widthPx = img.Width; var heightPx = img.Height; var horzRezDpi = img.HorizontalResolution; var vertRezDpi = img.VerticalResolution; const int emusPerInch = 914400; const int emusPerCm = 360000; var widthEmus = (long)(widthPx / horzRezDpi * emusPerInch); var heightEmus = (long)(heightPx / vertRezDpi * emusPerInch); // Получить ID ImagePart string relationShipId = wdDoc.MainDocumentPart.GetIdOfPart(imagePart); Paragraph paragraph = sdtContentBlock.GetFirstChild <Paragraph>(); Run run = paragraph.GetFirstChild <Run>(); Drawing drawing = run.GetFirstChild <Drawing>(); Inline inline = drawing.GetFirstChild <Inline>(); Graphic graphic = inline.GetFirstChild <Graphic>(); GraphicData graphicData = graphic.GetFirstChild <GraphicData>(); Picture pic = graphicData.GetFirstChild <Picture>(); BlipFill blipFill = pic.GetFirstChild <BlipFill>(); Blip blip = blipFill.GetFirstChild <Blip>(); string prefix = "r"; string localName = "embed"; string namespaceUri = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; OpenXmlAttribute oldEmbedAttribute = blip.GetAttribute("embed", namespaceUri); IList <OpenXmlAttribute> attributes = blip.GetAttributes(); if (oldEmbedAttribute != null) { attributes.Remove(oldEmbedAttribute); } // Удалить хз что, выявлено практическим путем blipFill.RemoveAllChildren <SourceRectangle>(); // Установить новую картинку blip.SetAttribute(new OpenXmlAttribute(prefix, localName, namespaceUri, relationShipId)); blip.SetAttribute(new OpenXmlAttribute("cstate", "", "print")); // Подогнать размеры Extent extent = inline.GetFirstChild <Extent>(); OpenXmlAttribute oldCxExtent = extent.GetAttribute("cx", ""); if (oldCxExtent != null) { var maxWidthEmus = long.Parse(oldCxExtent.Value); if (widthEmus > maxWidthEmus) { var ratio = (heightEmus * 1.0m) / widthEmus; widthEmus = maxWidthEmus; heightEmus = (long)(widthEmus * ratio); } extent.GetAttributes().Remove(oldCxExtent); } OpenXmlAttribute oldCyExtent = extent.GetAttribute("cy", ""); if (oldCyExtent != null) { extent.GetAttributes().Remove(oldCyExtent); } extent.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extent.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); ShapeProperties shapeProperties = pic.GetFirstChild <ShapeProperties>(); Transform2D transform2D = shapeProperties.GetFirstChild <Transform2D>(); Extents extents = transform2D.GetFirstChild <Extents>(); OpenXmlAttribute oldCxExtents = extents.GetAttribute("cx", ""); if (oldCxExtents != null) { extents.GetAttributes().Remove(oldCxExtents); } OpenXmlAttribute oldCyExtents = extents.GetAttribute("cy", ""); if (oldCyExtents != null) { extents.GetAttributes().Remove(oldCyExtents); } extents.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extents.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); // Удалить placeholder ShowingPlaceholder showingPlaceholder = sdtProperties.GetFirstChild <ShowingPlaceholder>(); if (showingPlaceholder != null) { sdtProperties.RemoveChild <ShowingPlaceholder>(showingPlaceholder); } } /* Повторяющийся раздел */ if (sdtProperties.GetFirstChild <SdtRepeatedSection>() != null) { // Представить repeatedSection как новый xml документ (сделать корнем) XmlDocument repeatedSectionXml = new XmlDocument(); repeatedSectionXml.LoadXml(macroVarValue); // Получить корневой элемент repeatedSection XmlElement rootRepeatedSectionXml = repeatedSectionXml.DocumentElement; // Получить количество repeatedSectionItem XmlNodeList repeatedSectionItems = rootRepeatedSectionXml.SelectNodes("repeatedSectionItem"); int repeatedItemCount = repeatedSectionItems.Count; Console.WriteLine("Количество repeatedSectionItem: " + repeatedItemCount); /* Блок клонирования ноды повтор. раздела до нужного количества */ for (int i = 0; i < repeatedItemCount; i++) { XmlElement macroListRepeatedSectionItem = rootRepeatedSectionXml.SelectSingleNode(String.Format(@"repeatedSectionItem[@id=""{0}""]", i)) as XmlElement; Console.WriteLine("Item " + i + ": " + macroListRepeatedSectionItem.OuterXml); SdtContentBlock sdtContentBlockRepeatedSectionItem = sdtContentBlock.Elements <SdtBlock>().Last <SdtBlock>().GetFirstChild <SdtContentBlock>(); Fill(sdtContentBlockRepeatedSectionItem, macroListRepeatedSectionItem, wdDoc); if (i + 1 < repeatedItemCount) { SdtBlock clonedRepeatedSectionItem = sdtContentBlock.GetFirstChild <SdtBlock>().Clone() as SdtBlock; sdtContentBlock.AppendChild <SdtBlock>(clonedRepeatedSectionItem); } } /**/ //Fill(sdtContentBlock, macroListRepeatedSection, wdDoc); } } Console.WriteLine(); } }
/// <summary> /// Get paragraph's numbering level object by searching abstractNums with the numbering level ID. /// </summary> /// <param name="pg"></param> /// <returns></returns> public Word.Level GetNumbering(Word.Paragraph pg) { Word.Level ret = null; if (pg == null || this.numbering == null) { return(ret); } Word.ParagraphProperties pgpr = pg.Elements <Word.ParagraphProperties>().FirstOrDefault(); if (pgpr == null) { return(ret); } // direct numbering Word.NumberingProperties numPr = pgpr.Elements <Word.NumberingProperties>().FirstOrDefault(); if (numPr != null && numPr.NumberingId != null) { int numId = numPr.NumberingId.Val; if (numId > 0) // numId == 0 means this paragraph doesn't have a list item { int? ilvl = null; String refStyleName = null; if (numPr.NumberingLevelReference != null) { // ilvl included in NumberingProperties ilvl = numPr.NumberingLevelReference.Val; } else { // doesn't have ilvl in NumberingProperties, search by referenced style name Word.Style st = pgpr.Elements <Word.Style>().FirstOrDefault(); if (st != null && st.StyleName != null) { refStyleName = st.StyleName.Val; } } // find abstractNumId by numId Word.NumberingInstance numInstance = this.numbering.Elements <Word.NumberingInstance>().FirstOrDefault(c => c.NumberID.Value == numId); if (numInstance != null) { // find abstractNum by abstractNumId Word.AbstractNum abstractNum = (Word.AbstractNum) this.numbering.Elements <Word.AbstractNum>().FirstOrDefault(c => c.AbstractNumberId.Value == numInstance.AbstractNumId.Val); if (abstractNum != null) { if (ilvl != null) // search by ilvl { ret = abstractNum.Elements <Word.Level>().FirstOrDefault(c => c.LevelIndex == ilvl); } else if (refStyleName != null) // search by matching referenced style name { ret = abstractNum.Elements <Word.Level>().FirstOrDefault(c => { return((c.ParagraphStyleIdInLevel != null) ? c.ParagraphStyleIdInLevel.Val == refStyleName : false); }); } } } } } // TODO: linked style if (ret == null) { ; } return(ret); }
/// <summary> /// Get the nearest applied element (e.g. RunFonts, Languages) in the style hierachy. It searches upstream from current $obj til reach the top of the hierachy if no found. /// </summary> /// <typeparam name="T">Target element type (e.g. RunFonts.GetType()).</typeparam> /// <param name="obj">The OpenXmlElemet to search from.</param> /// <returns>Return found element or null if not found.</returns> public T GetAppliedElement <T>(OpenXmlElement obj) { T ret = default(T); if (obj == null) { return(ret); } Type objType = obj.GetType(); if (objType == typeof(Word.Run)) { // Run.RunProperties > Run.RunProperties.rStyle > Paragraph.ParagraphProperties.pStyle (> default style > docDefaults) // ( ): done in paragraph level Word.RunProperties runpr = StyleHelper.GetElement <Word.RunProperties>(obj); if (runpr != null) { ret = StyleHelper.GetDescendants <T>(runpr); // If has rStyle, go through rStyle before go on. // Use getAppliedStyleElement() is because it will go over all the basedOn styles. if (ret == null && runpr.RunStyle != null) { ret = this.GetAppliedElement <T>(this.GetStyleById(runpr.RunStyle.Val)); } } if (ret == null) { // parent paragraph's pStyle if (obj.Parent != null && obj.Parent.GetType() == typeof(Word.Paragraph)) { Word.Paragraph pg = obj.Parent as Word.Paragraph; if (pg.ParagraphProperties != null && pg.ParagraphProperties.ParagraphStyleId != null) { ret = this.GetAppliedElement <T>(this.GetStyleById(pg.ParagraphProperties.ParagraphStyleId.Val)); } } } if (ret == null) // default run style { ret = this.GetAppliedElement <T>(this.GetDefaultStyle(DefaultStyleType.Character)); } if (ret == null) // docDefaults { ret = StyleHelper.GetDescendants <T>(this.docDefaults.RunPropertiesDefault); } } else if (objType == typeof(Word.Paragraph)) { // Paragraph.ParagraphProperties > Paragraph.ParagraphProperties.pStyle > default style > docDefaults Word.ParagraphProperties pgpr = StyleHelper.GetElement <Word.ParagraphProperties>(obj); if (pgpr != null) { ret = StyleHelper.GetDescendants <T>(pgpr); // If has pStyle, go through pStyle before go on. // Use getAppliedStyleElement() is because it will go over the whole Style hierachy. if (ret == null && pgpr.ParagraphStyleId != null) { ret = this.GetAppliedElement <T>(this.GetStyleById(pgpr.ParagraphStyleId.Val)); } } if (ret == null) { if (obj.Parent != null && obj.Parent.GetType() == typeof(Word.TableCell)) { for (int i = 0; i < 3 && obj != null; i++) { obj = (obj.Parent != null) ? obj.Parent : null; } if (obj != null && obj.GetType() == typeof(Word.Table)) { ret = this.GetAppliedElement <T>(obj); } } } if (ret == null) // default paragraph style { ret = this.GetAppliedElement <T>(this.GetDefaultStyle(DefaultStyleType.Paragraph)); } if (ret == null) // docDefaults { ret = StyleHelper.GetDescendants <T>(this.docDefaults); } } else if (objType == typeof(Word.Table)) { // Table.TableProperties > Table.TableProperties.tblStyle > default style Word.TableProperties tblpr = StyleHelper.GetElement <Word.TableProperties>(obj); if (tblpr != null) { ret = StyleHelper.GetDescendants <T>(tblpr); // If has tblStyle, go through tblStyle before go on. // Use getAppliedStyleElement() is because it will go over the whole Style hierachy. if (ret == null && tblpr.TableStyle != null) { ret = this.GetAppliedElement <T>(this.GetStyleById(tblpr.TableStyle.Val)); } } if (ret == null) // default table style { ret = this.GetAppliedElement <T>(this.GetDefaultStyle(DefaultStyleType.Table)); } } else if (objType == typeof(Word.TableRow)) { // TableRow.TableRowProperties > Table.TableProperties.tblStyle (> default style) // ( ): done in Table level Word.TableRowProperties rowpr = StyleHelper.GetElement <Word.TableRowProperties>(obj); if (rowpr != null) { ret = StyleHelper.GetDescendants <T>(rowpr); } if (ret == null) { for (int i = 0; i < 1 && obj != null; i++) { obj = (obj.Parent != null) ? obj.Parent : null; } if (obj != null && obj.GetType() == typeof(Word.Table)) { ret = this.GetAppliedElement <T>(obj); } } } else if (objType == typeof(Word.TableCell)) { // TableCell.TableCellProperties > Table.TableProperties.tblStyle (> default style) // ( ): done in Table level Word.TableCellProperties cellpr = StyleHelper.GetElement <Word.TableCellProperties>(obj); if (cellpr != null) { ret = StyleHelper.GetDescendants <T>(cellpr); } if (ret == null) { for (int i = 0; i < 2 && obj != null; i++) { obj = (obj.Parent != null) ? obj.Parent : null; } if (obj != null && obj.GetType() == typeof(Word.Table)) { ret = this.GetAppliedElement <T>(obj); } } } else if (objType == typeof(Word.Style)) { Word.Style st = obj as Word.Style; ret = StyleHelper.GetDescendants <T>(st); if (ret == null) { if (st.BasedOn != null) { ret = this.GetAppliedElement <T>(this.GetStyleById(st.BasedOn.Val)); } } } else // unknown type, just get everything can get { ret = StyleHelper.GetDescendants <T>(obj); } return(ret); }
public Wordprocessing.Body insertinform() { Wordprocessing.Body body = new Wordprocessing.Body(); //Параграф1 Wordprocessing.Paragraph paragraph1 = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties paragraphProperties1 = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines1 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; paragraphProperties1.Append(spacingBetweenLines1); paragraphProperties1.Append(justification1); Wordprocessing.Run run1 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties1 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts2 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.Bold bold2 = new Wordprocessing.Bold(); Wordprocessing.FontSize fontSize2 = new Wordprocessing.FontSize() { Val = "24" }; runProperties1.Append(runFonts2); runProperties1.Append(bold2); runProperties1.Append(fontSize2); Wordprocessing.Text text1 = new Wordprocessing.Text(); text1.Text = "ФГБОУВПО \"ПЕРМСКИЙ ГОСУДАРСТВЕННЫЙ НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ УНИВЕРСИТЕТ\""; run1.Append(runProperties1); run1.Append(text1); paragraph1.Append(paragraphProperties1); paragraph1.Append(run1); //Параграф2 Wordprocessing.Paragraph paragraph2 = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties paragraphProperties2 = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; Wordprocessing.Justification justification2 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; paragraphProperties2.Append(spacingBetweenLines2); paragraphProperties2.Append(justification2); Wordprocessing.Run run2 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties2 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts4 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.FontSize fontSize4 = new Wordprocessing.FontSize() { Val = "24" }; runProperties2.Append(runFonts4); runProperties2.Append(fontSize4); Wordprocessing.Text text2 = new Wordprocessing.Text(); text2.Text = "Механико-математический факультет "; run2.Append(runProperties2); run2.Append(text2); Wordprocessing.Run run3 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties3 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts5 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.FontSize fontSize5 = new Wordprocessing.FontSize() { Val = "24" }; runProperties3.Append(runFonts5); runProperties3.Append(fontSize5); Wordprocessing.Break break1 = new Wordprocessing.Break(); Wordprocessing.Text text3 = new Wordprocessing.Text(); text3.Text = "очная форма обучения"; run3.Append(runProperties3); run3.Append(break1); run3.Append(text3); paragraph2.Append(paragraphProperties2); paragraph2.Append(run2); paragraph2.Append(run3); //Параграф2 Wordprocessing.Paragraph paragraph3 = new Wordprocessing.Paragraph() { RsidParagraphAddition = "004D49E1", RsidParagraphProperties = "004D49E1", RsidRunAdditionDefault = "004D49E1" }; Wordprocessing.ParagraphProperties paragraphProperties3 = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines3 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; Wordprocessing.Justification justification3 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; paragraphProperties3.Append(spacingBetweenLines3); paragraphProperties3.Append(justification3); Wordprocessing.Run run4 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties4 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts7 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.Bold bold4 = new Wordprocessing.Bold(); runProperties4.Append(runFonts7); runProperties4.Append(bold4); Wordprocessing.Text text4 = new Wordprocessing.Text(); text4.Text = "ЭКЗАМЕНАЦИОННАЯ ВЕДОМОСТЬ"; run4.Append(runProperties4); run4.Append(text4); Wordprocessing.Run run5 = new Wordprocessing.Run(); Wordprocessing.Break break2 = new Wordprocessing.Break(); run5.Append(break2); paragraph3.Append(paragraphProperties3); paragraph3.Append(run4); paragraph3.Append(run5); body.Append(paragraph1); body.Append(paragraph2); body.Append(paragraph3); return body; }
private Wordprocessing.Table doptable(Wordprocessing.Table table) { //Строка подпись декана Wordprocessing.TableRow tableRow2 = new Wordprocessing.TableRow() { RsidTableRowAddition = "00FF67BF", RsidTableRowProperties = "008E2483" }; Wordprocessing.TableCell tableCell = new Wordprocessing.TableCell(); Wordprocessing.TableCellProperties tableCellProperties = new Wordprocessing.TableCellProperties(); Wordprocessing.TableCellWidth tableCellWidth = new Wordprocessing.TableCellWidth() { Width = "0", Type = Wordprocessing.TableWidthUnitValues.Auto }; Wordprocessing.GridSpan gridSpan = new Wordprocessing.GridSpan() { Val = 6 }; Wordprocessing.TableCellVerticalAlignment tableCellVerticalAlignment = new Wordprocessing.TableCellVerticalAlignment() { Val = Wordprocessing.TableVerticalAlignmentValues.Center }; tableCellProperties.Append(tableCellWidth); tableCellProperties.Append(gridSpan); tableCellProperties.Append(tableCellVerticalAlignment); Wordprocessing.Paragraph paragraph = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties parprop = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; parprop.Append(spacingBetweenLines2); paragraph.Append(parprop); Wordprocessing.Run run = new Wordprocessing.Run(); Wordprocessing.Text text = new Wordprocessing.Text(); text.Text = "Подпись декана"; run.Append(text); paragraph.Append(run); tableCell.Append(tableCellProperties); tableCell.Append(paragraph); tableRow2.Append(tableCell); table.Append(tableRow2); return table; }
private Wordprocessing.Paragraph retText(int r, int c) { string value=""; if (r == 0 && c == 0) value = "Подпись преподавателя"; if (r == 1 && c == 1) value = "1.Факультет составляет ведомость в 1 экз."; if (r == 2 && c == 1) value = "2.Экзаменатор лично получает ведомость в деканате."; if (r == 3 && c == 1) value = "3.По окончании экзамена экзаменатор лично сдает"; if (r == 4 && c == 1) value = "ведомость в деканат."; if (r == 1 && c == 2) value = "ИТОГО"; if (r == 1 && c == 3) value = "отлично"; if (r == 2 && c == 3) value = "хорошо"; if (r == 3 && c == 3) value = "удовлетворительно"; if (r == 4 && c == 3) value = "плохо"; if (r == 5 && c == 3) value = "не явился"; Wordprocessing.Run run = new Wordprocessing.Run(); Wordprocessing.Text text = new Wordprocessing.Text(value); run.Append(text); Wordprocessing.Paragraph par = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties parprop = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines = new Wordprocessing.SpacingBetweenLines() { After = "0" }; parprop.Append(spacingBetweenLines); par.Append(parprop); par.Append(run); return par; }
public static void SetSpacinggBetweenLines(ParagraphProperties pp, int space) { OpenXmlElementHelper.SetChild(pp, new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Auto, Line = space.ToString() }); }
public static void SetJustification(ParagraphProperties pp, JustificationValues jv) { OpenXmlElementHelper.SetChild(pp, new Justification { Val = jv }); }
public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedChapter(Chapter chapter) { if(!stylesAdded) StyleCreator.AddStylePart(); List<OpenXmlElement> result = new List<OpenXmlElement>(); //Setting up Heading style Word.ParagraphProperties paraProps = new Word.ParagraphProperties(); Word.ParagraphStyleId style = new Word.ParagraphStyleId() { Val = "Heading1" }; paraProps.Append(style); //Adding chapter title Word.Paragraph para = new Word.Paragraph(); Word.Run run = new Word.Run(); Word.Text text = new Word.Text() { Text = chapter.Title }; run.Append(text); para.Append(paraProps); para.Append(run); result.Add(para); //Add all child elements foreach (Element element in chapter.SubElements) { if (element.GetElementType() == ElementType.MultiColumnSection) { result.AddRange(MultiColumnSectionFormatter.GetFormattedSection((MultiColumnSection)element)); } else if (element.GetElementType() == ElementType.Section) result.AddRange(SectionFormatter.GetFormattedSection((Section)element)); else throw new InvalidSubFeatureException( chapter.GetElementType().ToString() , element.GetElementType().ToString()); } return result.ToArray(); }