/// <summary> /// Render a hyperlink. /// </summary> /// <param name="hyperlink"></param> /// <param name="parent"></param> /// <param name="context"></param> /// <param name="documentPart"></param> /// <param name="formatProvider"></param> /// <returns></returns> public static OpenXmlElement Render(this Hyperlink hyperlink, OpenXmlElement parent, ContextModel context, OpenXmlPart documentPart, IFormatProvider formatProvider) { context.ReplaceItem(hyperlink, formatProvider); if (!hyperlink.Show) { return(null); } var fieldCodeXmlelement = new DocumentFormat.OpenXml.Wordprocessing.Hyperlink(); if (!string.IsNullOrWhiteSpace(hyperlink.Anchor)) { fieldCodeXmlelement.Anchor = hyperlink.Anchor; } else if (!string.IsNullOrWhiteSpace(hyperlink.WebSiteUri)) { HyperlinkRelationship hyperlinkPart = documentPart.AddHyperlinkRelationship(new Uri(hyperlink.WebSiteUri), true); fieldCodeXmlelement.Id = hyperlinkPart.Id; } parent.AppendChild(fieldCodeXmlelement); hyperlink.Text.Render(fieldCodeXmlelement, context, documentPart, formatProvider); return(fieldCodeXmlelement); }
public Hyperlink CreateUrlHyperlink(MainDocumentPart mainPart, string text, string url, string style) { RunProperties rp = new RunProperties( new RunStyle() { Val = style }); HyperlinkRelationship rel = mainPart.AddHyperlinkRelationship(new Uri(url), true); var hyperlink = new Hyperlink( new ProofError() { Type = ProofingErrorValues.GrammarStart }, new Run( rp, new Text(text))) { History = true, Id = rel.Id }; return(hyperlink); }
/// <summary> /// Get hyperlink URL string by r:id /// </summary> /// <param name="rid"></param> /// <returns>Return hyperlink URL string or null.</returns> public String GetHyperlinkById(String rid) { HyperlinkRelationship hr = this.hyperlinkRelationships.FirstOrDefault(c => c.Id == rid); if (hr != null && hr.IsExternal && hr.Uri != null) { return(hr.Uri.OriginalString); } else { return(null); } }
/// <summary> /// Add hyperlink /// </summary> /// <param name="hyperlink"></param> /// <returns></returns> private string AddHyperlink(Hyperlink hyperlink) { string styleTemplate = "<span style='STYLE_CONTENT'>HYPERLINK_CONTENT</span>"; string style = ""; List <string> cssStyleElements = new List <string>(); HyperlinkRelationship relation = (from rel in document.MainDocumentPart.HyperlinkRelationships where rel.Id == hyperlink.Id select rel).FirstOrDefault() as HyperlinkRelationship; if (relation != null) { string result = "<a href=\"" + relation.Uri.ToString() + "\">" + hyperlink.Descendants <Run>().Select(x => x.InnerText).Aggregate((i, j) => i + j) + "</a>"; FontSize fontSize = hyperlink.Descendants <FontSize>().FirstOrDefault(); if (fontSize != null) { cssStyleElements.Add(string.Format("font-size:{0}pt", Convert.ToInt32(fontSize.Val.Value) / 2)); } foreach (string element in cssStyleElements) { style += element + " "; } result = styleTemplate.Replace("HYPERLINK_CONTENT", result).Replace("STYLE_CONTENT", style); Italic italic = hyperlink.Descendants <Italic>().FirstOrDefault(); if (italic != null) { result = AddFormat(result, "i"); } return(result); } else { return(""); } }
/// <summary> /// Add a note to the FootNotes part and ensure it exists. /// </summary> /// <param name="description">The description of an acronym, abbreviation, some book references, ...</param> /// <returns>Returns the id of the footnote reference.</returns> protected int AddFootnoteReference(string description) { FootnotesPart fpart = mainPart.FootnotesPart; if (fpart == null) { fpart = mainPart.AddNewPart <FootnotesPart>(); } if (fpart.Footnotes == null) { // Insert a new Footnotes reference new Footnotes( new Footnote( new Paragraph( new ParagraphProperties { SpacingBetweenLines = new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto } }, new Run( new SeparatorMark()) ) ) { Type = FootnoteEndnoteValues.Separator, Id = -1 }, new Footnote( new Paragraph( new ParagraphProperties { SpacingBetweenLines = new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto } }, new Run( new ContinuationSeparatorMark()) ) ) { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0 }).Save(fpart); footnotesRef = 1; } else { // The footnotesRef Id is a required field and should be unique. You can assign yourself some hard-coded // value but that's absolutely not safe. We will loop through the existing Footnote // to retrieve the highest Id. foreach (var fn in fpart.Footnotes.Elements <Footnote>()) { if (fn.Id.HasValue && fn.Id > footnotesRef) { footnotesRef = (int)fn.Id.Value; } } footnotesRef++; } Run markerRun; Paragraph p; fpart.Footnotes.Append( new Footnote( p = new Paragraph( new ParagraphProperties { ParagraphStyleId = new ParagraphStyleId() { Val = htmlStyles.GetStyle("footnote text", StyleValues.Paragraph) } }, markerRun = new Run( new RunProperties { RunStyle = new RunStyle() { Val = htmlStyles.GetStyle("footnote reference", StyleValues.Character) } }, new FootnoteReferenceMark()), new Run( // Word insert automatically a space before the definition to separate the // reference number with its description new Text(" ") { Space = SpaceProcessingModeValues.Preserve }) ) ) { Id = footnotesRef }); // Description in footnote reference can be plain text or a web protocols/file share (like \\server01) Uri uriReference; Regex linkRegex = new Regex(@"^((https?|ftps?|mailto|file)://|[\\]{2})(?:[\w][\w.-]?)"); if (linkRegex.IsMatch(description) && Uri.TryCreate(description, UriKind.Absolute, out uriReference)) { HyperlinkRelationship extLink = fpart.AddHyperlinkRelationship(uriReference, true); var h = new Hyperlink( ) { History = true, Id = extLink.Id }; htmlStyles.EnsureKnownStyle(HtmlDocumentStyle.KnownStyles.Hyperlink); h.Append(new Run( new RunProperties { RunStyle = new RunStyle() { Val = htmlStyles.GetStyle("Hyperlink", StyleValues.Character) } }, new Text(description))); p.Append(h); } else { p.Append(new Run( new Text(description) { Space = SpaceProcessingModeValues.Preserve })); } if (!htmlStyles.DoesStyleExists("footnote reference")) { // Force the superscript style because if the footnote text style does not exists, // the rendering will be awful. markerRun.InsertInProperties(prop => prop.VerticalTextAlignment = new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript }); } fpart.Footnotes.Save(); return(footnotesRef); }
/// <summary> /// Add a note to the FootNotes part and ensure it exists. /// </summary> /// <param name="description">The description of an acronym, abbreviation, some book references, ...</param> /// <returns>Returns the id of the footnote reference.</returns> private int AddFootnoteReference(string description) { FootnotesPart fpart = mainPart.FootnotesPart; if (fpart == null) { fpart = mainPart.AddNewPart <FootnotesPart>(); } if (fpart.Footnotes == null) { // Insert a new Footnotes reference new Footnotes( new Footnote( new Paragraph( new ParagraphProperties { SpacingBetweenLines = new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto } }, new Run( new SeparatorMark()) ) ) { Type = FootnoteEndnoteValues.Separator, Id = -1 }, new Footnote( new Paragraph( new ParagraphProperties { SpacingBetweenLines = new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto } }, new Run( new ContinuationSeparatorMark()) ) ) { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0 }).Save(fpart); footnotesRef = 1; } else { // The footnotesRef Id is a required field and should be unique. You can assign yourself some hard-coded // value but that's absolutely not safe. We will loop through the existing Footnote // to retrieve the highest Id. foreach (var fn in fpart.Footnotes.Elements <Footnote>()) { if (fn.Id.HasValue && fn.Id > footnotesRef) { footnotesRef = (int)fn.Id.Value; } } footnotesRef++; } Run markerRun; Paragraph p; fpart.Footnotes.Append( new Footnote( p = new Paragraph( new ParagraphProperties { ParagraphStyleId = new ParagraphStyleId() { Val = htmlStyles.GetStyle("FootnoteText", StyleValues.Paragraph) } }, markerRun = new Run( new RunProperties { RunStyle = new RunStyle() { Val = htmlStyles.GetStyle("FootnoteReference", StyleValues.Character) } }, new FootnoteReferenceMark()), new Run( // Word insert automatically a space before the definition to separate the // reference number with its description new Text(" ") { Space = SpaceProcessingModeValues.Preserve }) ) ) { Id = footnotesRef }); // Description in footnote reference can be plain text or a web protocols/file share (like \\server01) Uri uriReference; Regex linkRegex = new Regex(@"^((https?|ftps?|mailto|file)://|[\\]{2})(?:[\w][\w.-]?)"); if (linkRegex.IsMatch(description) && Uri.TryCreate(description, UriKind.Absolute, out uriReference)) { // when URI references a network server (ex: \\server01), System.IO.Packaging is not resolving the correct URI and this leads // to a bad-formed XML not recognized by Word. To enforce the "original URI", a fresh new instance must be created uriReference = new Uri(uriReference.AbsoluteUri, UriKind.Absolute); HyperlinkRelationship extLink = fpart.AddHyperlinkRelationship(uriReference, true); var h = new Hyperlink( ) { History = true, Id = extLink.Id }; h.Append(new Run( new RunProperties { RunStyle = new RunStyle() { Val = htmlStyles.GetStyle("Hyperlink", StyleValues.Character) } }, new Text(description))); p.Append(h); } else { p.Append(new Run( new Text(description) { Space = SpaceProcessingModeValues.Preserve })); } fpart.Footnotes.Save(); return(footnotesRef); }
private OpenXmlElement Process(XmlReader xmlReader, OpenXmlElement current) { Paragraph cPara = current as Paragraph; Run cRun = current as Run; Hyperlink cHyperlink = current as Hyperlink; Table cTable = current as Table; TableRow cTableRow = current as TableRow; TableCell cTableCell = current as TableCell; if (xmlReader.NodeType == XmlNodeType.Element) { // Do something for elements switch (xmlReader.Name) { case "p": if (cPara != null) { break; } Paragraph newParagraph = new Paragraph( new ParagraphProperties( new ParagraphStyleId() { Val = Properties.Settings.Default.TemplateDescriptionStyle })); return(NewChild(current, newParagraph)); case "b": if (cPara != null) { Run newRun = new Run(); AddBoldToRun(newRun); return(NewChild(current, newRun)); } else if (cRun != null) { AddBoldToRun(cRun); return(cRun); } break; case "i": if (cPara != null) { Run newRun = new Run(); AddItalicsToRun(newRun); return(NewChild(current, newRun)); } else if (cRun != null) { AddItalicsToRun(cRun); return(cRun); } break; case "a": string hrefAttr = xmlReader.GetAttribute("href"); Hyperlink newHyperlink = new Hyperlink( new ProofError() { Type = ProofingErrorValues.GrammarStart }); if (!string.IsNullOrEmpty(hrefAttr)) { Template foundTemplate = null; if (hrefAttr.StartsWith("#") && hrefAttr.Length > 1) { foundTemplate = this.tdb.Templates.SingleOrDefault(y => y.Oid == hrefAttr.Substring(1)); } if (foundTemplate != null) { newHyperlink.Anchor = foundTemplate.Bookmark; newHyperlink.Append( DocHelper.CreateRun( string.Format("{0} ({1})", foundTemplate.Name, foundTemplate.Oid))); } else { try { HyperlinkRelationship rel = mainPart.AddHyperlinkRelationship(new Uri(hrefAttr), true); newHyperlink.History = true; newHyperlink.Id = rel.Id; } catch { } } } if (cPara != null) { return(NewChild(current, newHyperlink)); } break; case "ul": this.currentListLevel++; this.currentListStyle = "ListBullet"; if (current is Paragraph) { current = current.Parent; } break; case "ol": this.currentListLevel++; this.currentListStyle = "ListNumber"; if (current is Paragraph) { current = current.Parent; } break; case "li": Paragraph bulletPara = new Paragraph( new ParagraphProperties( new ParagraphStyleId() { Val = this.currentListStyle })); return(NewChild(current, bulletPara)); case "table": Table newTable = new Table( new TableProperties(), new TableGrid()); return(NewChild(current, newTable)); case "thead": this.currentIsTableHeader = true; break; case "tr": if (cTable != null) { TableRow newTableRow = new TableRow(); if (this.currentIsTableHeader) { newTableRow.Append( new TableRowProperties( new CantSplit(), new TableHeader())); } return(NewChild(current, newTableRow)); } break; case "td": if (cTableRow != null) { TableCell newCell = new TableCell(); if (this.currentIsTableHeader) { newCell.Append( new TableCellProperties() { Shading = new Shading() { Val = new EnumValue <ShadingPatternValues>(ShadingPatternValues.Clear), Color = new StringValue("auto"), Fill = new StringValue("E6E6E6") } }); } // Cells' contents should be within a paragraph Paragraph newPara = new Paragraph(); newCell.AppendChild(newPara); current.Append(newCell); return(newPara); } break; case "span": if (cPara != null) { Run newRun = new Run(); return(NewChild(current, newRun)); } break; case "root": case "tbody": break; default: throw new Exception("Unsupported wiki syntax"); } } else if (xmlReader.NodeType == XmlNodeType.Text) { string text = xmlReader.Value .Replace(" ", " "); if (current is Paragraph || current is TableCell) { current.Append(DocHelper.CreateRun(text)); } else if (cHyperlink != null) { if (!(cHyperlink.LastChild is Run)) { cHyperlink.Append(DocHelper.CreateRun(text)); } } else if (cRun != null) { cRun.Append(new Text(text)); } } else if (xmlReader.NodeType == XmlNodeType.EndElement) { if (xmlReader.Name == "thead") { this.currentIsTableHeader = false; return(current); } else if (xmlReader.Name == "tbody") { return(current); } else if (xmlReader.Name == "td") { // Expect that we are in a paragraph within a table cell, and when TD ends, we need to return two levels higher if (cPara != null && cPara.Parent is TableCell) { return(current.Parent.Parent); } } else if (xmlReader.Name == "a") { // Make sure all runs within a hyperlink have the correct style foreach (var cChildRun in current.ChildElements.OfType <Run>()) { cChildRun.RunProperties.RunStyle = new RunStyle() { Val = Properties.Settings.Default.LinkStyle }; } } else if (xmlReader.Name == "ul") { this.currentListLevel--; } if (current.Parent == null) { return(current); } return(current.Parent); } return(current); }
// prohibit // - altChunk // - subDoc // - contentPart // This strips all text nodes from the XML tree, thereby leaving only the structure. private static object CloneBlockLevelContentForHashing( OpenXmlPart mainDocumentPart, XNode node, bool includeRelatedParts, WmlComparerSettings settings) { if (node is XElement element) { if (element.Name == W.bookmarkStart || element.Name == W.bookmarkEnd || element.Name == W.pPr || element.Name == W.rPr) { return(null); } if (element.Name == W.p) { var clonedPara = new XElement(element.Name, element.Attributes().Where(a => a.Name != W.rsid && a.Name != W.rsidDel && a.Name != W.rsidP && a.Name != W.rsidR && a.Name != W.rsidRDefault && a.Name != W.rsidRPr && a.Name != W.rsidSect && a.Name != W.rsidTr && a.Name.Namespace != PtOpenXml.pt), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); IEnumerable <IGrouping <bool, XElement> > groupedRuns = clonedPara .Elements() .GroupAdjacent(e => e.Name == W.r && e.Elements().Count() == 1 && e.Element(W.t) != null); var clonedParaWithGroupedRuns = new XElement(element.Name, groupedRuns.Select(g => { if (g.Key) { string text = g.Select(t => t.Value).StringConcatenate(); if (settings.CaseInsensitive) { text = text.ToUpper(settings.CultureInfo); } var newRun = (object)new XElement(W.r, new XElement(W.t, text)); return(newRun); } return(g); })); return(clonedParaWithGroupedRuns); } if (element.Name == W.r) { IEnumerable <XElement> clonedRuns = element .Elements() .Where(e => e.Name != W.rPr) .Select(rc => new XElement(W.r, CloneBlockLevelContentForHashing(mainDocumentPart, rc, includeRelatedParts, settings))); return(clonedRuns); } if (element.Name == W.tbl) { var clonedTable = new XElement(W.tbl, element.Elements(W.tr).Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(clonedTable); } if (element.Name == W.tr) { var clonedRow = new XElement(W.tr, element.Elements(W.tc).Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(clonedRow); } if (element.Name == W.tc) { var clonedCell = new XElement(W.tc, element.Elements().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(clonedCell); } if (element.Name == W.tcPr) { var clonedCellProps = new XElement(W.tcPr, element.Elements(W.gridSpan).Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(clonedCellProps); } if (element.Name == W.gridSpan) { var clonedGridSpan = new XElement(W.gridSpan, new XAttribute("val", (string)element.Attribute(W.val))); return(clonedGridSpan); } if (element.Name == W.txbxContent) { var clonedTextbox = new XElement(W.txbxContent, element.Elements().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(clonedTextbox); } if (includeRelatedParts) { if (ComparisonUnitWord.ElementsWithRelationshipIds.Contains(element.Name)) { var newElement = new XElement(element.Name, element.Attributes() .Where(a => a.Name.Namespace != PtOpenXml.pt) .Where(a => !AttributesToTrimWhenCloning.Contains(a.Name)) .Select(a => { if (!ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name)) { return(a); } var rId = (string)a; // could be an hyperlink relationship try { OpenXmlPart oxp = mainDocumentPart.GetPartById(rId); if (oxp == null) { throw new FileFormatException("Invalid WordprocessingML Document"); } var anno = oxp.Annotation <PartSHA1HashAnnotation>(); if (anno != null) { return(new XAttribute(a.Name, anno.Hash)); } if (!oxp.ContentType.EndsWith("xml")) { using (Stream str = oxp.GetStream()) { byte[] ba; using (var br = new BinaryReader(str)) { ba = br.ReadBytes((int)str.Length); } string sha1 = WmlComparerUtil.SHA1HashStringForByteArray(ba); oxp.AddAnnotation(new PartSHA1HashAnnotation(sha1)); return(new XAttribute(a.Name, sha1)); } } } catch (ArgumentOutOfRangeException) { HyperlinkRelationship hr = mainDocumentPart.HyperlinkRelationships.FirstOrDefault(z => z.Id == rId); if (hr != null) { string str = hr.Uri.ToString(); return(new XAttribute(a.Name, str)); } // could be an external relationship ExternalRelationship er = mainDocumentPart.ExternalRelationships.FirstOrDefault(z => z.Id == rId); if (er != null) { string str = er.Uri.ToString(); return(new XAttribute(a.Name, str)); } return(new XAttribute(a.Name, "NULL Relationship")); } return(null); }), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(newElement); } } if (element.Name == VML.shape) { return(new XElement(element.Name, element.Attributes() .Where(a => a.Name.Namespace != PtOpenXml.pt) .Where(a => a.Name != "style" && a.Name != "id" && a.Name != "type"), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)))); } if (element.Name == O.OLEObject) { var o = new XElement(element.Name, element.Attributes() .Where(a => a.Name.Namespace != PtOpenXml.pt) .Where(a => a.Name != "ObjectID" && a.Name != R.id), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(o); } if (element.Name == W._object) { var o = new XElement(element.Name, element.Attributes() .Where(a => a.Name.Namespace != PtOpenXml.pt), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings))); return(o); } if (element.Name == WP.docPr) { return(new XElement(element.Name, element.Attributes() .Where(a => a.Name.Namespace != PtOpenXml.pt && a.Name != "id"), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)))); } return(new XElement(element.Name, element.Attributes() .Where(a => a.Name.Namespace != PtOpenXml.pt) .Where(a => !AttributesToTrimWhenCloning.Contains(a.Name)), element.Nodes().Select(n => CloneBlockLevelContentForHashing(mainDocumentPart, n, includeRelatedParts, settings)))); } if (settings.CaseInsensitive) { if (node is XText xt) { string newText = xt.Value.ToUpper(settings.CultureInfo); return(new XText(newText)); } } return(node); }
private string CleanupXml(string xmlContent) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlContent); XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable); nsManager.AddNamespace("w", OpenXmlWordProcessingNamespace); nsManager.AddNamespace("a", OpenXmlDrawingMLNamespace); nsManager.AddNamespace("r", OpenXmlRelationshipsNamespace); nsManager.AddNamespace("pic", OpenXmlPictureNamespace); nsManager.AddNamespace("wp", OpenXmlWordProcessingDrawingNamespace); var hyperlinkNodes = xmlDoc.SelectNodes("//w:hyperlink", nsManager); var drawingNodes = xmlDoc.SelectNodes("//w:drawing", nsManager); var numberIdNodes = xmlDoc.SelectNodes("//w:pPr/w:numPr/w:numId[@val]", nsManager); int numberIdCount = 0; // Ensure that all number ids are unique in the OpenXml document foreach (XmlElement numberIdNode in numberIdNodes) { //var numberingPart = this.mainPart.NumberingDefinitionsPart; var nextNumberId = this.mainPart.Document .Descendants <NumberingId>() .Select(y => y.Val.HasValue ? y.Val.Value : 0) .DefaultIfEmpty() .Max() + (numberIdCount++); numberIdNode.Attributes["val"].Value = nextNumberId.ToString(); } // Ensure that hyperlinks have a HyperlinkRelationship created for them // and the id of the relationship is set on the w:hyperlink element foreach (XmlElement hyperlinkNode in hyperlinkNodes) { XmlComment hrefCommentNode = hyperlinkNode.PreviousSibling as XmlComment; if (hrefCommentNode == null) { continue; } string href = hrefCommentNode.Value; HyperlinkRelationship rel = this.mainPart.AddHyperlinkRelationship(new Uri(href), true); XmlAttribute idAttr = xmlDoc.CreateAttribute("id", OpenXmlRelationshipsNamespace); idAttr.Value = rel.Id; hyperlinkNode.Attributes.Append(idAttr); } // Ensure that image data has been added to the document, an id has been created // for the image, the image's filename has been set, and the width and height are set appropriately foreach (XmlElement drawingNode in drawingNodes) { XmlComment srcCommentNode = drawingNode.PreviousSibling as XmlComment; if (srcCommentNode == null) { throw new Exception("Expected transformed OpenXml w:drawing to have a comment preceding it representing the src of the image"); } if (this.igImageRegex.IsMatch(srcCommentNode.Value)) { var match = this.igImageRegex.Match(srcCommentNode.Value); int implementationGuideId = Int32.Parse(match.Groups[1].Value); string fileName = match.Groups[2].Value; var file = this.tdb.ImplementationGuideFiles.SingleOrDefault(y => y.ImplementationGuideId == implementationGuideId && y.FileName.ToLower() == fileName.ToLower()); if (file == null) { continue; } string imageExtension = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1); var latestVersion = file.GetLatestData(); ImagePart newImagePart = this.mainPart.AddImagePart(this.GetImagePartType(imageExtension)); int docImageWidth = 0; int docImageHeight = 0; using (MemoryStream ms = new MemoryStream(latestVersion.Data)) { newImagePart.FeedData(ms); } using (MemoryStream ms = new MemoryStream(latestVersion.Data)) { System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(ms); docImageWidth = (int)Math.Round((decimal)bitmap.Width * 9525); docImageHeight = (int)Math.Round((decimal)bitmap.Height * 9525); } // Set the id of the image to the id of the relationship part XmlAttribute embedAttr = (XmlAttribute)drawingNode.SelectSingleNode("//a:blip/@r:embed", nsManager); embedAttr.Value = this.mainPart.GetIdOfPart(newImagePart); XmlAttribute nameAttr = (XmlAttribute)drawingNode.SelectSingleNode("//pic:nvPicPr/pic:cNvPr/@name", nsManager); nameAttr.Value = file.FileName; XmlAttribute extentWidthAttribute = (XmlAttribute)drawingNode.SelectSingleNode("//wp:inline/wp:extent/@cx", nsManager); extentWidthAttribute.Value = docImageWidth.ToString(); XmlAttribute extentHeightAttribute = (XmlAttribute)drawingNode.SelectSingleNode("//wp:inline/wp:extent/@cy", nsManager); extentHeightAttribute.Value = docImageHeight.ToString(); } else { // We don't yet support external images continue; } } return(xmlDoc.OuterXml); }
public override void Parse() { StringBuilder hyperlinkText = null; string hyperlinkRelationshipId = string.Empty; try { byte[] fileByteArray = Utility.GetFileByteArray(FileUrl); if (fileByteArray != null) { using (MemoryStream fileStream = new MemoryStream(fileByteArray, false)) { using (WordprocessingDocument doc = WordprocessingDocument.Open(fileStream, false)) { Document mainDocument = doc.MainDocumentPart.Document; // Iterate through the hyperlink elements in the // main document part. foreach (DocumentFormat.OpenXml.Wordprocessing.Hyperlink hyperlink in mainDocument.Descendants <DocumentFormat.OpenXml.Wordprocessing.Hyperlink>()) { if (hyperlink.Id != null) { hyperlinkText = new StringBuilder(); // Get the text in the document that is associated // with the hyperlink. The text could be spread across // multiple text elements so process all the text // elements that are descendants of the hyperlink element. foreach (DocumentFormat.OpenXml.Wordprocessing.Text text in hyperlink.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>()) { hyperlinkText.Append(text.InnerText); } // The hyperlink element has an explicit relationship // with the actual hyperlink. Get the relationship id // via the hyperlink element's Id attribute. hyperlinkRelationshipId = hyperlink.Id.Value; // Get the hyperlink uri via the explicit relationship Id. HyperlinkRelationship hyperlinkRelationship = doc .MainDocumentPart.HyperlinkRelationships .Single(c => c.Id == hyperlinkRelationshipId); if (hyperlinkRelationship != null && hyperlinkRelationship.IsExternal) { if (hyperlinkRelationship.Uri.IsAbsoluteUri == false) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = hyperlinkText.ToString(), LinkAddress = hyperlinkRelationship.Uri.OriginalString, hasError = true }; Results.Add(objLink); } else { if (hyperlinkRelationship.Uri.Scheme != Uri.UriSchemeMailto) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = hyperlinkText.ToString(), LinkAddress = hyperlinkRelationship.Uri.AbsoluteUri }; Results.Add(objLink); } } } } } } } } } catch (Exception ex) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = "Error occurred when parsing this file.", LinkAddress = ex.Message, hasError = true }; Results.Add(objLink); } }
public override void Parse() { string hyperlinkText = string.Empty; string hyperlinkRelationshipId; try { byte[] fileByteArray = Utility.GetFileByteArray(FileUrl); if (fileByteArray != null) { using (MemoryStream fileStream = new MemoryStream(fileByteArray, false)) { using (PresentationDocument document = PresentationDocument.Open(fileStream, false)) { // Iterate through all the slide parts in the presentation part. foreach (SlidePart slidePart in document.PresentationPart.SlideParts) { IEnumerable <DocumentFormat.OpenXml.Drawing.HyperlinkType> links = slidePart.Slide.Descendants <DocumentFormat.OpenXml.Drawing.HyperlinkType>(); // Iterate through all the links in the slide part. foreach (DocumentFormat.OpenXml.Drawing.HyperlinkType hyperlink in links) { if (hyperlink.Id != null) { hyperlinkText = Utility.GetPPTHyperlinkText(hyperlink); hyperlinkRelationshipId = hyperlink.Id.Value; HyperlinkRelationship hyperlinkRelationship = slidePart .HyperlinkRelationships .Single(c => c.Id == hyperlinkRelationshipId); if (hyperlinkRelationship != null && hyperlinkRelationship.IsExternal) { if (hyperlinkRelationship.Uri.IsAbsoluteUri == false) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = hyperlinkText, LinkAddress = hyperlinkRelationship.Uri.OriginalString, hasError = true }; Results.Add(objLink); } else { if (hyperlinkRelationship.Uri.Scheme != Uri.UriSchemeMailto) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = hyperlinkText, LinkAddress = hyperlinkRelationship.Uri.AbsoluteUri }; Results.Add(objLink); } } } } } } } } } } catch (Exception ex) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = "Error occurred when parsing this file.", LinkAddress = ex.Message, hasError = true }; Results.Add(objLink); } }