Openxml C# while adding a new pragraph - c#

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.

Related

How to add a paragraph above a bookmark using open xml?

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);

How to create Table Of Contents in pdf file using iTextSharp with C#

I have found many Java examples, but I want C# examples any one to help me on this.
Thanks in advance!
This the example i did
private void GeneratePdf()
{
string path = Server.MapPath("APP_Data");
Document doc = new Document();
try
{
Guid newGd= Guid.NewGuid();
PdfWriter.GetInstance(doc, new FileStream(path + "/Anchors"+ newGd+".pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Font link = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.UNDERLINE);
Anchor anchor = new Anchor("www.mikesdotnetting.com", link);
anchor.Reference = "http://www.mikesdotnetting.com";
Anchor click = new Anchor("Click to go to Target");
click.Reference = "#target";
Paragraph p1 = new Paragraph();
p1.Add(click);
doc.Add(p1);
Paragraph p2 = new Paragraph();
p2.Add(new Chunk("\n\n\n\n\n\n\n\n"));
doc.Add(p2);
Anchor target = new Anchor("This is the Target");
target.Name = "target";
Paragraph p3 = new Paragraph();
p3.Add(target);
doc.Add(p3);
Paragraph p4 = new Paragraph();
p4.Add(new Chunk("Click "));
p4.Add(new Chunk("here", link).SetLocalGoto("GOTO"));
p4.Add(new Chunk(" to find local goto"));
p4.Add(new Chunk("\n\n\n\n\n\n\n\n\n"));
Paragraph p5 = new Paragraph();
p5.Add(new Chunk("Local Goto Destination").SetLocalDestination("GOTO"));
doc.Add(p4);
doc.Add(p5);
Chapter chapter1 = new Chapter(new Paragraph("This is Chapter 1"), 1);
Section section1 = chapter1.AddSection(20f, "Section 1.1", 2);
Section section2 = chapter1.AddSection(20f, "Section 1.2", 2);
Section subsection1 = section2.AddSection(20f, "Subsection 1.2.1", 3);
Section subsection2 = section2.AddSection(20f, "Subsection 1.2.2", 3);
Section subsubsection = subsection2.AddSection(20f, "Sub Subsection 1.2.2.1", 4);
Chapter chapter2 = new Chapter(new Paragraph("This is Chapter 2"), 1);
Section section3 = chapter2.AddSection("Section 2.1", 2);
Section subsection3 = section3.AddSection("Subsection 2.1.1", 3);
Section section4 = chapter2.AddSection("Section 2.2", 2);
chapter1.BookmarkTitle = "Changed Title";
chapter1.BookmarkOpen = true;
chapter2.BookmarkOpen = false;
doc.Add(chapter1);
doc.Add(chapter2);
doc.Add(anchor);
}
catch (DocumentException dex)
{
Response.Write(dex.Message);
}
catch (IOException ioex)
{
Response.Write(ioex.Message);
}
finally
{
doc.Close();
}
}

Insert text at the start of a document in Word - openXML

I am using OpenXML to manipulate Microsoft Word files (.docx).
I am sending the Word files as memory stream, editing them and then send them back to browser so they open in client office program.
I want to insert text, approximatley 10 lines, at the start of a document which already got content. I am doing it like this;
using (var wordprocessingDocument = WordprocessingDocument.Open(mem, true))
{
Paragraph firstParagraph = wordprocessingDocument.MainDocumentPart.Document.Descendants<Paragraph>().First();
Run run1 = new Run();
Text text1 = new Text();
text1.Text = "Document type: ";
run1.Append(text1);
Run run2 = new Run();
Break break1 = new Break();
run2.Append(break1);
ProofError proofError1 = new ProofError() { Type = ProofingErrorValues.SpellStart };
Run run3 = new Run();
Text text2 = new Text();
text2.Text = "Document ID";
run3.Append(text2);
ProofError proofError2 = new ProofError() { Type = ProofingErrorValues.SpellEnd };
Run run4 = new Run();
Break break2 = new Break();
Text text3 = new Text();
text3.Text = "Document Title";
run4.Append(break2);
run4.Append(text3);
firstParagraph.Append(run1);
firstParagraph.Append(run2);
firstParagraph.Append(proofError1);
firstParagraph.Append(run3);
firstParagraph.Append(proofError2);
firstParagraph.Append(run4);
Paragraph paragraph3 = new Paragraph() { RsidParagraphAddition = "0068718C", RsidParagraphProperties = "0068718C", RsidRunAdditionDefault = "00E1050C" };
Run run5 = new Run();
Text text4 = new Text();
text4.Text = "A";
run5.Append(text4);
Run run6 = new Run() { RsidRunAddition = "00126F2D" };
Text text5 = new Text();
text5.Text = "tlet";
run6.Append(text5);
paragraph3.Append(run5);
paragraph3.Append(run6);
Paragraph paragraph4 = new Paragraph() { RsidParagraphMarkRevision = "0068718C", RsidParagraphAddition = "00E1050C", RsidParagraphProperties = "0068718C", RsidRunAdditionDefault = "00E1050C" };
BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };
paragraph4.Append(bookmarkStart1);
paragraph4.Append(bookmarkEnd1);
SectionProperties sectionProperties1 = new SectionProperties() { RsidRPr = "0068718C", RsidR = "00E1050C", RsidSect = "000C7A63" };
}
My problem is that if I already got some text from the first line, then my text will be appended after the original text there. How can I push the original content some lines down, and insert my text above?
Use PrependChild instead of Append. Append will always insert at the end of the current element. So if you already have content in the first paragraph your append will put your text at the end of it. You can also insert your text as a new first paragraph by calling Document.PrependChild(firstParagraph)

WPF RichTextBox - Add a hyperlink without line break?

My code adds a line break before each link. How can i add hyperlinks without adding line breaks? This is my code:
String link = "http://google.de";
if (Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute))
{
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(link);
Hyperlink hyper = new Hyperlink(paragraph.ContentStart, paragraph.ContentEnd);
hyper.NavigateUri = new Uri(new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text);
paragraph.Margin = new Thickness(0);
richTextBox1.Document.Blocks.Add(paragraph);
}
The linebreaks are exactly created by the paragraph. You can just create a new Hyperlink using some other Inline element not Block element. The code should be like this:
if (Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute)) {
//check if there is any paragraph, if not then add a new one
Paragraph para = null;
if(richTextBox1.Blocks.Count == 0 ||
!(richTextBox1.Blocks.LastBlock is Paragraph)) {
para = new Paragraph();
para.Margin = new Thickness(0);
richTextBox1.Blocks.Add(para);
} else para = richTextBox1.Blocks.LastBlock;
Hyperlink hyper = new Hyperlink(new Run(link));
hyper.NavigateUri = new Uri(link);
//add hyperlink to the last Paragraph
para.Inlines.Add(hyper);
}

