I'm using Spire.Doc for Java (13.1.3), and I'm trying to insert files at specific bookmark locations. These bookmarks are formatted like this: $spire_replace(fileName.docx).
In my test, I locate the TextSelection instances using Document.findAllPattern(MyPattern).
For each TextSelection, I need to replace the placeholder content with the corresponding Word file.
Here is my current code:
- Code: Select all
public static final String REPLACE_PATERNE = "(\\$)(\\bspire_replace")(\\()([\\W\\w][^\\)]*)(\\))";
public void insertFile(File base, List<FileSharing> fileSharings) {
try (InputStream baseIs = new FileInputStream(base)) {
Document document = new Document(baseIs);
TextSelection[] textSelections = document.findAllPattern(Pattern.compile(DocxConverter.REPLACE_PATERNE));
for (TextSelection textSelection : textSelections) {
// Find file inside fileSharings using fileName from textSelection.getSelectedText()
Document toInsert = new Document(new FileInputStream(fileSharing));
TextRange range = textSelection.getAsOneRange();
if (range != null) {
Paragraph para = range.getOwnerParagraph();
// Remove the placeholder text
para.getChildObjects().clear();
// Insert content from the secondary document
for (Object oInsertSection : toInsert.getSections()) {
Section insertSection = (Section) oInsertSection;
for (Object oDocumentObject : insertSection.getBody().getChildObjects()) {
DocumentObject documentObject = (DocumentObject) oDocumentObject;
para.getOwnerTextBody().getChildObjects().add(documentObject.deepClone());
}
}
}
}
}
}
Issues I'm facing:
- - The inserted files are appended at the end of the document instead of replacing the bookmark placeholders.
- The inserted document loses the original styling, whereas I need it to maintain the styles of the main document.
Could you please help me resolve these issues?
I have attached my files for reference.
Thank you,
Raphaël