I found the solution here is the code that works to add a paragraph below the bookmark using openxml.Below is the code that works:
var mainPart = wDoc.MainDocumentPart;
var res = from bm in mainPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == "vendos_tekstin"
select bm;
var bookmark = res.SingleOrDefault();
if (bookmark != null)
{
var parent = bookmark.Parent; // bookmark's parent element
// build paragraph piece by piece
Text text = new Text(DateTime.Now.ToString() + " , ");
Text text1 = new Text(gjenerimi + " , ");
Text text2 = new Text(merreshifren());
var run = new Run();
run.Append(text,text1,text2);
Paragraph newParagraph = new Paragraph(run);
run.PrependChild<RunProperties>(runProp);
// insert after bookmark parent
parent.InsertAfterSelf(newParagraph);
I'm trying to add a hyperlink that links to a heading inside the same word document.
This is my code so far:
First I add the hyperlink
Paragraph p = new Paragraph();
Hyperlink h = new Hyperlink(){ Anchor = new StringValue("_Link") };
Run r = new Run();
RunProperties rp = new RunProperties(){ Val = "Hyperlink" };
Text t = new Text("Click here");
r.Append(rp);
r.Append(t);
p.Append(r);
body.Append(p);
Then I add the Heading (with the necessary Bookmark)
Paragraph p = new Paragraph();
Run r = new Run(new Text("My Heading"));
ParagraphProperties pp = new ParagraphProperties();
ParagraphStyleId psi = new ParagraphStyleId(){ Val = new StringValue("Heading1") };
p.Append(r);
p.Append(pp);
p.Append(psi);
p.Append(new BookmarkStart() { Name = new StringValue("_Link") };
p.Append(new BookmarkEnd());
body.Append(p);
I don't see what I'm missing. I set the anchor in the hyperlink, that should link to the Heading with a Bookmark which holds the equal name. (Anchor from hyperlink == Name from Bookmark in Heading).
Or do I need to add a HyperLinkRelationship to MainDocumentPart.HyperlinkRelationship, like I've to do when I want to add a hyperlink with an URI to a website?
You are adding header as a paragraph to the body instead, you need to create the header part -
HeaderPart headerPart = mainDocumentPart.AddNewPart<HeaderPart>();
string headerPartId = mainDocumentPart.GetIdOfPart(headerPart);
GenerateHeaderPartContent(headerPart);
And the code for GenerateHeaderPartContent
private void GeneratePartContent(HeaderPart part)
{
Header header1 = new Header(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "w14 w15 wp14" } };
header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
header1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00225DC9", RsidRunAdditionDefault = "00225DC9" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "Header" };
paragraphProperties1.Append(paragraphStyleId1);
BookmarkStart bookmarkStart1 = new BookmarkStart(){ Name = "HeadingBookmark", Id = "1" };
Run run1 = new Run();
Text text1 = new Text();
text1.Text = "Test";
run1.Append(text1);
paragraph1.Append(paragraphProperties1);
paragraph1.Append(bookmarkStart1);
paragraph1.Append(run1);
BookmarkEnd bookmarkEnd1 = new BookmarkEnd(){ Id = "1" };
header1.Append(paragraph1);
header1.Append(bookmarkEnd1);
part.Header = header1;
}
Once the header part is ready, add it to your documents section properties -
HeaderReference headerReference1 = new HeaderReference(){ Type = HeaderFooterValues.Default, Id = headerPartId };
Also a good ref to check - https://msdn.microsoft.com/en-us/library/office/cc546917.aspx
For open XML (snippet)
// Your new paragraph with the hyperlink
Paragraph hyperlinkParagraph = new Paragraph();
// Run for the hyperlink
Run hyperlinkRun = new Run();
// Styling for the hyperlink
RunProperties runPropertiesHyperLink = new RunProperties(
new RunStyle { Val = "Hyperlink", },
new Underline { Val = UnderlineValues.Single },
new Color { ThemeColor = ThemeColorValues.Hyperlink });
// Actual hyperlink
Hyperlink xmlHyperLink = new Hyperlink()
{
Anchor = "https://stackoverflow.com",
DocLocation = "https://stackoverflow.com"
};
// Text that you see to click on
Text hyperLinkText = new Text("Click for going to StackOverflow!");
// Apply the styling in this order to the run
hyperlinkRun.Append(runPropertiesHyperLink);
hyperlinkRun.Append(hyperLinkText);
// Now add the run to the hyperlink
xmlHyperLink.Append(hyperlinkRun);
// Add the hyperlink to the paragraph
hyperlinkParagraph.Append(xmlHyperLink);
// Add paragraph to the body
_mainBody.Append(hyperlinkParagraph );
DocIO is a .NET library that can read, write, modify and render Microsoft Word documents. Using DocIO, you can able to add Bookmarks and hyperlinks very easily. You don't have to worry about where hyperlink is present (either in header or footer or document body) and decide where to add the reference.
The whole suite of controls is available for free (commercial applications also) through the community license program if you qualify. The community license is the full product with no limitations or watermarks.
Step 1: Create a console application
Step 2: Add reference to these 3 assemblies (Syncfusion.DocIO.Base, Syncfusion.Compression.Base and Syncfusion.OfficeChart.Base). You can also able to add these references through NuGet
Step 3: Copy & paste the below code snippet which open an existing Word document, replace contents and save it back as Word document.
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
namespace DocIO_HyperlinkinkToBookmark
{
class Program
{
static void Main(string[] args)
{
using (WordDocument document = new WordDocument())
{
document.EnsureMinimal();
IWSection section = document.LastSection;
IWParagraph paragraph = document.LastParagraph;
//add text enclosed by BookmarkStart and BookmarkEnd into a paragraph
paragraph.AppendBookmarkStart("Title1Mark");
paragraph.AppendText("Title paragraph");
paragraph.AppendBookmarkEnd("Title1Mark");
//Add few paragraph of textual data
for (int i = 0; i < 10; i++)
section.AddParagraph().AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
paragraph = section.AddParagraph();
//Add a hyperlink with the specified display text and targets to Bookmark named "Title1Mark"
paragraph.AppendHyperlink("Title1Mark", "Link to Title", HyperlinkType.Bookmark);
document.Save("output.docx", FormatType.Docx);
}
}
}
}
For further information about DocIO, please refer our help documentation
Note: I work for Syncfusion
First I have created a paragraph in openxml
Paragraph paragraph1 = new Paragraph();
try
{
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() {
Val = "Correspondence" };
paragraphProperties1.AppendChild(paragraphStyleId1);
Run run1 = new Run();
Text text1 = new Text();
text1.Text = array[1];
run1.AppendChild(text1);
paragraph1.AppendChild(paragraphProperties1);
paragraph1.AppendChild(run1);
}
catch { }
After that i traverse my document paragraph by paragraph and add paragraph that i have described above.
var ps = wordDoc1.MainDocumentPart.Document.Descendants<Paragraph>();
bool addBool;
addBool = false;
foreach (Paragraph pg in ps)
{
if (addBool == true)
{
//pg.Append(paragraph1);
//wordDoc1.MainDocumentPart.Document.Save();
break;
}
if (pg.InnerXml.Contains(#"w:val=""Author""") == true)
{
addBool = true;
pg.Append(paragraph1);
//pg.InnerXml = pg.InnerXml + array[0];
wordDoc1.MainDocumentPart.Document.Save();
break;
}
}
So, It will just append the paragraph into the select paragraph.
My Question:
How can i insert a new paragraph just below the selected paragraph?
Note** And it should not merge into the paragraph but is should create a new paragraph
You can use pg.InsertAfter method to insert new paragraph. Doing so will automatically add paragraph breaks before and after the paragraph.
In my app I have to print some data to a printer. This data is stored in a collection, each record in the collection has a string field and that is what is to be printed. Each of these string fields should be one line. I figured to do something like this
FlowDocument doc = new FlowDocument();
foreach (var x in myCollection)
{
Paragraph p = new Paragraph(new Run(x.PrintString));
doc.Blocks.Add(p);
}
doc.Name = "FlowDoc";
IDocumentPaginatorSource idpSource = doc;
printDlg.PrintDocument(idpSource.DocumentPaginator, "My Printing");
The problem is that there is an empty space after every line, something like this;
Line 1
Line 2
Line 3
When I need it to look like this;
Line 1
Line 2
Line 3
Thanks
edit: Add the definition of doc
Based on the comments I was able to it to work with the following
FlowDocument doc = new FlowDocument();
Paragraph p = new Paragraph();
foreach (var x in myCollection)
{
p.Inlines.Add(x.PrintString + "\r\n");
p.Margin = new Thickness(0);
}
doc.Blocks.Add(p);
doc.Name = "FlowDoc";
IDocumentPaginatorSource idpSource = doc;
printDlg.PrintDocument(idpSource.DocumentPaginator, "My Printing");
How to set the right-to-left direction for a paragraph in word with OpenXML in C#? I use codes below to define it but they won't make any change:
RunProperties rPr = new RunProperties();
Style style = new Style();
style.StyleId = "my_style";
style.Append(new Justification() { Val = JustificationValues.Right });
style.Append(new TextDirection() { Val = TextDirectionValues.TopToBottomRightToLeft });
style.Append(rPr);
and at the end I will set this style for my paragraph:
...
heading_pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "my_style" };
But is see no changes in the output file.
I have found some post but they didn't help me at all,like:
Changing text direction in word file
How can solve this problem?
Thanks in advance.
Use the BiDi class to set the text direction to RTL for a paragraph.
The following code sample searches for the first paragraph in a word document
and sets the text direction to RTL using the BiDi class:
using (WordprocessingDocument doc =
WordprocessingDocument.Open(#"test.docx", true))
{
Paragraph p = doc.MainDocumentPart.Document.Body.ChildElements.First<Paragraph>();
if(p == null)
{
Console.Out.WriteLine("Paragraph not found.");
return;
}
ParagraphProperties pp = p.ChildElements.First<ParagraphProperties>();
if (pp == null)
{
pp = new ParagraphProperties();
p.InsertBefore(pp, p.First());
}
BiDi bidi = new BiDi();
pp.Append(bidi);
}
There are a few more aspects to bi-directional text in Microsoft Word.
SanjayKumarM wrote an article about how right-to-left text content
is handled in Microsoft Word. See this link for more information.
This code worked for me to set the direction Right to Left
var run = new Run(new Text("Some text"));
var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
paragraph.ParagraphProperties = new ParagraphProperties()
{
BiDi = new BiDi(),
TextDirection = new TextDirection()
{
Val = TextDirectionValues.TopToBottomRightToLeft
}
};