Поля страниц: PAGE/NUMPAGES пересчитываются, а не печатают кэш
Word записывает поле колонтитула как fldChar begin -> instrText "PAGE" -> separate -> закэшированный результат -> end. Экспорт docx4j в XSL-FO инструкцию внутри такого поля не видит и печатает кэш из docx: в references/word.docx на всех страницах было «2» и «11/11». FieldNormalizer разворачивает поле в w:fldSimple — его обрабатывает FldSimpleWriter из docx4j-export-fo (PAGE -> fo:page-number, есть также NUMPAGES/SECTIONPAGES). Закэшированные ран сохраняются внутри поля: они дают оформление. Штатный FieldsCombiner docx4j делает то же, но не заходит внутрь w:sdt, а Word держит нумерацию именно в контентном контроле «Page Numbers (Top of Page)» — отсюда нормализация байтов. Переписываются только инструкции, для которых есть обработчик; поле без separate/end и вложенные поля пропускаются.
This commit is contained in:
@@ -11,6 +11,7 @@ import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||
import ru.pjandro.wordpdf.internal.chart.DrawingPreRenderer;
|
||||
import ru.pjandro.wordpdf.internal.DocxOnOffNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.FieldNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.FopFallbackFonts;
|
||||
import ru.pjandro.wordpdf.internal.SymbolFontNormalizer;
|
||||
|
||||
@@ -100,6 +101,9 @@ public final class WordPdfConverter {
|
||||
// ...и символьные шрифты Symbol/Wingdings: их коды из PUA экспорт
|
||||
// в FO не понимает и рисует «#» (см. SymbolFontNormalizer).
|
||||
docxBytes = SymbolFontNormalizer.normalize(docxBytes);
|
||||
// ...и поля PAGE/NUMPAGES из fldChar делаем w:fldSimple, иначе
|
||||
// в колонтитулах печатается кэш docx (см. FieldNormalizer).
|
||||
docxBytes = FieldNormalizer.normalize(docxBytes);
|
||||
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(
|
||||
new ByteArrayInputStream(docxBytes));
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Locale;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* Разворачивание «сложных» полей PAGE/NUMPAGES в {@code w:fldSimple} —
|
||||
* до загрузки docx4j.
|
||||
*
|
||||
* Word записывает поле как последовательность ранов:
|
||||
* {@code fldChar begin} → {@code instrText "PAGE"} → {@code fldChar separate}
|
||||
* → закэшированный результат → {@code fldChar end}. Экспорт docx4j в XSL-FO
|
||||
* игнорирует {@code w:instrText} внутри такого поля и печатает кэш из docx,
|
||||
* поэтому в колонтитулах всех страниц стоит одно и то же число
|
||||
* (в references/word.docx — «2» вместо 1, 2, 3 …).
|
||||
*
|
||||
* Собственно поле docx4j умеет: {@code w:fldSimple} обрабатывает
|
||||
* {@code FldSimpleWriter} из docx4j-export-fo, у которого есть обработчики
|
||||
* {@code PAGE} (→ {@code fo:page-number}), {@code NUMPAGES} и
|
||||
* {@code SECTIONPAGES}. Поэтому переписываем поле в {@code w:fldSimple},
|
||||
* сохраняя внутри закэшированные ран — они дают оформление (шрифт, размер).
|
||||
*
|
||||
* Штатный {@code FieldsCombiner} docx4j делает то же самое, но не заходит
|
||||
* внутрь {@code w:sdt}: нумерация страниц Word почти всегда лежит в
|
||||
* контентном контроле («Page Numbers (Top of Page)»), и до поля не добирается.
|
||||
* Отсюда и нормализация байтов, как в {@link DocxOnOffNormalizer}.
|
||||
*
|
||||
* Трогаются только поля, которые действительно есть кому рисовать
|
||||
* ({@link #SUPPORTED}); остальные остаются как были. Вложенные поля не
|
||||
* разбираются — если внутри {@code begin … end} встречается ещё один
|
||||
* {@code begin}, поле пропускается.
|
||||
*/
|
||||
public final class FieldNormalizer {
|
||||
|
||||
/** Инструкции, для которых в docx4j-export-fo есть обработчик fldSimple. */
|
||||
private static final String[] SUPPORTED = {"PAGE", "NUMPAGES", "SECTIONPAGES"};
|
||||
|
||||
private FieldNormalizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Переписывает поддерживаемые поля во всех word/*.xml частях docx.
|
||||
*
|
||||
* @param docx байты .docx (zip)
|
||||
* @return те же или переупакованные байты
|
||||
*/
|
||||
public static byte[] normalize(byte[] docx) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(docx.length);
|
||||
boolean changed = false;
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(docx));
|
||||
ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
byte[] data = zis.readAllBytes();
|
||||
String name = entry.getName();
|
||||
if (name.startsWith("word/") && name.endsWith(".xml")) {
|
||||
String fixed = rewrite(new String(data, StandardCharsets.UTF_8));
|
||||
if (fixed != null) {
|
||||
changed = true;
|
||||
data = fixed.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(name));
|
||||
zos.write(data);
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
return changed ? out.toByteArray() : docx;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return новая строка либо null, если менять нечего
|
||||
*/
|
||||
static String rewrite(String xml) {
|
||||
if (xml.indexOf("fldCharType=\"begin\"") < 0) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(xml.length());
|
||||
int pos = 0;
|
||||
boolean changed = false;
|
||||
while (true) {
|
||||
int begin = xml.indexOf("fldCharType=\"begin\"", pos);
|
||||
if (begin < 0) {
|
||||
break;
|
||||
}
|
||||
int runStart = runStart(xml, begin);
|
||||
int runEnd = xml.indexOf(RUN_CLOSE, begin);
|
||||
if (runStart < 0 || runEnd < 0) {
|
||||
break;
|
||||
}
|
||||
runEnd += RUN_CLOSE.length();
|
||||
|
||||
int end = xml.indexOf("fldCharType=\"end\"", runEnd);
|
||||
int endRunEnd = end < 0 ? -1 : endRunEnd(xml, end);
|
||||
int nested = xml.indexOf("fldCharType=\"begin\"", runEnd);
|
||||
// поле без конца, битое или с вложенным полем — пропускаем целиком
|
||||
int skipTo = endRunEnd >= 0 ? endRunEnd : runEnd;
|
||||
if (endRunEnd < 0 || (nested >= 0 && nested < end)) {
|
||||
sb.append(xml, pos, skipTo);
|
||||
pos = skipTo;
|
||||
continue;
|
||||
}
|
||||
|
||||
String instr = instruction(xml.substring(runStart, endRunEnd));
|
||||
if (instr.isBlank() || !isSupported(instr)) {
|
||||
sb.append(xml, pos, endRunEnd);
|
||||
pos = endRunEnd;
|
||||
continue;
|
||||
}
|
||||
sb.append(xml, pos, runStart)
|
||||
.append(toFldSimple(instr, cached(xml, runEnd, end)));
|
||||
pos = endRunEnd;
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) {
|
||||
return null;
|
||||
}
|
||||
return sb.append(xml, pos, xml.length()).toString();
|
||||
}
|
||||
|
||||
private static final String RUN_CLOSE = "</w:r>";
|
||||
|
||||
/**
|
||||
* Результат поля: ран-маркер {@code separate} и всё, что идёт после него
|
||||
* до рана с {@code end}. Если {@code separate} нет, кэша нет — поле
|
||||
* отрисует обработчик.
|
||||
*/
|
||||
private static String cached(String xml, int from, int endMarker) {
|
||||
int sep = xml.indexOf("fldCharType=\"separate\"", from);
|
||||
int sepRunEnd = xml.indexOf(RUN_CLOSE, sep);
|
||||
if (sep < 0 || sep > endMarker || sepRunEnd < 0) {
|
||||
return "";
|
||||
}
|
||||
sepRunEnd += RUN_CLOSE.length();
|
||||
int endRunStart = runStart(xml, endMarker);
|
||||
if (endRunStart < 0 || endRunStart < sepRunEnd) {
|
||||
return "";
|
||||
}
|
||||
return xml.substring(sepRunEnd, endRunStart);
|
||||
}
|
||||
|
||||
/** Склеивает все {@code w:instrText} блока — Word дробит инструкцию на части. */
|
||||
private static String instruction(String block) {
|
||||
StringBuilder instr = new StringBuilder(64);
|
||||
int pos = 0;
|
||||
while (true) {
|
||||
int open = block.indexOf("<w:instrText", pos);
|
||||
if (open < 0) {
|
||||
break;
|
||||
}
|
||||
int gt = block.indexOf('>', open);
|
||||
int close = block.indexOf("</w:instrText>", gt);
|
||||
if (gt < 0 || close < 0) {
|
||||
break;
|
||||
}
|
||||
instr.append(unescape(block.substring(gt + 1, close)));
|
||||
pos = close + "</w:instrText>".length();
|
||||
}
|
||||
// не trim(): пробелы вокруг инструкции — часть записи Word
|
||||
return instr.toString();
|
||||
}
|
||||
|
||||
private static boolean isSupported(String instr) {
|
||||
String name = instr.trim().split("[\\\\\\s]", 2)[0].toUpperCase(Locale.ROOT);
|
||||
for (String s : SUPPORTED) {
|
||||
if (s.equals(name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String toFldSimple(String instr, String cached) {
|
||||
return "<w:fldSimple w:instr=\"" + escapeAttr(instr) + "\">"
|
||||
+ cached + "</w:fldSimple>";
|
||||
}
|
||||
|
||||
/** Начало рана, содержащего позицию {@code idx} (раны не вложены). */
|
||||
private static int runStart(String xml, int idx) {
|
||||
for (int i = xml.lastIndexOf("<w:r", idx); i >= 0; i = xml.lastIndexOf("<w:r", i - 1)) {
|
||||
if (i + 4 >= xml.length()) {
|
||||
continue;
|
||||
}
|
||||
char next = xml.charAt(i + 4);
|
||||
if (next != '>' && next != ' ') {
|
||||
continue;
|
||||
}
|
||||
// между найденным открытием и idx не должно быть конца рана
|
||||
if (xml.indexOf(RUN_CLOSE, i) > idx) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Позиция сразу за {@code </w:r>} рана, содержащего {@code idx}. */
|
||||
private static int endRunEnd(String xml, int idx) {
|
||||
int end = xml.indexOf(RUN_CLOSE, idx);
|
||||
return end < 0 ? -1 : end + RUN_CLOSE.length();
|
||||
}
|
||||
|
||||
private static String escapeAttr(String value) {
|
||||
return value.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """);
|
||||
}
|
||||
|
||||
private static String unescape(String value) {
|
||||
String v = value;
|
||||
if (v.indexOf('&') < 0) {
|
||||
return v;
|
||||
}
|
||||
v = v.replace("<", "<").replace(">", ">").replace(""", "\"");
|
||||
return v.replace("&", "&");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user