create Hyperlink with docx.dll? - c#

How to create hyperlink with docx.dll dynamically , currently tried below but not working
using (DocX document = DocX.Create(#"Test.docx"))
{
// Add a hyperlink to this document.
Hyperlink h = document.AddHyperlink
("Google", new Uri("http://www.google.com"));
// Add a new Paragraph to this document.
Paragraph p = document.InsertParagraph();
p.Append("My favourite search engine is ");
p.AppendHyperlink(h);
p.Append(", I think it's great.");
// Save all changes made to this document.
document.Save();
}

How about using p.AppendHyperlink("www.google.com", "Google", HyperlinkType.WebLink);
?
Additionally , you can take a reference from Insert Hyperlink to Word in C# .

Related

How to dynamically link bookmarks to table of contents using PDFsharp + MigraDoc

I'm trying to create a Table of Contents using MigraDoc and PDFsharp and I've gotten really close but the problem I'm currently having is that the links on the Table of Contents all take me to the very first page of the PDF. I'm trying to link them to their respective pages. PDFSharp bookmarks work fine but when trying to create a table of contents based on the merged PDF it's not working.
static void TableOfContents(PdfDocument document)
{
// Puts the Table of contents on the second page
PdfPage page = document.Pages[1];
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.MUH = PdfFontEncoding.Unicode;
// Create MigraDoc document + Setup styles
Document doc = new Document();
Styles.DefineStyles(doc);
// Add header
Section section = doc.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 document.Outlines)
{
paragraph = section.AddParagraph();
paragraph.Style = "TOC";
paragraph.AddBookmark(bookmark.Title);
Hyperlink hyperlink = paragraph.AddHyperlink(bookmark.Title);
hyperlink.AddText($"{bookmark.Title}\t");
hyperlink.AddPageRefField(bookmark.Title);
}
// Render document
DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
docRenderer.RenderPage(gfx, 1);
gfx.Dispose();
}
Ideally I want it to return the file's name (which it's doing) and the page number (it's only returning the first page). This is what it's currently outputting.
Table of Contents
file name here......................... 1
file name here......................... 1
file name here......................... 1
file name here......................... 1
As I understand it, the Hyperlink and bookmark should be unique to the document.
Otherwise the link will be made to the first paragraph containing the bookmark.
I simply use a number which I increase for a simple report I make.
private void DefineTOCLine(int level, string text, Paragraph linkTo)
{
var tocIndex = (tocindex++).ToString(CultureInfo.InvariantCulture);
var paragraph = tocsection.AddParagraph();
paragraph.Style = level == 1 ? "TOC1" : "TOC2";
var hyperlink = paragraph.AddHyperlink(tocIndex);
hyperlink.AddText(text + "\t");
hyperlink.AddPageRefField(tocIndex);
linkTo.AddBookmark(tocIndex);
}
You invoke hyperlink.AddPageRefField to set a reference, but as far as I can tell you never create the MigraDoc bookmark for the target of the reference by calling MigraDoc's AddBookmark method.
MigraDoc bookmarks are different from PDF file bookmarks.

C# word document

I want to read a word document without opening it. Then replace some text in it and then save it with another name in the same format using C#. But the document is not being saved with the changes but int the same way as the original document. Any help will be appreciated. Thanks in advance.
string path = Server.MapPath("~/CustomerDocument/SampleNDA5.docx");
WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(path, false);
{
var body = wordprocessingDocument.MainDocumentPart.Document.Body;
foreach (var text in body.Descendants<Text>())
{
if (text.Text.Contains("<var_Date>"))
{
text.Text = text.Text.Replace("<var_Date>", DateTime.Now.ToString("MMM dd,yyyy"));
}
}
wordprocessingDocument.SaveAs(Server.MapPath("~/CustomerDocument/SampleNDA10.docx"));
wordprocessingDocument.Close();
}
I think this should help. It explains how to put edits back into a collection.
https://www.codeproject.com/Articles/87616/List-T-ForEach-or-Foreach-It-Doesn-t-Matter-Or-Doe
So if your word template is the same each time you essentially
Copy The Template
Work On The Template
Save In Desired Format
Delete Template Copy
Each of the sections that you are replacing within your word document you have to insert a bookmark for that location (easiest way to input text in an area).
I always create a function to accomplish this, and I end up passing in the path - as well as all of the text to replace my in-document bookmarks. The function call can get long sometimes, but it works for me.
Application app = new Application();
Document doc = app.Documents.Open("sDocumentCopyPath.docx");
if (doc.Bookmarks.Exists("bookmark_1"))
{
object oBookMark = "bookmark_1";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text =
"My Text To Replace bookmark_1";
}
if (doc.Bookmarks.Exists("bookmark_2"))
{
object oBookMark = "bookmark_2";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text =
"My Text To Replace bookmark_2";
}
doc.ExportAsFixedFormat("myNewPdf.pdf", WdExportFormat.wdExportFormatPDF);
((_Document)doc).Close();
((_Application)app).Quit();
This code should get you up and running unless you want to pass in all the values into a function.
If you need some more explanation I can help as well :) my example saves it as a .pdf, but you can do any format you prefer.

