I am trying to create a Java “script” such that, given a template and a target document:
To summarize, this is what I have come up until now, also based on the API reference for the StyleCollection
class:
Document target = new Document(targetPath);
StyleCollection targetStyles = target.getStyles();
for (Style style : source.getStyles()) {
switch (style.getType()) {
case StyleType.PARAGRAPH:
case StyleType.TABLE:
case StyleType.LIST:
if (!style.getName().trim().toLowerCase().endsWith("carattere")) {
String name = style.getName();
Style copied = styles.addCopy(style);
switch (style.getType()) {
case StyleType.PARAGRAPH:
copied.setNextParagraphStyleName(style.getNextParagraphStyleName());
// fallthrough
case StyleType.CHARACTER:
case StyleType.TABLE:
copied.setBaseStyleName(style.getBaseStyleName());
break;
default:
break;
}
copied.setName(name);
}
break;
default:
break;
}
}
target.save(savePath);
As of now, the problems I have identified are the following:
How do I get a clean copy of all the styles in the document?
if I tried using the standard MS Word styles (“Normal”, “Title 1”, …), when they’re copied over they get duplicated even using the setName() “trick”
Please use following sample code snippet, it will help you to get output without style duplication.
Document source = new Document(MyDir + "template.doc");
Document target = new Document(MyDir + "target.doc");
StyleCollection sourceStyles = source.getStyles();
StyleCollection targetStyles = target.getStyles();
System.out.println("SORGENTE = " + sourceStyles.getCount() + " stili");
System.out.println("DESTINAZIONE = " + targetStyles.getCount() + " stili");
for (Style style : sourceStyles) {
String name = style.getName();
if (name.endsWith("Carattere")) continue;
if (style.getType() == StyleType.PARAGRAPH
|| style.getType() == StyleType.TABLE)
{
Style copied = targetStyles.addCopy(style);
copied.setBaseStyleName(style.getBaseStyleName());
if (style.getType() == StyleType.PARAGRAPH) {
copied.setNextParagraphStyleName(style.getNextParagraphStyleName());
}
copied.setName(name);
System.out.println("COPIA STILE " + name + " -> " + copied.getName());
}
}
target.cleanup();
target.save(MyDir + "output.docx");
if I instead use custom style, I have a problem with table styles, in which the text color changes
Please note Aspose.Words mimics MS Word behavior. If you import the styles from your template to target document using MS Word, it will show same results as Aspose.Words does.
I work with Aspose as developer Evangelist.