Link ms word hyperlink to a place in the document - c#

While trying to create a ms word document programmaticly, i came across a problem:
I am trying to find (without success) a way to create a HyperLink or something else that will do the work, that will navigate the user to another place in the document
A place can be a bookmark or some other paragraph object i inserted before
In the word application, i select a text, right click, press hyperlink and point the link to a "place in the document"
I cant find a way to it in C#
help?

Beside adding a CrossReference, there is also the possibility to use hyperlink
although the hyperlink is said to link to web url's, it can also direct to you to in-document text by using it like this:
Microsoft.Office.Interop.Word.Paragraph oPara2;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Heading 2";
oPara2.Format.SpaceAfter = 6;
oPara2.Range.InsertParagraphAfter();
oDoc.Bookmarks.Add("BookmakrName3", oRng);
object oAddress = "#BookmakrName3";
//Add text after the chart.
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.InsertParagraphAfter();
wrdRng.InsertAfter("Click here to jump");
wrdRng.Hyperlinks.Add(wrdRng, ref oAddress);
Note that there is a '#' before the bookmark name in the address given.. this is the trick

If you want to do that more often with other Word documents, you might take a look at Latex, which can create very fast references inside your document, but generates a PDF instead. Now the question is, does your Word should still be editable later, if yes, then I would go for Ranger.InsertCrossReference.
Example about InsertCrossReference:
http://msdn.microsoft.com/fr-fr/library/microsoft.office.tools.word.bookmark.insertcrossreference.aspx
About what is latex.
http://fr.wikipedia.org/wiki/LaTeX
Here you can write online your latex document.
https://www.sharelatex.com/

Related

Reading a document from bottom

