Search code examples
c#.netxmlopenxmlopenxml-sdk

Issue when paragraph falls into new line Open XML


I have a number of images that I'm trying to insert into a document, these replacements fall into a different page from where the replacement paragraph is. This seems to be the reason why there's a repair pop-up when I try to open the generated document in MS Word. This is the code I'm using to copy the images across:

tbl.Drawing drawing = buildImage(doc.MainDocumentPart.GetIdOfPart(imagePart), heightEmus, widthEmus);
tbl.Paragraph paragraph1 = new tbl.Paragraph();
tbl.ParagraphProperties paragraphProperties1 = new tbl.ParagraphProperties();
KeepLines keepLines1 = new KeepLines();
paragraphProperties1.Append(keepLines1);
BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
tbl.Run run1 = new tbl.Run();
LastRenderedPageBreak lastRenderedPageBreak1 = new LastRenderedPageBreak();
run1.Append(lastRenderedPageBreak1);
run1.Append(drawing);
BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };
paragraph1.Append(paragraphProperties1);
paragraph1.Append(bookmarkStart1);
paragraph1.Append(run1);
paragraph1.Append(bookmarkEnd1);
paragraph.InsertAfterSelf(paragraph1);

I have been inspired by this post after trying a few approaches: OpenXml - How to identify whether the paragraph extends to next page

The xml looks like this (the repaired one on the left the corrupted one on the right):

enter image description here


Solution

  • I don't think (but not sure) that the issue is the w:lastRenderedPageBreak. I suspect that I'm not seeing the exact issue that is causing Word to fail.

    When I have these types of issues, I use a 'binary search' approach - removing markup until Word opens without failing, and then adding markup back in until it fails. Unfortunately, this is basically the only approach we can take when Word fails to open. We don't get any kind of information back from Word as to why it failed.

    Some time ago, I recorded a screen-cast that explains the approach that I take when faced with this situation.

    https://www.youtube.com/watch?v=xAnmxPqP_5A