0

After I solved my problem on docx4j previously, I'm be able to use it now.

I just try to run the sample code from this link

http://www.smartjava.org/content/create-complex-word-docx-documents-programatically-docx4j

with some modification.

let's say I have two documents.

One is main template that have about 2-3 pages. Second one have only 1 paragraph of text with various of style (Bold, Italic, Underline, Font Size, etc).

I want to replace a parameter in my template with a paragraph in the second document.

The result is it can replace my parameter with a paragraph but there is a problem with style. What I can observe with many experiment is:

  • Indent still there
  • New Line still there
  • Underline move along too
  • Font Color/ Font Size is working
  • Bold/Italic not come along
  • Font Family not come along

Here is my code

private static void replaceParagraph2(String placeholder, WordprocessingMLPackage template, ContentAccessor addTo) throws Exception {

//get the paragraph
WordprocessingMLPackage paragraph_template = getTemplate("./resources/input/paragraph.docx");
List<Object> paragraphs_LineList = getAllElementFromObject(paragraph_template.getMainDocumentPart(), P.class);

// get the template
List<Object> template_lineList = getAllElementFromObject(template.getMainDocumentPart(), P.class);
int position = 0;
P toReplace = null;
//find placeholder position
for (Object p : template_lineList) {
  List<Object> texts = getAllElementFromObject(p, Text.class);
  for (Object t : texts) {
    Text content = (Text) t;
    if (content.getValue().equals(placeholder)) {

      toReplace = (P) p;
      position = template_lineList.indexOf(toReplace);
      break;
    }
  }
}

//add paragraph into template
for (int i = 0; i < paragraphs_LineList.size(); i++) {

  P para = (P) XmlUtils.deepCopy(paragraphs_LineList.get(i));


  addTo.getContent().add(position + 1 + i, para);
}

// remove the placeholder on the template
((ContentAccessor)toReplace.getParent()).getContent().remove(toReplace);

}

Do I missing something?

PS. I debug to check the object of template. It seems that bold value in the P object is config to null. (It's booleanTrueifNull type I think.)

Doppellon
  • 1
  • 2

1 Answers1

0

The formatting comes from direct formatting (in rPr and pPr elements in the paragraph), and also from the styles part. If no style is specified, the default styles will be used.

You'll need to look at the XML in your paragraph, and in the styles part.

Microsoft Word (2010 at least) has a useful "Reveal Formatting" sidebar which can help you to understand where the formatting is coming from. Click the "distinguish style source" at the bottom.

There is code in docx4j (used by its PDF output) to determine the effective formatting. I guess you could use that to specifically apply the effective formatting from your source to each run in your target.

JasonPlutext
  • 15,352
  • 4
  • 44
  • 84