I have created a add-in for MS word. I have two buttons. Click on first move me forward by highlighting a range of words. On every second button click I want to go to the previous highlighted word. Can anybody help me in second button functionality. On button click one I have this code working fine.Now how to go the previously highlighted word range on every button2 click??
private void adxRibbonButton1_OnClick(object sender, IRibbonControl control, bool pressed)
{
object missing = System.Type.Missing;
Word.Document document = WordApp.ActiveDocument;
foreach(Word.Range docRange in document.Words)
{
if(docRange.HighlightColorIndex.Equals(Microsoft.Office.Interop.Word.WdColorIndex.wdRed))
{
docRange.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
docRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
break;
}
}
}
There's more than one way to approach this:
Use Word's built-in Find to search backwards in the document for the first instance of the changed highlighting.
Set two bookmarks, one for the current position of the code in the question and one for the previous position. The code sample below is for this variation.
string CurrentBkm = "_bkmCurrent";
string LastBkm= "_bkmLast";
if(docRange.HighlightColorIndex.Equals(Microsoft.Office.Interop.Word.WdColorIndex.wdRed))
{
docRange.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
docRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
if (document.Bookmarks.Exists(CurrentBkm))
{
document.Bookmarks.Add(LastBkm, document.Bookmarks[CurrentBkm].Range.Duplicate);
}
document.Bookmarks.Add(CurrentBkm, docRange);
break;
The code for button2 simply goes to the bookmark "_bkmLast":
string LastBkm= "_bkmLast";
document.Bookmarks[LastBkm].Range.Select();
Note that the bookmark name starts with an underscore _. This hides the bookmark in the Word UI so that it won't irritate the user in case the application settings show bookmark non-printing characters.
Note, also, that the code in the question could also work with Word's built-in Find functionality to search the formatting. This would almost certainly be more efficient than "walking" each word in the document and testing its highlight formatting. If you were to change your code to use Find the solution I provide with the bookmarks would still work.

Add MigraDoc Table of Contents to PDFsharp PDF

I am trying to use PDFsharp and MigraDoc to create a PDF report file from many other files.
Basically the workflow is as follows:
The user uploads 2 or more documents to concatenate
The user selects what pages they want to include in the TOC
The documents are concatenated together and a table of contents is generated
Now I am able to easily concatenate the documents and add bookmarks/outlines in PDFsharp. Where I have run into problems is when using MigraDoc to create the TOC referencing the PDFsharp created bookmarks/outlines as the targets of the hyperlinks.
Code to add bookmark/outline in PDFsharp (successfully adds the bookmarks):
// Current document is a PdfDocument and Title is the name of the bookmark
CurrentDocument.Outlines.Add(title, page, true, PdfOutlineStyle.Bold);
MigraDoc code to create the TOC page and render it to the current PDFsharp document:
// Create blank page
PdfPage page = (!hasTitlePage)
? AddPage(null, 0, TOC_BOOKMARK_TITLE) // Add to start
: AddPage(null, 1, TOC_BOOKMARK_TITLE); // Add after title page
// Get Graphics obj
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.MUH = PdfFontEncoding.Unicode;
// Create MigraDoc document + Setup styles
Document document = new Document();
DefineStyles(document);
// Add header
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph("Table of Contents");
paragraph.Format.Font.Size = 14;
paragraph.Format.Font.Bold = true;
paragraph.Format.SpaceAfter = 24;
paragraph.Format.OutlineLevel = OutlineLevel.Level1;
// Add links - these are the PdfSharp outlines/bookmarks added previously when concatinating the pages
foreach (var bookmark in CurrentDocument.Outlines)
{
paragraph = section.AddParagraph();
paragraph.Style = "TOC";
Hyperlink hyperlink = paragraph.AddHyperlink(bookmark.Title);
hyperlink.AddText($"{bookmark.Title}\t");
hyperlink.AddPageRefField(bookmark.Title);
}
// Render document
DocumentRenderer docRenderer = new DocumentRenderer(document);
docRenderer.PrepareDocument();
docRenderer.RenderPage(gfx, 1);
return page;
Note - the MigraDoc code adds the TOC page but it doesn't recognize the PDFsharp bookmarks.
Screenshot of the TOC:
The TOC page is added at the start (although the TOC bookmark is listed at the end) but I cannot link to PDFsharp bookmarks
I am certain that the issue is with my understanding of MigraDoc and/or PDFsharp.
First prize would be to only use PDFsharp to add the TOC. I would appreciate any help in being pointed in the right direction.
MigraDoc is a world of its own - it uses PDFsharp to create PDF files, but cannot access internals of PDF files creates with PDFsharp (like Bookmarks in your case).
One approach: create the TOC with PDFsharp (as you already suggested).
Other approach: use MigraDoc to add pages from existing PDF files to a MigraDoc document to create the final PDF (you can add pages from PDF files like you add images).
With the second approach you can use the formatting capabilities of MigraDoc for the TOC and MigraDoc will insert the correct page numbers, provided you add MigraDoc Bookmarks for every image (imported PDF page).
With the first approach, you will have to do the formatting and insert the page numbers yourself, but you'll have more control over the final PDF.
Which is the "best" approach? Depends a bit on the extent of formatting you need for your TOC. With the second approach the TOC can have two or more pages and MigraDoc will take care of that automatically and entries in the TOC can have two or more lines and MigraDoc will also take care of that automatically. But I think a hack will be needed to add the Outlines (e.g. draw very small white text with the outline text somewhere on the page).
Update: For the PDFsharp only approach, you will add links with code like this:
PdfRectangle prect = new PdfRectangle(gfx.Transformer.WorldToDefaultPage(rect));
page.AddDocumentLink(prect, 1);
The second parameter to AddDocumentLink is the target page.

How to search the text in WebBrowser Control

Hai, we have a requirement like previewing the documents as like in
windows7/vista "preview Pane" and have to implement the search
functionality in Winforms.For that, I have loaded the Ms office
docuemnts, and Excel Sheets and Power Point documents into Webbrowser
Control in html format.Now we need to implement the search
functionality in that webbrowser Control. For that we have
implemented the search functionality using the following code
public bool FindNext(string text, WebBrowser webBrowser1)
{
IHTMLDocument2 doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject sel =doc.selection;// (IHTMLSelectionObject)doc.selection;
IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;
rng.collapse(false); // collapse the current selection so we start from the end of the previous range
if (rng.findText(text, 1000000, 0))
{
rng.select();
return true;
}
else
FindFirst(text, webBrowser1);
return false;
}
This code is working fine for searching the string values in word
Document for all the occurences. But when it Comes to Excel and PPt
documents this code doesn't work properly.it finds only the first
occurrence of the string other occurrences doesn't find. while
debugging i found that,for word Documents "IHTMLDocument2" object
stores the html Content in "innerHTML" and "innerText" with some
values. But for Excel it stores the text in "innerHTML" only by using
the Frames, and sheets are referenced to local temporary .html files
and it didn't have any "innerText" content it showing as null.
Please provide the solution to search the text in webbrowser control which loaded the html content, that is converted from
Excel,PPT to html type and displaying in webbrowser control.
If you have any queries please feel to ask me.
Thank You.

Building a PDF with links from HTML and other PDFs with abcPDF

I've got some code that builds a PDF from an HTML template, then attaches several other PDFs to make one big PDF using abcPDF 7.
All this works fine and dandy -- however, I'd like to make some links in the HTML portion of the PDF to jump down to one of the several attached PDFs.
I tried creating links and anchors using the technique referenced here, by putting the
Link to another page
link in the HTML, then putting the anchor
<div><a name="elementId">A div that's on another page</a></div>
as an added-on paste-over on the top of the first page of the PDF I wanted to jump to.
I can see the text of the anchor just fine, and the link to it is blue, but it doesn't do anything.
As the next attempt, I've created bookmarks that work as well. Can someone point me in the direction to go back and adjust the links in the HTML portion to use them to jump to the bookmarks?
I apologize in advance for a lack of code, and I'm not asking for any code now.. I'd just like a more general way to go about it, like "try something like this." I'm not having much luck finding anything that is close to what I'm trying to do, not even on WebSuperGoo's website.
This method has worked for me in the latest ABCpdf version (9) Add a bookmark to each page in your document:
For i = 1 to pdf.PageCount
pdf.PageNumber = i
pdf.AddBookmark("Page " & i, True)
Next
Then where you want to insert a link you can reference the bookmark - in this case we create a table of contents by looping through each bookmark we've created:
For Each bm As Bookmark In pdf.Bookmark
toc &= "<Font annots='goto:" + bm.Page.PageNumber.ToString() + "'>" & bm.Title & "</Font><br>"
Next
pdf.AddHtml(toc)
The Websupergoo team supplied me with some example code and that's what this is based off of - so thanks to them!

Copy Image between documents using OpenXml and C#

I have two documents, I need to copy a picture from one document to the other. I can't use altChunks because I need to do further editing on the file.
I tried taking a clone of the sdtBlock that the image is in and appending that to the other document.
Like..
sdtBlock = document2.Decendants<StdBlock>.First().Clone(); //Block with image and text etc...
WordprocessingDocument oDoc = WordprocessingDocument.Open(document1, true);
Body body = oDoc.MainDocumentPart.Document.Body;
body.InsertAfter(sdtBlock, body.Elements<Paragraph>().First()); //insert block into new doc
That works for everything except the image. The image appears as either a red X or the document shows as corrupt. If you take the image out this method works fine.
Looking on msdn I think its because I need to create a relationship for that image?
Can anyone show me how this is possible?
Thanks!
Yes, you need to copy the image part across, and add a rel pointing to it. You need to make sure the relId in the paragraph matches the relId of the rel you added.
Have a look at DocumentBuilder in http://powertools.codeplex.com/ for how to do this.

Categories