Hello All,
I need to how to add a rich text to a bookmark.Please send the sample code in Vb.net
Hi Sreejesh,
Thank you for contacting support. Could you please share your platform and information about input/output file formats? It will help us to guide you accordingly.
Hi,
I am using ASP.NET
and vb for development.Currently I am assigning a bookmark to a richtext field in the Webform.After exporting I need to make some track changes in Richtext field in the word document.Then I need to import it back to my application.I can see the text changes in the form when I use
Div_something.innerHtml=bookmark1.text
But what I wanted is word changes with formatting
ie : If I change font size big or bold
I tried to get bookmarks.html that is exactly what I wanted
here is the importing code snippet in vb.net
Dim document As New Document(paths)
If (ValidateFile(document)) Then
Dim bmRecommendation As Bookmark = document.Range.Bookmarks("bmRecommendation")
div_Recommendation.InnerHtml = bmRecommendation.Text
thanks
sreejesh
Hi ,
This input file is html string,In this html string I have added bookmark .
The overall risk is increased to 3. The impact rating
and the overall rating have been increased by one rating level, based on the inherent risk of the additional activity and a heightened
We have not found any adverse development in
systems and controls, or governance.
After exporting and changing the format I can only retrieve the string and not formatting .
div.innerHtml=bookmark1.text
My output string below:
The overall risk is increased to 3. The impact rating and the overall rating have been increased by one rating level, based on the inherent risk of the additional activity and a heightened evaluation of the reputational impact that the firm might have on the DIFC. We have not found any adverse development in systems and controls, or governance. Dgdfgdfg fdgdfgdfaaaa
Hi Sreejesh,
Thanks for your inquiry. Yes, you can insert RTF contents at the position of bookmark by using Aspose.Words. Please note that bookmark is imported from element. Bookmark start and end appear in the same position. Please check the following code example to insert the RTF contents at the position of bookmark.
Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
Document rtfDoc = RtfStringToDocument(" rtf contents…");
builder.MoveToBookmark("bookmark name ");
InsertDocument(builder.CurrentParagraph, rtfDoc);
doc.Save(MyDir + "Out.docx");
private static Document RtfStringToDocument(string rtf)
{
Document doc = null;
// Convert RTF string to byte array.
byte[] rtfBytes = Encoding.UTF8.GetBytes(rtf);
// Create stream.
using (MemoryStream rtfStream = new MemoryStream(rtfBytes))
{
// Open document from stream.
doc = new Document(rtfStream);
}
return doc;
}
Please check the code of insertDocument method from here:
https://docs.aspose.com/words/java/insert-and-append-documents/
Following code example shows how to use insertDocument method. Hope this helps you. Please let us know if you have any more
queries.
It would be great if you please share following detail here for our reference. We will then provide you more information on this along with code.
Please attach your input HTML document.
Please
attach your target Word document showing the desired behavior. You can
use Microsoft Word to create your target Word document. I will
investigate as to how you are expecting your final document be generated
like.
milkseal:
Currently I am assigning a bookmark to a richtext field in the Webform.After exporting I need to make some track changes in Richtext field in the word document.Then I need to import it back to my application.I can see the text changes in the form when I use
It would be great if you please share some more detail about this query. We will then provide you more information on this along with code.
Thanks for reply Tahir.
I will tell you in details :
I have a formatted text in the aspose document Like “AMERICA”.
and I am setting the bookmark “BM1” in that “America” field. when I import the document I need to read the bookmark text with formatting and need to display in a div or editor. currently i can convert it into rtf .Does any method there in which we can read the formatted Text from Aspose word? or any method which can be used for converting rtf to html .
Please check my code :
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim document As New Document("C:\sreejesh\aspose_test.doc")
Dim bmnew As Bookmark = document.Range.Bookmarks("BM1")
Dim boomarktext As String
boomarktext = bmnew.Text
Dim _rtf As String = GetRtfString(boomarktext)
'displaying it in the content editor
RadEditor1.Content = _rtf
End Sub
Private Shared Function GetRtfString(html As String) As String
Dim rtfString As String = ""
Dim builder As New DocumentBuilder()
builder.InsertHtml(html)
Using rtfStream As New MemoryStream()
builder.Document.Save(rtfStream, SaveFormat.Rtf)
Dim rtfBytes As Byte() = rtfStream.ToArray()
rtfString = Encoding.UTF8.GetString(rtfBytes)
End Using
Return rtfString
End Function
HI ,
what I needed is simple :
div_something.innerHtml=bookmark1.html ()
not “bookmark.Text.”… It only gives Text not formatting
thanks
sreejesh
Hi Sreejesh,
Thanks for your inquiry.
milkseal:
what I needed is simple :
div_something.innerHtml=bookmark1.html ()
not “bookmark.Text.”… It only gives Text not formatting
I have a formatted text in the aspose document Like “AMERICA”.
and
I am setting the bookmark “BM1” in that “America” field. when I import
the document I need to read the bookmark text with formatting and need
to display in a div or editor. currently i can convert it into rtf .Does
any method there in which we can read the formatted Text from Aspose
word? or any method which can be used for converting rtf to html .
The Bookmark.Text property gets the text
enclosed in the bookmark without formatting. If you want to get the
formatted text inside a bookmark, please extract the content from a
bookmark using the code shared in following documentation link:
https://docs.aspose.com/words/net/how-to-extract-selected-content-between-nodes-in-a-document/
If you face any issue, please share following detail for investigation purposes.
Please attach your input Word document.
Please attach the output document that shows the undesired behavior.
Please
attach your target document showing the desired behavior.
HI aspose team,
I have extracted the content between BookmarkStart and bookmarkEnd …I needed the content as html string …Is there any method there ??
I need the extracted content to bind in a div
Here is my code
’ We use the BookmarkStart and BookmarkEnd nodes as markers.
Dim bookmarkStart As BookmarkStart = bmRecommendation.BookmarkStart
Dim bookmarkEnd As BookmarkEnd = bmRecommendation.BookmarkEnd
’ Firstly extract the content between these nodes including the bookmark.
Dim extractedNodesInclusive As ArrayList = ExtractContent(bookmarkStart, bookmarkEnd, True)
Dim dstDoc As Document = GenerateDocument(document, extractedNodesInclusive)
’ Secondly extract the content between these nodes this time without including the bookmark.
Dim extractedNodesExclusive As ArrayList = ExtractContent(bookmarkStart, bookmarkEnd, False)
dstDoc = GenerateDocument(document, extractedNodesExclusive)
Div_Recommendation.InnerHtml = ???
Thanks
sreejesh
Thanks …I found out another way to load html to div
Thanks for your support
Hi all,
I set a bookmark in table which is placed inside a parent table.
builder.InsertHtml(html)
builder.MoveToCell(1, 0, 0, 0)
builder.StartBookmark("bmRecommendation")
builder.MoveToCell(1, 0, 1, 0)
builder.EndBookmark("bmRecommendation")
I can see the bookmark .text which is same as the table content in which I have assigned.But while extracting the content between the bookmark it showing another content in the parent table .Is it any problem of assigning bookmarkend?
thanks
Hi Sreejesh,
Thanks for your inquiry.
milkseal:
…I needed the content as html string …Is there any method there ??
I need the extracted content to bind in a div
Here is my code
…
…
Dim extractedNodesExclusive As ArrayList = ExtractContent(bookmarkStart, bookmarkEnd, False)
dstDoc = GenerateDocument(document, extractedNodesExclusive)
dstDoc.Save(“Out.html”)
Div_Recommendation.InnerHtml = ???
Please use the Document.Save method to convert extracted contents into HTML.
milkseal:
I can see the bookmark .text which is same as the table content in which I have assigned.But while extracting the content between the bookmark it showing another content in the parent table .Is it any problem of assigning bookmarkend?
Unfortunately,
it is difficult to say what the problem is without the Document(s) and
simplified application. We need your Document(s) and simple project to
reproduce the problem. As soon as you get these pieces of information to
us we’ll start our investigation into your issue.
Hi Tahir,
I have set bookmark start and end on a cell content.I am using the Aspose Extracting method for extracting the content between the bookmarks.But my resulting content are different from the content that I have assigned bookmark.It showing another content of a cell.why ?
In the processMarker Method I can see the node start which is starting from my bookmark .But after exit of this loop it showing another content .So I am doubt about this section.
' If either marker is part of a comment then to include the comment itself we need to move the pointer forward to the Comment
' node found after the CommentRangeEnd node.
If node.NodeType = NodeType.CommentRangeEnd Then
Do While node.NextSibling IsNot Nothing AndAlso node.NodeType <> NodeType.Comment
node = node.NextSibling
Loop
End If
' Find the corresponding node in our cloned node by index and return it.
' If the start and end node are the same some child nodes might already have been removed. Subtract the
' difference to get the right index.
Dim indexDiff As Integer = node.ParentNode.ChildNodes.Count - cloneNode.ChildNodes.Count
' Child node count identical.
If indexDiff = 0 Then
node = cloneNode.ChildNodes(node.ParentNode.IndexOf(node))
Else
node = cloneNode.ChildNodes(node.ParentNode.IndexOf(node) - indexDiff)
End If
Here is my html and all method code:
Public Shared Function GenerateDocument(ByVal srcDoc As Document, ByVal nodes As ArrayList) As Document
' Create a blank document.
Dim dstDoc As New Document()
' Remove the first paragraph from the empty document.
dstDoc.FirstSection.Body.RemoveAllChildren()
' Import each node from the list into the new document. Keep the original formatting of the node.
Dim importer As New NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting)
For Each node As Node In nodes
Dim importNode As Node = importer.ImportNode(node, True)
dstDoc.FirstSection.Body.AppendChild(importNode)
Next node
' Return the generated document.
Return dstDoc
End Function
Public Shared Function ExtractContent(ByVal startNode As Node, ByVal endNode As Node, ByVal isInclusive As Boolean) As ArrayList
' First check that the nodes passed to this method are valid for use.
VerifyParameterNodes(startNode, endNode)
' Create a list to store the extracted nodes.s
Dim nodes As New ArrayList()
' Keep a record of the original nodes passed to this method so we can split marker nodes if needed.
Dim originalStartNode As Node = startNode
Dim originalEndNode As Node = endNode
' Extract content based on block level nodes (paragraphs and tables). Traverse through parent nodes to find them.
' We will split the content of first and last nodes depending if the marker nodes are inline
Do While startNode.ParentNode.NodeType <> NodeType.Body
startNode = startNode.ParentNode
Loop
Do While endNode.ParentNode.NodeType <> NodeType.Body
endNode = endNode.ParentNode
Loop
Dim isExtracting As Boolean = True
Dim isStartingNode As Boolean = True
Dim isEndingNode As Boolean = False
' The current node we are extracting from the document.
Dim currNode As Node = startNode
' Begin extracting content. Process all block level nodes and specifically split the first and last nodes when needed so paragraph formatting is retained.
' Method is little more complex than a regular extractor as we need to factor in extracting using inline nodes, fields, bookmarks etc as to make it really useful.
Do While isExtracting
' Clone the current node and its children to obtain a copy.i
Dim cloneNode As CompositeNode = CType(currNode.Clone(True), CompositeNode)
isEndingNode = currNode.Equals(endNode)
If isStartingNode OrElse isEndingNode Then
' We need to process each marker separately so pass it off to a separate method instead.
If isStartingNode Then
ProcessMarker(cloneNode, nodes, originalStartNode, isInclusive, isStartingNode, isEndingNode)
isStartingNode = False
End If
' Conditional needs to be separate as the block level start and end markers maybe the same node.
If isEndingNode Then
ProcessMarker(cloneNode, nodes, originalEndNode, isInclusive, isStartingNode, isEndingNode)
isExtracting = False
End If
Else
' Node is not a start or end marker, simply add the copy to the list.
nodes.Add(cloneNode)
End If
' Move to the next node and extract it. If next node is null that means the rest of the content is found in a different section.
If currNode.NextSibling Is Nothing AndAlso isExtracting Then
' Move to the next section.
Dim nextSection As Section = CType(currNode.GetAncestor(NodeType.Section).NextSibling, Section)
currNode = nextSection.Body.FirstChild
Else
' Move to the next node in the body.
currNode = currNode.NextSibling
End If
Loop
' Return the nodes between the node markers.
Return nodes
End Function
Private Shared Sub ProcessMarker(ByVal cloneNode As CompositeNode, ByVal nodes As ArrayList, ByVal node As Node, ByVal isInclusive As Boolean, ByVal isStartMarker As Boolean, ByVal isEndMarker As Boolean)
' If we are dealing with a block level node just see if it should be included and add it to the list.
If (Not IsInline(node)) Then
' Don't add the node twice if the markers are the same node
If Not (isStartMarker AndAlso isEndMarker) Then
If isInclusive Then
nodes.Add(cloneNode)
End If
End If
Return
End If
' If a marker is a FieldStart node check if it's to be included or not.
' We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph.
If node.NodeType = NodeType.FieldStart Then
' If the marker is a start node and is not be included then skip to the end of the field.
' If the marker is an end node and it is to be included then move to the end field so the field will not be removed.
If (isStartMarker AndAlso (Not isInclusive)) OrElse ((Not isStartMarker) AndAlso isInclusive) Then
Do While node.NextSibling IsNot Nothing AndAlso node.NodeType <> NodeType.FieldEnd
node = node.NextSibling
Loop
End If
End If
' If either marker is part of a comment then to include the comment itself we need to move the pointer forward to the Comment
' node found after the CommentRangeEnd node.
If node.NodeType = NodeType.CommentRangeEnd Then
Do While node.NextSibling IsNot Nothing AndAlso node.NodeType <> NodeType.Comment
node = node.NextSibling
Loop
End If
' Find the corresponding node in our cloned node by index and return it.
' If the start and end node are the same some child nodes might already have been removed. Subtract the
' difference to get the right index.
Dim indexDiff As Integer = node.ParentNode.ChildNodes.Count - cloneNode.ChildNodes.Count
' Child node count identical.
If indexDiff = 0 Then
node = cloneNode.ChildNodes(node.ParentNode.IndexOf(node))
Else
node = cloneNode.ChildNodes(node.ParentNode.IndexOf(node) - indexDiff)
End If
' Remove the nodes up to/from the marker.
Dim isSkip As Boolean = False
Dim isProcessing As Boolean = True
Dim isRemoving As Boolean = isStartMarker
Dim nextNode As Node = cloneNode.FirstChild
Do While isProcessing AndAlso nextNode IsNot Nothing
Dim currentNode As Node = nextNode
isSkip = False
If currentNode.Equals(node) Then
If isStartMarker Then
isProcessing = False
If isInclusive Then
isRemoving = False
End If
Else
isRemoving = True
If isInclusive Then
isSkip = True
End If
End If
End If
nextNode = nextNode.NextSibling
If isRemoving AndAlso (Not isSkip) Then
currentNode.Remove()
End If
Loop
' After processing the composite node may become empty. If it has don't include it.
If Not (isStartMarker AndAlso isEndMarker) Then
If cloneNode.HasChildNodes Then
nodes.Add(cloneNode)
End If
End If
End Sub
Private Shared Sub VerifyParameterNodes(ByVal startNode As Node, ByVal endNode As Node)
' The order in which these checks are done is important.
If startNode Is Nothing Then
Throw New ArgumentException("Start node cannot be null")
End If
If endNode Is Nothing Then
Throw New ArgumentException("End node cannot be null")
End If
If (Not startNode.Document.Equals(endNode.Document)) Then
Throw New ArgumentException("Start node and end node must belong to the same document")
End If
If startNode.GetAncestor(NodeType.Body) Is Nothing OrElse endNode.GetAncestor(NodeType.Body) Is Nothing Then
Throw New ArgumentException("Start node and end node must be a child or descendant of a body")
End If
' Check the end node is after the start node in the DOM tree
' First check if they are in different sections, then if they're not check their position in the body of the same section they are in.
Dim startSection As Section = CType(startNode.GetAncestor(NodeType.Section), Section)
Dim endSection As Section = CType(endNode.GetAncestor(NodeType.Section), Section)
Dim startIndex As Integer = startSection.ParentNode.IndexOf(startSection)
Dim endIndex As Integer = endSection.ParentNode.IndexOf(endSection)
If startIndex = endIndex Then
If startSection.Body.IndexOf(startNode) > endSection.Body.IndexOf(endNode) Then
Throw New ArgumentException("The end node must be after the start node in the body")
End If
ElseIf startIndex > endIndex Then
Throw New ArgumentException("The section of end node must be after the section start node")
End If
End Sub
'''
''' Checks if a node passed is an inline node.
'''
Private Shared Function IsInline(ByVal node As Node) As Boolean
' Test if the node is desendant of a Paragraph or Table node and also is not a paragraph or a table a paragraph inside a comment class which is decesant of a pararaph is possible.
Return ((node.GetAncestor(NodeType.Paragraph) IsNot Nothing OrElse node.GetAncestor(NodeType.Table) IsNot Nothing) AndAlso Not (node.NodeType = NodeType.Paragraph OrElse node.NodeType = NodeType.Table))
End Function
My importing code is below:
Protected Sub btn_import_Click(sender As Object, e As System.EventArgs) Handles btn_import.Click
Try
Dim paths = Server.MapPath("Document/" + FileUpload1.FileName)
Dim _fileName = FileUpload1.FileName
If (FileUpload1.HasFile) Then
FileUpload1.SaveAs(paths)
Dim document As New Document(paths)
If (ValidateFile(document)) Then
Dim bmRecommendation As Bookmark = document.Range.Bookmarks("bmRecommendation")
' We use the BookmarkStart and BookmarkEnd nodes as markers.
Dim bookmarkStart As BookmarkStart = bmRecommendation.BookmarkStart
Dim bookmarkEnd As BookmarkEnd = bmRecommendation.BookmarkEnd
Dim dstDoc As Document
' Firstly extract the content between these nodes including the bookmark.
Dim extractedNodesInclusive As ArrayList = ExtractContent(bookmarkStart, bookmarkEnd, True)
dstDoc = GenerateDocument(document, extractedNodesInclusive)
dstDoc.Save(paths + "BookmarkInclusive Out.html", SaveFormat.Html)
' Secondly extract the content between these nodes this time without including the bookmark.
Dim extractedNodesExclusive As ArrayList = ExtractContent(bookmarkStart, bookmarkEnd, False)
dstDoc = GenerateDocument(document, extractedNodesExclusive)
dstDoc.Save(paths + "BookmarkExclusive Out.html", SaveFormat.Html)
Dim resulthtml = GetHTML("http://localhost:61030/ProofOfConcept/Document/aspose.docBookmarkInclusive Out.html")
txt_Recommendation.InnerHtml = resulthtml
' txt_Recommendation.InnerHtml =
End If
End If
Catch ex As Exception
MsgBox(ex)
End Try
End Sub
Function GetHTML(ByVal strPage As String) As String
Dim strReply As String = "NULL"
Try
Dim objHttpRequest As System.Net.HttpWebRequest
Dim objHttpResponse As System.Net.HttpWebResponse
objHttpRequest = System.Net.HttpWebRequest.Create(strPage)
objHttpResponse = objHttpRequest.GetResponse
Dim objStrmReader As New StreamReader(objHttpResponse.GetResponseStream)
strReply = objStrmReader.ReadToEnd()
Catch ex As Exception
strReply = "ERROR! " + ex.Message.ToString
End Try
Return strReply
End Function
I need to import a document with bookmark assigned and extract content between bookmarkStart and bookmark end
Here is the bookmark assigning code :
In exporting button click code …
Dim builder As New DocumentBuilder(doc)
Dim html As String = String.Empty
Dim sb As New StringBuilder()
Dim tw As New StringWriter(sb)
Dim hw As New HtmlTextWriter(tw)
Page.RenderControl(hw)
html = sb.ToString()
Dim styles As String = readStyleSheet()
html = html.Replace(".temp{}", styles)
builder.InsertHtml(html)
builder.MoveToCell(1, 0, 0, 0)
builder.StartBookmark("bmRecommendation")
builder.MoveToCell(1, 0, 1, 0)
builder.EndBookmark("bmRecommendation")
builder.PageSetup.PaperSize = PaperSize.A4
builder.PageSetup.Orientation = Orientation.Landscape
doc = RemoveContentFromMergedCells(doc)
doc = FixRowBackground(doc)
doc = RepeatHeaderRow(doc)
Dim fileName As String = "aspose"
doc.Save(fileName + "." + SaveFormat.ToString(), SaveFormat, SaveType.OpenInApplication, Response)
Response.End()
I have used two table in the aspx page and one table is inside a tag I need a content from that .So the table index is 1
Please look at this…I am suspecting problems in Aspose extract method.
Thanks
sreejesh
Hi Sreejesh,
Thanks for sharing the code. To ensure a timely and accurate response please supply us with the following information, if you cannot supply us with this information we will not be able to investigate your issue and raise a ticket.
Please attach your input Word documents.
Please
create a standalone/runnable simple application (for example a Console
Application Project) that demonstrates the code (Aspose.Words code) you used to generate
your output document
Please attach the output document that shows the undesired behavior.
Please
attach your target document showing the desired behavior. You can
use Microsoft Word to create your target Word document. I will
investigate as to how you are expecting your final document be generated
like.
As soon as you get these pieces of information to
us we’ll start our investigation into your issue. We are really keen to help you but need some more details from your side.
Thank you Tahir for your immense support.My project is working well now.Your support help me a lot during development.One more question for you now.
Why aspose is showing “Evaluation Only. Created with Aspose.Words. Copyright 2003-2010 Aspose Pty Ltd.” while using extract method?
Thanks
sreejesh
Hi Sreejesh,
Thanks for your inquiry. Please note that in evaluation mode there are some limitations applied. E.g Aspose.Words injects an evaluation watermark at the top of the document. The document’s content are truncated after a certain number of paragraphs during import or export.
To
avoid this you can request a free 30-day trial license which removes
these evaluation restrictions. You can request this from here:
https://purchase.aspose.com/temporary-license
Please let us know if you have any more queries.
Why aspose is showing “Evaluation Only. Created with Aspose.Words. Copyright 2003-2010 Aspose Pty Ltd.” while using extract method?
Thanks
sreejesh
Hi Sreejesh,
Thanks for your inquiry. This is limitation of evaluation version. Evaluation version of
Aspose.Words injects an evaluation watermark at the top of the document
on open and save and limits the maximum document size to several hundred
paragraphs.
If
you want to test Aspose.Words without evaluation version limitations,
you can request a 30-Day Temporary License. See the following link for
more information:
https://purchase.aspose.com/temporary-license