Open XML Word C# - Split into Two Columns

I was wondering how would it be possible to split the word document into two columns. The reason why I want to do this is because I want to be able to fit all of the information on one page.
Thank you so much for your help and time!
My Code
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var margin_size = 100;
PageMargin pargeMargins = new PageMargin();
pargeMargins.Top = margin_size;
pargeMargins.Bottom = margin_size;
SectionProperties sectionProps = new SectionProperties();
sectionProps.Append(pargeMargins);
Body body = mainPart.Document.AppendChild(new Body());
body.Append(sectionProps);
ParagraphProperties paragraphProperties = new ParagraphProperties
(
//new ParagraphStyleId() { Val = "No Spacing" },
new SpacingBetweenLines() { After = "0" }
);
Paragraph para_main = body.AppendChild(new Paragraph(paragraphProperties));
// Creating the Header where the Serial Number will exist
// Serial Number
Run run_mainHeader = para_main.AppendChild(new Run());
RunProperties runProp_mainHeader = new RunProperties(); // Create run properties.
FontSize size_mainHeader = new FontSize();
size_mainHeader.Val = new StringValue("48");
runProp_mainHeader.Append(size_mainHeader);
run_mainHeader.Append(runProp_mainHeader); // Append all of the properties
run_mainHeader.Append(new Text("S/N: " + sn));
// Serial Barcode
Run run_barcode = para_main.AppendChild(new Run());
RunProperties runProp_barcode = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode = new RunFonts(); // Create font
runFontMain_barcode.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode = new FontSize();
size_barcode.Val = new StringValue("48");
runProp_barcode.Append(runFontMain_barcode);
runProp_barcode.Append(size_barcode);
run_barcode.PrependChild<RunProperties>(runProp_barcode);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode.AppendChild(new Text("*" + sn + "*"));
run_barcode.AppendChild(new Break());
// Tube Type
Run run_tubetype = para_main.AppendChild(new Run());
RunProperties runProp_tubetype = new RunProperties(); // Create run properties.
FontSize size_tubetype = new FontSize();
size_tubetype.Val = new StringValue("38");
runProp_tubetype.Append(size_tubetype);
run_tubetype.Append(runProp_tubetype); // Append all of the properties
run_tubetype.Append(new Text("Tube Type: " + forms[0].TubeType + " "));
//run_tubetype.Append(new Break());
// Tube Barcode
Run run_barcode_tube = para_main.AppendChild(new Run());
RunProperties runProp_barcode_tube = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode_tube = new RunFonts(); // Create font
runFontMain_barcode_tube.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode_tube = new FontSize();
size_barcode_tube.Val = new StringValue("48");
runProp_barcode_tube.Append(runFontMain_barcode_tube);
runProp_barcode_tube.Append(size_barcode_tube);
run_barcode_tube.PrependChild<RunProperties>(runProp_barcode_tube);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode_tube.AppendChild(new Text("*" + forms[0].TubeType + "*"));
run_barcode_tube.AppendChild(new Break());
// Goes through all of the forms
foreach (var form in forms)
{
// Set up a header per form
Run run_header = para_main.AppendChild(new Run());
RunProperties runProp_formHeader = new RunProperties();
Bold bold = new Bold();
Underline ul = new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single };
FontSize size_formHeader = new FontSize();
size_formHeader.Val = new StringValue("24");
runProp_formHeader.Append(size_formHeader);
runProp_formHeader.Append(bold);
runProp_formHeader.Append(ul);
run_header.AppendChild(new RunProperties(runProp_formHeader));
//run_header.AppendChild(new RunProperties(new Bold(), new Underline()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header));
run_header.AppendChild(new Break());
// Goes through all of the fields that each form contains.
for (int i = 0; i < form.FieldList.Count; i++)
{
// Do not need to print out user or serial for each form.
if (!(form.FieldList[i].Token == "SNT"))
{
Run run_data = para_main.AppendChild(new Run());
if (form.FieldList[i].Default)
{
run_data.AppendChild(new Text(form.FieldList[i].Label));
}
else
{
run_data.AppendChild(new Text(form.FieldList[i].Label + " " + form.FieldList[i].Spec + form.FieldList[i].Value));
}
run_data.AppendChild(new Break());
}
}
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
Currently the code prints out everything top-down on one column. And I want it with two columns
You can two or how many columns you want using the Columns Class for the SectionProperties and ParagraphProperties Class
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.columns(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.paragraphproperties(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v=office.14).aspx
This should do it:
// Add a new main document part.
package.AddMainDocumentPart();
// Create the Document DOM.
package.MainDocumentPart.Document = new Document();
Body bd = package.MainDocumentPart.Document.Body = new Body();
//write a first paragraph on two columns
var paragrap1 = new Paragraph();
var paragraphSectionProperties = new ParagraphProperties(new SectionProperties());
var paragraphColumns = new Columns();
paragraphColumns.EqualWidth = true;
paragraphColumns.ColumnCount = 2;
paragraphSectionProperties.Append(paragraphColumns);
paragrap1.Append(paragraphSectionProperties);
paragrap1.Append(new Run(new Text(str)));
bd.AppendChild(paragrap1);
//write another paragraph without paragraph properties
bd.Append(new Paragraph(new Run(new Text(str))));
//set the body properties default three columns
var sectionProperties = new SectionProperties();
var columns = new Columns();
columns.EqualWidth = true;
columns.ColumnCount = 3;
sectionProperties.Append(columns);
bd.Append(sectionProperties);
package.MainDocumentPart.Document.Save();
You can do it for the complete document with this code:
var sectionProperty = document.Body.Descendants<SectionProperties>().First();
var paragraphColumns = new Columns {EqualWidth = true, ColumnCount = 2};
sectionProperty.Append(paragraphColumns);
Try with..
Word.Application WordApp = new Word.Application();
Word.Document BaseDoc = default(Word.Document);
Word.Document DestDoc = default(Word.Document);
int intNumberOfPages = 0;
string intNumberOfChars = null;
int intPage = 0;
//Word Constants
const var wdGoToPage = 1;
const var wdStory = 6;
const var wdExtend = 1;
const var wdCharacter = 1;
//Show WordApp
WordApp.ShowMe();
//Load Base Document
BaseDoc = WordApp.Documents.Open(Filename);
BaseDoc.Repaginate();
//Loop through pages
intNumberOfPages = BaseDoc.BuiltInDocumentProperties("Number of Pages").value;
intNumberOfChars = BaseDoc.BuiltInDocumentProperties("Number of Characters").value;
for (intPage = 1; intPage <= intNumberOfPages; intPage++) {
if (intPage == intNumberOfPages) {
WordApp.Selection.EndKey(wdStory); }
else {
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.MoveLeft(Unit = wdCharacter, Count = 1);
}
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Copy();
Application.DoEvents();
//Create New Document
DestDoc = WordApp.Documents.Add;
DestDoc.Activate();
WordApp.Selection.Paste();
DestDoc.SaveAs(NewFileName + intPage.ToString + ".doc");
DestDoc.Close();
DestDoc = null;
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Delete();
Application.DoEvents();
}
BaseDoc.Close(false);
BaseDoc = null;
WordApp.Quit();
WordApp = null;

Categories