Link to another file

I'm generating a word document by using open-xml.
There i show names of image files
i.e.
c:\config\1.jpg
c:\config\2.jpg
On-click on those names (cntl+click) those file should be opened. But it doesnt go to the file rather than an anchor to top of the word doc.
I used hyperlink as below
Paragraph paraSummary = body.AppendChild(new Paragraph());
Run runSummary = paraSummary.AppendChild(new Run());
runSummary.AppendChild(new Break());
Hyperlink hl = new Hyperlink(new Run(new Text(item.ToString())))
{
DocLocation = rootPath1 + "\\" + item.ToString()
};
runSummary.AppendChild(hl);
mainPart.Document.Append(body);
mainPart.Document.Save();
and the xml of generated file is :
-<w:hyperlink w:docLocation="c:\\config\\1.jpg">-<w:r><w:t>1.jpg</w:t></w:r></w:hyperlink>
is there any other solution other than 'Hyperlinks' or anything that i have missed in above code.
According to the Open XML spec.
http://officeopenxml.com/WPhyperlink.php
docLocation is for external links.
For All types of hyperlinks we have to create a relationship.
for example
In your case TargetMode can't be external
In Open XML SDK you can implement this as below code sample
Hyperlink hl =
new Hyperlink(new Run(new Text("Link1")))
{
Id = "L1"
};
runSummary.AppendChild(hl);
mainPart.Document.Append(body);
mainPart.AddHyperlinkRelationship(new Uri("file:\\C:\\config\\image.jpg"), false, "L1");
in AddHyperlinkRelationship method false means that this is not external link (which is for internal link)

Adding links to pdf by using MigraDoc

I use MigraDoc for creating pdf documents in the project.
Code below shows how I work with library:
var document = new Document { Info = { Author = "title" } };
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph("Title");
var renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always) { Document = document };
renderer.RenderDocument();
So, I'm looking for a way to adding link to web resource inside pdf.
Does someone know?)
-------------Solution-------------------
I found solution!
I tried to use AddHyperlink() for adding link, and it was the first step for this. The code below shows correct using:
var h = paragraph.AddHyperlink("http://stackoverflow.com/",HyperlinkType.Web);
h.AddFormattedText("http://www.stackoverflow.com/");
To add a link use AddHyperlink():
var h = paragraph.AddHyperlink("http://stackoverflow.com/",HyperlinkType.Web);
h.AddFormattedText("http://www.stackoverflow.com/");
So the idea that you should add some text for a link to make link visible.
Use paragraph.AddHyperlink() for that purpose. You will need HyperlinkType.Web.

How to add hyperlinks into Word docx using open XML?

I am having a trouble adding hyperlinks to my word document. I don't know how to do it. I would like to make a link in a word document from my C# code using open xml. Is ther a different solution using only href or sth similar? There is a HyperLink class on the net from Open XML but how to use it?
Try this
using (WordprocessingDocument doc = WordprocessingDocument.Open("", true))
{
doc.MainDocumentPart.Document.Body.AppendChild(
new Paragraph(
new Hyperlink(new Run(new Text("Click here")))
{
Anchor = "Description",
DocLocation = "location",
}
)
);
doc.MainDocumentPart.Document.Save();
}

Categories

Resources