How to keep current style when pasting through OpenXML SDK?

I have a docx document that I want to modify using the OpenXML SDK. This document has a table with bookmarks in its cells. Cells have certain font settings, say Times New Roman, 14pt. When I try to insert some text as follows:

public void ReplaceBookmark(string bookMarkName, string text) { var bookmarkStart = _document.MainDocumentPart.RootElement.Descendants<BookmarkStart>() .Where(p => p.Name == bookMarkName) .FirstOrDefault(); if (bookmarkStart == null) return; bookmarkStart.InsertAfterSelf(new Run(new Text(text))); } 

texts are inserted, but its style is set to Calibri, 11pt (default style). How can I insert text to save font settings? The important thing is that I should not define any style settings in the code, but instead use the ones that were in the original document.

Thanks.

+4
source share
1 answer

I studied the docx file format a bit. Obviously, I cannot speak specifically about the file you are using ... but I thought you might be interested in what I found.

If you create a copy of the docx file and provide it with the .zip extension, you can extract the contents of the document. In my case, and possibly in yours, the main part of the document is in the extracted [Extraction Base Path]\word\document.xml file.

The following XML fragment is one that appears to be applied to the first cell in the table (for the created document):

 <w:tc> <w:tcPr> <w:tcW w:w="3192" w:type="dxa"/> </w:tcPr> <w:pw:rsidR="006C4430" w:rsidRPr="006C4430" w:rsidRDefault="006C4430"> <w:pPr> <w:rPr> <w:rFonts w:ascii="Ariel" w:hAnsi="Ariel"/> <w:sz w:val="28"/> <w:szCs w:val="28"/> </w:rPr> </w:pPr> <w:bookmarkStart w:id="0" w:name="First"/> <w:bookmarkEnd w:id="0"/> <w:rw:rsidRPr="006C4430"> <w:rPr> <w:rFonts w:ascii="Bauhaus 93" w:hAnsi="Bauhaus 93"/> <w:sz w:val="28"/> <w:szCs w:val="28"/> </w:rPr> <w:t>Here is some text</w:t> </w:r> </w:p> </w:tc> 

As you can see, the w:bookmarkStart and w:bookmarkEnd tags are found outside the actual contents of the table (which looks like the w: r tag following the bookmark). This happened despite the fact that I created the entire contents of the cell before creating the bookmark. As a result, I suspect that any call made to bookmarkStart.InsertAfterSelf will, as you have seen, use the default font settings, and not any settings related to the table cell. It seems to me that you need to either go to the launch right after the bookmark, or paste the text there, or copy the settings (presumably, the contents of the w:rPr ) from the next run to the new run that you create.

Hope this points you in the appropriate direction. Good luck

+1
source

Source: https://habr.com/ru/post/1345836/


All Articles