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 WP.Paragraph EccentricityParagraph(Bar bar, float ecc) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); officeMath.Append( GenerateRunWithText($"e = "), CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"M") }, new List <OpenXmlElement> { GenerateRunWithText($"N") }), GenerateRunWithText(" = "), CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"{bar.ActualMoment}∙ 100") }, new List <OpenXmlElement> { GenerateRunWithText($"{Math.Abs(bar.ActualForce)}") }), GenerateRunWithText($" = {ecc * 100} cм") ); p.AppendChild(officeMath); return(p); }
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); } }
public static WP.Paragraph LambdaParagraph(Bar bar, float lambda) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); officeMath.Append( GenerateRunWithText($"λ = "), CreateFraction( new List <OpenXmlElement> { Index("l", "x"), GenerateRunWithText($"∙"), Index("μ", "x") }, new List <OpenXmlElement> { Index("i", "x") }), GenerateRunWithText(" = "), CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"{bar.Length} ∙ 1") }, new List <OpenXmlElement> { GenerateRunWithText($"{bar.Section.RadiusOfGyrationX} ∙ 10") }), GenerateRunWithText($" = {lambda}") ); p.AppendChild(officeMath); return(p); }
public static WP.Paragraph GenerateParagraphWithAxialTensionFormula(Bar bar, float Ry) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); var fractionFormula = CreateFraction( new List <OpenXmlElement> { GenerateRunWithText("N") }, new List <OpenXmlElement> { GenerateRunWithText("A∙"), Index("R", "y") }); var fraction = CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"{Math.Abs(bar.ActualForce)}") }, new List <OpenXmlElement> { GenerateRunWithText($"{bar.Section.Area}∙{Ry}∙"), Power("10", "2") }); officeMath.Append( fractionFormula, new Run(new Text(" = ")), fraction, new Run(new Text($" = {bar.CalcResult} " + (bar.CalcResult <= 1 ? "≤" : ">") + " 1"))); p.AppendChild(officeMath); return(p); }
public static WP.Paragraph ReffEccentricityParagraph(Bar bar, float e, float m) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); officeMath.Append( GenerateRunWithText("m = e ∙ "), CreateFraction( new List <OpenXmlElement> { GenerateRunWithText("A") }, new List <OpenXmlElement> { GenerateRunWithText("W") }), GenerateRunWithText($" = {e} ∙ "), CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"{bar.Section.Area}") }, new List <OpenXmlElement> { GenerateRunWithText($"{bar.Section.SectionModulusX}") }), GenerateRunWithText($" = {m}") ); p.AppendChild(officeMath); return(p); }
public void InsertDecisionDetailViewMessage() { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decision Detail View")); // _body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Detail View")))); _body.AppendChild(new Paragraph()); }
public void InsertDecisionWithoutTopicMessage() { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decisions without topic")); //_body.AppendChild(new Paragraph(new Run(new Text("Decisions not included in a topic:")))); _body.AppendChild(new Paragraph()); }
public static WP.Paragraph GenerateParagraphWithText(string content) { var p = new WP.Paragraph(); var r = new WP.Run(); var text = new WP.Text(content); r.AppendChild(text); p.AppendChild(r); return(p); }
public static WP.Paragraph MefParagraph(float m, float etta, float mef) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); officeMath.Append( Index("m", "ef"), GenerateRunWithText($" = m ∙ η = {m} ∙ {etta} = {mef}")); p.AppendChild(officeMath); return(p); }
private void SetCellText(TableCell cell, string text, bool bold) { ParagraphProperties parProperties = new ParagraphProperties(); parProperties.Justification = new Justification(); parProperties.Justification.Val = JustificationValues.Center; Paragraph paragraph = new Paragraph(); paragraph.AppendChild(parProperties); var run = new Run(new Text(text)); run.RunProperties = new RunProperties(); run.RunProperties.FontSize = new FontSize(); run.RunProperties.FontSize.Val = new StringValue("28"); if (bold) { run.RunProperties.Bold = new Bold(); } paragraph.AppendChild(run); cell.AppendChild(paragraph); }
public void InsertTopicTable(ITopic topic) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading3(run); run.AppendChild(new Text(_diagmarCounter + "." + (++_topicCounter) + ". " + topic.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(_diagmarCounter + "." + (++_topicCounter) + ". " + topic.Name)))); //Topic Name if (topic.Description != "") { _body.AppendChild(new Paragraph(new Run(new Text(topic.Description)))); //Topic Desc } _body.AppendChild(new Paragraph()); }
private void AddPersonalRow(Body body, OpenXmlElement after, string firstName, string lastName, string city) { Paragraph par = new Paragraph(); var run = new Run(); run.RunProperties = new RunProperties(); run.RunProperties.FontSize = new FontSize(); run.RunProperties.FontSize.Val = new StringValue("28"); run.AppendChild(new Break()); run.AppendChild(new TabChar()); run.AppendChild(new Text($"{firstName} {lastName}, {city}")); par.AppendChild(run); body.InsertAfter(par, after); }
public static void CreateWordprocessingDocument(string filepath) { // Create a document by supplying the filepath. using (var wordprocessingDocument = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart(); mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); Body body = mainPart.Document.AppendChild(new Body()); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("siddiq")); wordprocessingDocument.MainDocumentPart.Document.Save(); } }
public void InsertDiagramImage(IEADiagram diagram) { if (diagram.IsRelationshipView()) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Relationship View: " + diagram.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Relationship Viewpoint")))); } else if (diagram.IsStakeholderInvolvementView()) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild( new Text(++_diagmarCounter + ". Decision Stakeholder Involvement View: " + diagram.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Stakeholder Involvement Viewpoint")))); } else if (diagram.IsChronologicalView()) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decision Chronological View: " + diagram.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Chronological Viewpoint")))); } else { return; } _body.AppendChild(new Paragraph(new Run(new Text()))); ImagePart imagePart = _mainPart.AddImagePart(ImagePartType.Emf); FileStream fs = diagram.DiagramToStream(); imagePart.FeedData(fs); Image image = Image.FromFile(fs.Name); AddImageToBody(_mainPart.GetIdOfPart(imagePart), Utils.GetImageSize(image)); //cleanup: fs.Close(); image.Dispose(); File.Delete(fs.Name); }
public static void createDocument(string filepath) { // Create a document by supplying the filepath. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("HQ - QUANTUM 2012")); } }
/// <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 static WP.Paragraph LambdaRefParagraph(float lambda, float lambdaRef, float Ry, float E) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); var bar = new DocumentFormat.OpenXml.Math.Bar(); var barProperties = new BarProperties(); var position = new Position() { Val = VerticalJustificationValues.Top }; barProperties.Append(position); var bas = new Base(new Run(new Text("λ"))); bar.Append(barProperties, bas); officeMath.Append( bar, GenerateRunWithText(" = λ ∙ "), CreateRadical( CreateFraction( new List <OpenXmlElement> { Index("R", "y") }, new List <OpenXmlElement> { GenerateRunWithText("E") })), GenerateRunWithText($" = {lambda} "), CreateRadical( CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"{Ry}") }, new List <OpenXmlElement> { GenerateRunWithText($"{E}") })), GenerateRunWithText(" = "), GenerateRunWithText($" = {lambdaRef}") ); p.AppendChild(officeMath); return(p); }
private void AddLinks() { WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true); Body body = wordprocessingDocument.MainDocumentPart.Document.Body; DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); System.Random rand = new System.Random(); int r = rand.Next(1, 11111111); res = res.Replace("<w:numId w:val=\"1\" />", "<w:numId w:val=\"" + r + "\" />"); body.InnerXml += res; wordprocessingDocument.Close(); }
public void AddTheListOfSourcesUsed(string filepath) { if (!File.Exists(filePath1.Text)) { Application.Current.Shutdown(); } WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true); Body body = wordprocessingDocument.MainDocumentPart.Document.Body; DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run()); text = body.InnerText; FileStream fl = new FileStream(@"NEWXML.xml", FileMode.OpenOrCreate); byte[] innerxml = Encoding.UTF8.GetBytes(body.InnerXml); fl.Write(innerxml, 0, innerxml.Length); fl.Close(); wordprocessingDocument.Close(); }
public WordDocument(string filename) { _filename = filename; using ( WordprocessingDocument wordDoc = WordprocessingDocument.Create(_filename, WordprocessingDocumentType.Document)) { _mainPart = wordDoc.AddMainDocumentPart(); _mainPart.Document = new Document(); _body = _mainPart.Document.AppendChild(new Body()); DateTime saveNow = DateTime.Now; Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading1(run); run.AppendChild(new Text("Decision Report [" + saveNow + "]")); //_body.Append(new Paragraph(new Run(new Text("Decision Report [" + saveNow + "]")))); _body.AppendChild(new Paragraph()); } }
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); }
/// <summary> /// Add the text paragraph. /// </summary> /// <param name="txt">The text.</param> /// <param name="boldStyle">if set to <c>true</c> [bold style].</param> public void AddTextParagraph( string txt, bool boldStyle) { // Assign a reference to the existing document body. Body body = _wordProcessingDocument.MainDocumentPart.Document.Body; // Add new text. Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(txt)); //create RunProperties and append styles RunProperties runProperties = new RunProperties(); if (boldStyle) { runProperties.Append(new Bold()); } // Set the RunProperties to the RunProperties containing the styles run.RunProperties = runProperties; }
public static WP.Paragraph AreaFractionParagraph(Bar bar, float afaw) { var p = new WP.Paragraph(); var officeMath = new OfficeMath(); officeMath.Append( CreateFraction( new List <OpenXmlElement> { Index("A", "f") }, new List <OpenXmlElement> { Index("A", "w") }), GenerateRunWithText(" = "), CreateFraction( new List <OpenXmlElement> { Index("b", "f"), GenerateRunWithText(" ∙ "), Index("t", "f") }, new List <OpenXmlElement> { GenerateRunWithText("2 ∙ "), Index("h", "w"), GenerateRunWithText(" ∙ "), Index("t", "w") }), GenerateRunWithText(" = "), CreateFraction( new List <OpenXmlElement> { GenerateRunWithText($"{bar.Section.Width} ∙{bar.Section.Thickness}") }, new List <OpenXmlElement> { GenerateRunWithText($"2 ∙ {bar.Section.Height} ∙ {bar.Section.Thickness}") }), GenerateRunWithText($" = {afaw}") ); p.AppendChild(officeMath); return(p); }
public void ProcessWordDocument(string docFilePath) { tableIndex = 1; mathIndex = 1; imageIndex = 1; textIndex = 1; using (WordprocessingDocument doc = WordprocessingDocument.Open(docFilePath, false)) { foreach (var table in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>()) { int trows = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>().Count(); int tcols = table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>().First().Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>().Count(); WordTable wordTable = new WordTable(trows, tcols); //create a table class and add the text from the rows and cells int row = 0, cell = 0; foreach (var tableRow in table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>()) { foreach (var tableCell in tableRow.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>()) { string text = tableCell.InnerText; wordTable.AddText(row, cell, text); cell++; //save the cell into a table class for later processing with row info } cell = 0; row++; } DocumentFormat.OpenXml.Wordprocessing.Paragraph para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Table-&" + tableIndex; run.AppendChild(new Text(IDplaceholder)); table.Parent.ReplaceChild(para, table); //table.Remove(); tableIndex++; //store the table TableList.Add(IDplaceholder, wordTable); } foreach (var formula in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Math.OfficeMath>()) { string wordDocXml = formula.OuterXml; XslCompiledTransform xslTransform = new XslCompiledTransform(); xslTransform.Load(officeMathMLSchemaFilePath); string mmlFormula = null; using (TextReader tr = new StringReader(wordDocXml)) { // Load the xml of your main document part. using (XmlReader reader = XmlReader.Create(tr)) { XmlWriterSettings settings = xslTransform.OutputSettings.Clone(); // Configure xml writer to omit xml declaration. settings.ConformanceLevel = ConformanceLevel.Fragment; settings.OmitXmlDeclaration = true; using (MemoryStream ms = new MemoryStream()) { XmlWriter xw = XmlWriter.Create(ms, settings); // Transform our OfficeMathML to MathML. xslTransform.Transform(reader, xw); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms, Encoding.UTF8)) { mmlFormula = sr.ReadToEnd(); } } } DocumentFormat.OpenXml.Wordprocessing.Paragraph para = formula.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Math-&" + mathIndex; run.AppendChild(new Text(IDplaceholder)); mathIndex++; formula.Remove(); if (mmlFormula != null) { MathList.Add(IDplaceholder, mmlFormula); } } } foreach (var graphic in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Drawing.Graphic>()) { DocumentFormat.OpenXml.Drawing.Blip blip = graphic.FirstChild.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().First(); string imageId = blip.Embed.Value; ImagePart imagePart = (ImagePart)doc.MainDocumentPart.GetPartById(imageId); var uri = imagePart.Uri; var filename = uri.ToString().Split('/').Last(); var stream = doc.Package.GetPart(uri).GetStream(); Bitmap b = new Bitmap(stream); string imagePath = TempImageFolder + filename; b.Save(imagePath); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = graphic.Parent.Parent.Parent.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Image-&" + imageIndex; run.AppendChild(new Text(IDplaceholder)); imageIndex++; ImageList.Add(IDplaceholder, imagePath); } try { foreach (var video in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Drawing.VideoFromFile>()) { string localName = video.LocalName; string innerXml = video.InnerXml; } foreach (var video in doc.MainDocumentPart.EmbeddedObjectParts) { string vct = video.ContentType; } } catch { } foreach (var element in doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>()) { try { var psID = element.ParagraphProperties.ParagraphStyleId; string type = null; switch (psID.Val.ToString().ToLowerInvariant()) { //for each case save the inner text of the paragraph and remove it case "heading1": { type = "h1-"; break; } case "heading2": { type = "h2-"; break; } case "heading3": { type = "h3-"; break; } case "heading4": { type = "h4-"; break; } case "heading5": { type = "h5-"; break; } case "title": { type = "title-"; break; } case "subtitle": { type = "subtitle-"; break; } default: break; } if (type != null) { string id = "%" + type + "&" + textIndex; PlainTextList.Add(id, element.InnerText); textIndex++; element.RemoveAllChildren(); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = element.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(id)); } } catch { //do nothing } } PlaceholderIDList = ExtractTextAndCreatePlaceholderList(doc); if (textBuilder.Length > 0) { string s2 = AddTextToTextList(); if (s2 != null) PlaceholderIDList.Add(s2); } } }
public void InsertDecisionTable(IDecision decision) { var dataDict = new Dictionary <String, IList <String> >(); dataDict.Add("Name", new List <string>()); dataDict.Add("State", new List <string>()); dataDict.Add("Problem", new List <string>()); dataDict.Add("Decision", new List <string>()); dataDict.Add("Argumentation", new List <string>()); dataDict.Add("Alternatives", new List <string>()); dataDict.Add("Related Decisions", new List <string>()); dataDict.Add("Forces", new List <string>()); dataDict.Add("Traces", new List <string>()); dataDict.Add("Stakeholder Involvement", new List <string>()); dataDict.Add("History", new List <string>()); dataDict["Name"].Add(decision.Name); dataDict["State"].Add(decision.State); //dataDict["Problem"].Add(decision.Problem); //dataDict["Decision"].Add(decision.Solution); //dataDict["Argumentation"].Add(decision.Argumentation); _decisionCounter++; //_body.AppendChild(new Paragraph(new Run(new Text("Decision " +_decisionCounter.ToString() +": " + decision.Name)))); var table = new Table(); var props = new TableProperties( new TableBorders( new TopBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new BottomBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new LeftBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new RightBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new InsideHorizontalBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new InsideVerticalBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new TableWidth { Width = "5000", Type = TableWidthUnitValues.Pct } ), new TableCaption { Val = new StringValue("My Caption Val") // Does not work.. }); table.AppendChild(props); foreach (IDecisionRelation relation in decision.RelatedDecisions) { dataDict["Related Decisions"].Add(relation.Decision.GUID.Equals(decision.GUID) ? "<<this>> " + decision.Name + " - " + relation.Type + " - " + relation.RelatedDecision.Name : relation.Decision.Name + " - " + relation.Type + " - <<this>> " + decision.Name + "\r\n"); } foreach (IDecisionRelation alternative in decision.Alternatives) { dataDict["Alternatives"].Add(alternative.Decision.GUID.Equals(decision.GUID) ? "<<this>> " + decision.Name + " - " + alternative.Type + " - " + alternative.RelatedDecision.Name : alternative.Decision.Name + " - " + alternative.Type + " - <<this>> " + decision.Name + "\r\n"); } foreach (IForceEvaluation rating in decision.Forces) { IEAElement force = EAMain.Repository.GetElementByGUID(rating.Force.ForceGUID); dataDict["Forces"].Add(rating.Force.Name + " - " + force.Notes); } foreach (ITraceLink trace in decision.Traces) { dataDict["Traces"].Add(trace.TracedElementName); } foreach (IHistoryEntry entry in decision.History) { dataDict["History"].Add(entry.State + " " + entry.Modified.ToShortDateString()); } foreach (IStakeholderAction stakeholderInvolvment in decision.Stakeholders) { string line = string.Format(Messages.ReportingStakeholderInvolvmentLine, stakeholderInvolvment.Stakeholder.Role, stakeholderInvolvment.Stakeholder.Name, stakeholderInvolvment.Action); dataDict["Stakeholder Involvement"].Add(line); } foreach (var entry in dataDict) { if (entry.Value.Count == 0) { continue; } if ("".Equals(entry.Value[0])) { continue; } var tableRow = new TableRow(); var rowHeader = new TableCell(); rowHeader.Append(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1821" }); rowHeader.Append( new TableCellProperties(new Shading { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "##d3d4d6" })); Paragraph para = rowHeader.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); getBold(run); run.AppendChild(new Text(entry.Key)); var rowValue = new TableCell(); Paragraph rowValuePara = rowValue.AppendChild(new Paragraph()); Run rowValueRun = rowValuePara.AppendChild(new Run()); int lineCount = 0; foreach (string line in entry.Value) { rowValueRun.AppendChild(new Text(line)); if (++lineCount != entry.Value.Count) { rowValueRun.AppendChild(new Break()); } } tableRow.AppendChild(rowHeader); tableRow.AppendChild(rowValue); table.AppendChild(tableRow); } /* for (int i = 0; i <= data.GetUpperBound(0); i++) * { * var tr = new TableRow(); * for (int j = 0; j <= data.GetUpperBound(1); j++) * { * var tc = new TableCell(); * if (j == 0) * { * //Apply the same width at column 1 (0) * tc.Append(new TableCellWidth {Type = TableWidthUnitValues.Dxa, Width = "1821"}); * tc.Append(new TableCellProperties(new Shading{Val = ShadingPatternValues.Clear,Color = "auto",Fill = "##d3d4d6"})); * Paragraph para = tc.AppendChild(new Paragraph()); * Run run = para.AppendChild(new Run()); * RunProperties runProperties = getBold(run); * run.AppendChild(new Text(dataDict.)); * } * else * { * tc.AppendChild(new Paragraph(new Run(new Text(data[i, j])))); * } * * tr.AppendChild(tc); * } * if (data[i, 1] != "") * table.AppendChild(tr); * }*/ _body.AppendChild(table); _body.AppendChild(new Paragraph()); }
private void InsertPageBreak(WordprocessingDocument wordprocessingDocument) { MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; WordDoc.Body body = mainPart.Document.Body; WordDoc.Paragraph para = new WordDoc.Paragraph(); para = body.AppendChild(new WordDoc.Paragraph()); WordDoc.Run run = para.AppendChild(new WordDoc.Run( new WordDoc.Break() { Type = WordDoc.BreakValues.Page } )); }
public void AddTextToWord(WordprocessingDocument doc, string text, bool bold, bool italic, bool underline, int heading, int slideNumber) { MainDocumentPart mainPart = doc.MainDocumentPart; WordDoc.Body body = mainPart.Document.Body; WordDoc.Paragraph para = new WordDoc.Paragraph(); foreach (WordDoc.Paragraph p in body.Elements<WordDoc.Paragraph>()) { para = p; } if (heading != 0) { para = body.AppendChild(new WordDoc.Paragraph()); para.ParagraphProperties = new WordDoc.ParagraphProperties(new WordDoc.ParagraphStyleId() { Val = "Heading" + heading.ToString() }); bold = false; italic = false; underline = false; WordDoc.BookmarkStart bs = new WordDoc.BookmarkStart(); bs.Id = slideNumber.ToString(); bs.Name = text; bs = para.AppendChild(bs); } else { if (para.ParagraphProperties != null) { if (para.ParagraphProperties.ParagraphStyleId != null) { if (para.ParagraphProperties.ParagraphStyleId.Val == "Heading1" || para.ParagraphProperties.ParagraphStyleId.Val == "Heading2" || para.ParagraphProperties.ParagraphStyleId.Val == "Heading3") { para = body.AppendChild(new WordDoc.Paragraph()); } } } } string[] t1 = text.Split('\n'); for (int j = 0; j < t1.Length; j++) { WordDoc.Run run = para.AppendChild(new WordDoc.Run()); WordDoc.RunProperties rp = run.AppendChild(new WordDoc.RunProperties()); if (bold) { WordDoc.Bold b = rp.AppendChild(new WordDoc.Bold()); } if (italic) { WordDoc.Italic i = rp.AppendChild(new WordDoc.Italic()); } if (underline) { WordDoc.Underline u = new WordDoc.Underline() { Val = WordDoc.UnderlineValues.Single }; rp.AppendChild(u); } WordDoc.Text t = new WordDoc.Text() { Text = t1[j], Space = SpaceProcessingModeValues.Preserve }; run.AppendChild(t); if (j != t1.Length - 1) run.AppendChild(new WordDoc.Break()); } WordDoc.BookmarkEnd be = new WordDoc.BookmarkEnd(); be.Id = slideNumber.ToString(); be = para.AppendChild(be); }
public void InsertForcesTable(IForcesModel forces) { Paragraph para = _body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); RunProperties runProperties = getHeading2(run); run.AppendChild(new Text(++_diagmarCounter + ". Decision Forces Viewpoint: " + forces.Name)); //_body.AppendChild(new Paragraph(new Run(new Text(++_diagmarCounter + ". Decision Forces Viewpoint")))); _body.AppendChild(new Paragraph(new Run(new Text()))); var table = new Table(); var props = new TableProperties( new TableBorders( new TopBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new BottomBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new LeftBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new RightBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new InsideHorizontalBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 }, new InsideVerticalBorder { Val = new EnumValue <BorderValues>(BorderValues.Single), Size = 11 })); table.AppendChild(props); var emptyCell = new TableCell(); // insert an empty cell in tol left of forces table var decRow = new TableRow(); decRow.AppendChild(emptyCell); emptyCell.AppendChild(new Paragraph(new Run(new Text("")))); // insert the concern header and the decisions names var concCellHeader = new TableCell(new Paragraph(new Run(new Text("Concerns")))); decRow.AppendChild(concCellHeader); foreach ( TableCell decCell in forces.GetDecisions() .Select(decision => new TableCell(new Paragraph(new Run(new Text(decision.Name)))))) { decRow.AppendChild(decCell); } table.AppendChild(decRow); foreach (var concernsPerForces in forces.GetConcernsPerForce()) { IEAElement force = concernsPerForces.Key; List <IEAElement> concerns = concernsPerForces.Value; foreach (IEAElement concern in concerns) { var forceRow = new TableRow(); var forceCell = new TableCell(new Paragraph(new Run(new Text(force.Name)))); forceRow.AppendChild(forceCell); var concCell = new TableCell(); concCell.AppendChild(new Paragraph(new Run(new Text(concern.Name)))); forceRow.AppendChild(concCell); // insert ratings foreach (Rating rating in forces.GetRatings()) { if (rating.ForceGUID != force.GUID || rating.ConcernGUID != concern.GUID) { continue; } if (forces.GetDecisions().Any(decision => rating.DecisionGUID == decision.GUID)) { var ratCell = new TableCell(); ratCell.AppendChild(new Paragraph(new Run(new Text(rating.Value)))); forceRow.AppendChild(ratCell); } } table.AppendChild(forceRow); } } _body.AppendChild(table); _body.AppendChild(new Paragraph()); }
/// <summary> /// Appends a Drawing object to the paragraph /// </summary> /// <param name="drawing"></param> /// <returns></returns> public Paragraph Append(Drawing drawing) { paragraph.AppendChild(new Run(drawing)); return(this); }
Word.TableRow CreateRow(ArrayList cellText) { Word.TableRow tr = new Word.TableRow(); // Create cells with simple text. foreach (string s in cellText) { Word.TableCell tc = new Word.TableCell(); Word.Paragraph p = new Word.Paragraph(); Word.Run r = new Word.Run(); Word.Text t = new Word.Text(s); r.AppendChild(t); p.AppendChild(r); tc.AppendChild(p); tr.AppendChild(tc); } return tr; }
public void ProcessWordDocument(string docFilePath) { tableIndex = 1; mathIndex = 1; imageIndex = 1; videoIndex = 1; textIndex = 1; using (WordprocessingDocument doc = WordprocessingDocument.Open(docFilePath, false)) { foreach (var table in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Table>()) { int trows = table.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableRow>().Count(); int tcols = table.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableRow>().First().Descendants <DocumentFormat.OpenXml.Wordprocessing.TableCell>().Count(); WordTable wordTable = new WordTable(trows, tcols); //create a table class and add the text from the rows and cells int row = 0, cell = 0; foreach (var tableRow in table.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableRow>()) { foreach (var tableCell in tableRow.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableCell>()) { string text = tableCell.InnerText; wordTable.AddText(row, cell, text); cell++; //save the cell into a table class for later processing with row info } cell = 0; row++; } DocumentFormat.OpenXml.Wordprocessing.Paragraph para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Table-&" + tableIndex; run.AppendChild(new Text(IDplaceholder)); table.Parent.ReplaceChild(para, table); //table.Remove(); tableIndex++; //store the table TableList.Add(IDplaceholder, wordTable); } foreach (var formula in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Math.OfficeMath>()) { string wordDocXml = formula.OuterXml; XslCompiledTransform xslTransform = new XslCompiledTransform(); xslTransform.Load(officeMathMLSchemaFilePath); string mmlFormula = null; using (TextReader tr = new StringReader(wordDocXml)) { // Load the xml of your main document part. using (XmlReader reader = XmlReader.Create(tr)) { XmlWriterSettings settings = xslTransform.OutputSettings.Clone(); // Configure xml writer to omit xml declaration. settings.ConformanceLevel = ConformanceLevel.Fragment; settings.OmitXmlDeclaration = true; using (MemoryStream ms = new MemoryStream()) { XmlWriter xw = XmlWriter.Create(ms, settings); // Transform our OfficeMathML to MathML. xslTransform.Transform(reader, xw); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms, Encoding.UTF8)) { mmlFormula = sr.ReadToEnd(); } } } DocumentFormat.OpenXml.Wordprocessing.Paragraph para = formula.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Math-&" + mathIndex; run.AppendChild(new Text(IDplaceholder)); mathIndex++; formula.Remove(); if (mmlFormula != null) { MathList.Add(IDplaceholder, mmlFormula); } } } foreach (var graphic in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Drawing.Graphic>()) { DocumentFormat.OpenXml.Drawing.Blip blip = graphic.FirstChild.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().First(); string imageId = blip.Embed.Value; ImagePart imagePart = (ImagePart)doc.MainDocumentPart.GetPartById(imageId); var uri = imagePart.Uri; var filename = uri.ToString().Split('/').Last(); var stream = doc.Package.GetPart(uri).GetStream(); Bitmap b = new Bitmap(stream); string imagePath = TempImageFolder + filename; b.Save(imagePath); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = graphic.Parent.Parent.Parent.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Image-&" + imageIndex; run.AppendChild(new Text(IDplaceholder)); imageIndex++; ImageList.Add(IDplaceholder, imagePath); } try { foreach (var video in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Drawing.VideoFromFile>()) { //extract video bytes from word document DocumentFormat.OpenXml.Drawing.Blip blip = video.FirstChild.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().First(); var vid = doc.MainDocumentPart.GetPartById(blip.Embed.Value); var uri = vid.Uri; var filename = uri.ToString().Split('/').Last(); var stream = doc.Package.GetPart(uri).GetStream(); byte[] videoBytes; using (BinaryReader br = new BinaryReader(stream)) { videoBytes = br.ReadBytes((int)stream.Length); } //TODO set these up universally somewhere string videoFolder = @"C:\websites\RoboBraille.Web.Api\dist\"; string urlDistribution = @"http://2.109.50.18:5150/dist/" + filename; //write bytes to shared web folder File.WriteAllBytes(videoFolder + filename, videoBytes); //send post video request to Amara //put placeholder //TODO check that video.Parent.Parent ...points to the right parent DocumentFormat.OpenXml.Wordprocessing.Paragraph para = video.Parent.Parent.Parent.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); string IDplaceholder = "%Video-&" + videoIndex; run.AppendChild(new Text(IDplaceholder)); videoIndex++; //make somehow an list of videos sent to amara and their source location and store that info somewhere? maybe as jobs? } } catch { } foreach (var element in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>()) { try { var psID = element.ParagraphProperties.ParagraphStyleId; string type = null; switch (psID.Val.ToString().ToLowerInvariant()) { //for each case save the inner text of the paragraph and remove it case "heading1": { type = "h1-"; break; } case "heading2": { type = "h2-"; break; } case "heading3": { type = "h3-"; break; } case "heading4": { type = "h4-"; break; } case "heading5": { type = "h5-"; break; } case "title": { type = "title-"; break; } case "subtitle": { type = "subtitle-"; break; } default: break; } if (type != null) { string id = "%" + type + "&" + textIndex; PlainTextList.Add(id, element.InnerText); textIndex++; element.RemoveAllChildren(); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = element.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(id)); } } catch { //do nothing } } PlaceholderIDList = ExtractTextAndCreatePlaceholderList(doc); if (textBuilder.Length > 0) { string s2 = AddTextToTextList(); if (s2 != null) { PlaceholderIDList.Add(s2); } } } }
private void EmptyLine(Body body, Paragraph para) { para = body.AppendChild(new Paragraph()); para.AppendChild(GetText(string.Empty, FontSizeSmall)); }
public void wordDocOpenXml(string TemplateFileLocation, string GeneratedFileNameLocation, List <ModelField> dataMap) { if (System.IO.File.Exists(GeneratedFileNameLocation)) { System.IO.File.Delete(GeneratedFileNameLocation); } System.IO.File.Copy(TemplateFileLocation, GeneratedFileNameLocation); using (WordprocessingDocument document = WordprocessingDocument.Open(GeneratedFileNameLocation, true)) { // Change the document type to Document document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); // Get the MainPart of the document MainDocumentPart mainPart = document.MainDocumentPart; // Get the Document Settings Part DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart; OpenXmlElement[] Enumerate = mainPart.ContentControls().ToArray(); for (int i = 0; i < Enumerate.Count(); i++) { OpenXmlElement cc = Enumerate[i]; SdtProperties props = cc.Elements <SdtProperties>().FirstOrDefault(); Tag tag = props.Elements <Tag>().FirstOrDefault(); //Console.WriteLine(tag.Val); SdtAlias alias = props.Elements <SdtAlias>().FirstOrDefault(); string title = ((DocumentFormat.OpenXml.Wordprocessing.StringType)(alias)).Val; string tagName = tag.Val; //if (dataMap.Any(f => string.Format("{0}Tag", f.Key) == tagName)) if (dataMap.Any(f => f.Key == title)) { var valkey = dataMap.FirstOrDefault(f => f.Key == title).Value; object val = POCUtil.DictionaryMappedDocPOC[valkey]; OpenXmlElement parentElement = cc.Parent; DocumentFormat.OpenXml.Wordprocessing.Paragraph pg = cc.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>().FirstOrDefault(); if (pg != null || true) { //ParagraphProperties paragraphProperties = (ParagraphProperties)cc.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().FirstOrDefault().ParagraphProperties.Clone(); Run r1 = null; DocumentFormat.OpenXml.Wordprocessing.Paragraph p1 = null; if (cc.Parent.GetType() != typeof(DocumentFormat.OpenXml.Wordprocessing.Paragraph)) { p1 = parentElement.InsertAfter(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(), cc); r1 = p1.AppendChild(new Run()); } else { r1 = parentElement.InsertAfter(new Run(), cc); } r1.RunProperties = new RunProperties(); cc.Descendants <DocumentFormat.OpenXml.Wordprocessing.RunProperties>().ToList().ForEach( runProperty => runProperty.ToList().ForEach( property => { if (!r1.RunProperties.ChildElements.ToList().Exists(propertyToAdd => propertyToAdd.GetType() == property.GetType())) { r1.RunProperties.AppendChild((OpenXmlElement)property.CloneNode(true)); } } ) ); if (cc.Descendants <DocumentFormat.OpenXml.Office2010.Word.SdtContentCheckBox>().Count() > 0) { //☒ //☐ //☐ var t2 = r1.AppendChild(new Text("☒")); //DocumentFormat.OpenXml.Wordprocessing.CheckBox c1 = r1.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.CheckBox()); //c1.AppendChild(new Checked()); } else { var t1 = r1.AppendChild(new Text(val.ToString())); } } } } while (mainPart.ContentControls().Count() > 0) { mainPart.ContentControls().FirstOrDefault().Remove(); } // Save the document mainPart.Document.Save(); document.Close(); } }