Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Thu Feb 13, 2025 3:04 pm

Hello Team,

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

Relin579
 
Posts: 8
Joined: Mon Jan 15, 2024 8:57 am

Fri Feb 14, 2025 7:28 am

Hi,

Thanks for your inquiry.
I have improved your code, please refer to the following code to resolve the two issues you faced.
Code: Select all
public static void insertFile(File base, ArrayList<String> fileSharings)
{
   int num=0;
   try (InputStream baseIs = new FileInputStream(base)) {
      Document document = new Document(baseIs);
      TextSelection[] textSelections = document.findAllPattern(Pattern.compile( "(\\$)(\\bspire_replace)(\\()([\\W\\w][^\\)]*)(\\))"));
      for (TextSelection textSelection : textSelections)
      {
         // Find file inside fileSharings using fileName from textSelection.getSelectedText()
         Document toInsert = new Document(new FileInputStream(fileSharings.get(num)));
         // Set this method to keep format
         toInsert.setKeepSameFormat(true);
         num++;
         TextRange range = textSelection.getAsOneRange();
         if (range != null)
         {
            Paragraph para = range.getOwnerParagraph();
            // Remove the placeholder text
            para.getChildObjects().clear();
            // Get the paragraph index
            Body body=para.getOwnerTextBody();
            int paraIndex=body.getChildObjects().indexOf(para);
            // 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;
                  
                  body.getChildObjects().insert(paraIndex,documentObject.deepClone());
                  paraIndex++;
               }
            }
         }
      }
      document.saveToFile("result.docx",FileFormat.Docx);
   } catch (FileNotFoundException e) {
      e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   }
}

Sincerely,
Nina
E-iceblue support team
User avatar

Nina.Tang
 
Posts: 1385
Joined: Tue Sep 27, 2016 1:06 am

Return to Spire.Doc