Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Help me. My problem is I want to replace a word document using openxml and add a page break. Then I want to write replaced text on the second page.BUT I CAN NOT WRITE THE SECOND PAGE
how do i this ?

Here my code:
C#
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"d:\a.docx", true)) {
 
            using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                text = reader.ReadToEnd();
            }
            Regex regexText = new Regex("#db#");
            text = regexText.Replace(text, textBox4.Text.Trim());
 
            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
 
                sw.Write(text);
 

            }
 
            MainDocumentPart mainPart = wordDoc.MainDocumentPart;
            Run r = new Run();
            Paragraph para = new Paragraph(new Run(new Break() { Type = BreakValues.Page }));
 
            using (StreamWriter sw1 = new StreamWriter(mainPart.GetStream(FileMode.Create)))
            {
                sw1.Write(text);
 
            }
 
            mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
            mainPart.Document.Save();
        }
    }
Posted

I think the problem is in your Body.InsertAfter statement. Look at http://openxmldeveloper.org/blog/b/openxmldeveloper/archive/2011/04/11/137431.aspx[^] where Eric White uses this routine

static void AppendPageBreak(WordprocessingDocument myDoc)
 {
     MainDocumentPart mainPart = myDoc.MainDocumentPart;
     OpenXmlElement last = myDoc.MainDocumentPart.Document
         .Body
         .Elements()
         .LastOrDefault(e => e is Paragraph || e is AltChunk);
     last.InsertAfterSelf(new Paragraph(
         new Run(
             new Break() { Type = BreakValues.Page })));
 }


you dont append to the body, but the last element. regards, me.
 
Share this answer
 
thanks for reply

i tried but i got an error when i try word document :(
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900