Dear ALL,
I would like to ask why, when I regenerate the TOC, I lose the page numbers. I am using Spring Boot 2.7.18 and Java 11. For docx4j I am using:
<!-- https://mvnrepository.com/artifact/org. ... erenceImpl -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>11.5.5</version>
</dependency>
Below the code I use to regenerate the TOC:
public static boolean processToc(File inputFile, File outputFile) throws Throwable {
boolean bResult = true;
try {
// Carica il documento Word
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(inputFile);
//verica se e' presente una TOC
if (isTocPresent(wordMLPackage) == null) {
bResult = true;
}
else {
//0. Trova e rimuove la TOC esistente
int tocIndex = removeExistingToc(wordMLPackage);
if (tocIndex < 0) {
bResult = false;
}
else {
//1. si sanificano gli stili
fixMissingStyleNames(wordMLPackage);
//2. si genera la nuova TOC con le opzioni corrette
TocGenerator tocGenerator = new TocGenerator(wordMLPackage);
// Usa \n per preservare la numerazione dei capitoli
// \o "1-4" per includere livelli 1-4
// \h per includere hyperlink
// \z per nascondere i tab leader nel Web Layout View
tocGenerator.generateToc(tocIndex, "TOC \\o \"1-4\" \\h \\z", true);
// 3. si aggiornano i riferimenti
tocGenerator.updateToc(true);
// 4. si salva il documento
wordMLPackage.save(outputFile);
}
}
}
catch (Throwable thwExc) {
bResult = false;
}
return bResult;
}
public static SdtBlock isTocPresent(WordprocessingMLPackage wordMLPackage) throws Throwable {
TocFinder tocFinder = new TocFinder(); // Nuova istanza per ogni esecuzione
tocFinder.walkJAXBElements(wordMLPackage.getMainDocumentPart());
return tocFinder.getTocSDT(); // Verifica se ha trovato una TOC
}
private static int removeExistingToc(WordprocessingMLPackage wordMLPackage) throws Throwable {
MainDocumentPart mainPart = wordMLPackage.getMainDocumentPart();
List<Object> content = mainPart.getContent();
for (int i = 0; i < content.size(); i++) {
Object obj = content.get(i);
// Cerca SdtBlock che contiene la TOC
if (obj instanceof SdtBlock) {
SdtBlock sdtBlock = (SdtBlock) obj;
// Verifica se è una TOC
if (isTocBlock(sdtBlock)) {
content.remove(i);
return i;
}
}
// Cerca anche nei paragrafi per campi TOC
if (obj instanceof P) {
P paragraph = (P) obj;
if (containsTocField(paragraph)) {
content.remove(i);
return i;
}
}
}
return -1;
}
Thanks in advance for your help
Michele