Раскладка class C: padding-компенсация таблиц, свёртка tblInd при jc≠left, suff=space; аудит lineRule/kerning закрыт
- LayoutPostRenderer (шаг 4.25, кастомный FORenderer): к start-indent таблицы прибавляется padding-left первой ячейки — рамка на margin+tblInd, текст +padding (MS-OI29500 §2.1.155); регрессия tableCellPadding_textInsetLikeWord - TableIndentNormalizer (правило 7): jc center/right + tblInd → абсолютный tblInd ((W−T)/2+X / (W−T)+X), docx4j игнорирует tblInd при jc≠left - NumberingSuffixNormalizer (правило 8): w:suff=space → пробел в lvlText (Part 1 §17.3.1.28); поиск lvlText вперёд по порядку CT_Lvl (suff→lvlText) - lineRule=auto: rescale НЕ делается — 13.4277pt@11pt канонический single по метрикам Carlito/Calibri (2500/2048 em), замер аудита 13.9 — пиксельное округление; тест пинит метрический шаг - кернинг: подтверждено отсутствие (шрифты бандла GPOS-only, FOP читает только legacy kern, свойства kerning нет); Word по умолчанию не кернит (§17.3.2.19, MS-OI29500 §21.1.2.3.9a) — совпадение по умолчанию, AGENTS.md исправлен - AGENTS.md: правила 1–8, шаг 4.25, счётчики 38/579, новые регрессивные пары
This commit is contained in:
@@ -752,6 +752,146 @@ class WordPdfConverterTest {
|
||||
"Q поднят (vertAlign), конвертация жива");
|
||||
}
|
||||
|
||||
/**
|
||||
* w:tblCellMar w:left=288 (14.4pt): docx4j всегда вычитает левый cellMar
|
||||
* из start-indent таблицы — текст стоит на margin, а рамка уезжает влево
|
||||
* на padding. Word (MS-OI29500 §2.1.155): рамка на margin, текст +padding.
|
||||
* LayoutPostRenderer компенсирует start-indent. Регрессия — аудит
|
||||
* раскладки (матрица B2).
|
||||
*/
|
||||
@Test
|
||||
void tableCellPadding_textInsetLikeWord() throws Exception {
|
||||
byte[] docx = minimalDocx("<w:tbl><w:tblPr>"
|
||||
+ "<w:tblCellMar><w:left w:w=\"288\" w:type=\"dxa\"/></w:tblCellMar>"
|
||||
+ "</w:tblPr><w:tblGrid><w:gridCol w:w=\"4000\"/></w:tblGrid>"
|
||||
+ "<w:tr><w:tc><w:p><w:r><w:t>Q</w:t></w:r></w:p></w:tc></w:tr></w:tbl>",
|
||||
"<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
|
||||
+ "<w:pgMar w:top=\"1440\" w:right=\"1800\" w:bottom=\"1440\" w:left=\"1800\""
|
||||
+ " w:header=\"851\" w:footer=\"992\" w:gutter=\"0\"/></w:sectPr>");
|
||||
Path pdf = convertPdf(docx, "t");
|
||||
// margin 1800 twips = 90pt + padding 288 twips = 14.4pt (до правки — 90)
|
||||
assertEquals(104.4, xOfMarker(pdf, 'Q'), 0.9);
|
||||
}
|
||||
|
||||
/**
|
||||
* w:spacing w:line="240" w:lineRule="auto" (single): шаг базовых =
|
||||
* 13.4277pt — канонический «single» по метрикам Carlito/Calibri
|
||||
* (hhea/win/typo — все 2500/2048 em @11pt; Carlito метрически совмест с
|
||||
* Calibri). Пиксельный замер аудита «Word ≈13.9pt» — округление
|
||||
* (18px@96dpi), расхождения с Word нет → rescale в LayoutPostRenderer
|
||||
* НЕ делается, тест пинит метрический шаг от регрессий. Регрессия —
|
||||
* аудит раскладки (матрица A2, пункт закрыт).
|
||||
*/
|
||||
@Test
|
||||
void lineRuleAuto_wordSingleLinePitch() throws Exception {
|
||||
String run = "<w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/>"
|
||||
+ "<w:sz w:val=\"22\"/></w:rPr>";
|
||||
byte[] docx = minimalDocx("<w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\""
|
||||
+ " w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>"
|
||||
+ "<w:r>" + run + "<w:t>P</w:t></w:r></w:p>"
|
||||
+ "<w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\""
|
||||
+ " w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>"
|
||||
+ "<w:r>" + run + "<w:t>Q</w:t></w:r></w:p>");
|
||||
Path pdf = convertPdf(docx, "t");
|
||||
// 2500/2048 em × 11pt = 13.4277 (не 13.9 — пиксельное округление)
|
||||
assertEquals(13.4277, yOfMarker(pdf, 'Q') - yOfMarker(pdf, 'P'), 0.1);
|
||||
}
|
||||
|
||||
/**
|
||||
* w:jc="center" + w:tblInd=720: docx4j при jc≠left игнорирует tblInd
|
||||
* (Part 1 §17.4.50 в чтении MS-OI29500 §2.1.155 — Word добавляет его
|
||||
* сдвигом от поля). TableIndentNormalizer сворачивает в абсолютный
|
||||
* tblInd: (9922−6000)/2+720 = 2681 twips = 134.05pt. Регрессия — аудит
|
||||
* раскладки (матрица B3).
|
||||
*/
|
||||
@Test
|
||||
void tableIndentCentered_shiftedLikeWord() throws Exception {
|
||||
byte[] docx = minimalDocx("<w:tbl><w:tblPr>"
|
||||
+ "<w:jc w:val=\"center\"/><w:tblInd w:w=\"720\" w:type=\"dxa\"/>"
|
||||
+ "</w:tblPr><w:tblGrid><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"3000\"/></w:tblGrid>"
|
||||
+ "<w:tr><w:tc><w:p><w:r><w:t>Q</w:t></w:r></w:p></w:tc></w:tr></w:tbl>",
|
||||
"<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
|
||||
+ "<w:pgMar w:top=\"1134\" w:right=\"850\" w:bottom=\"1134\" w:left=\"1134\""
|
||||
+ " w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/></w:sectPr>");
|
||||
Path pdf = convertPdf(docx, "t");
|
||||
// margin 56.7 + tblInd 134.05 + cell padding 5.4 (default cellMar)
|
||||
assertEquals(196.15, xOfMarker(pdf, 'Q'), 1.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* w:suff="space": Word пишет после номера обычный пробел (Part 1
|
||||
* §17.3.1.28), docx4j разделитель не эмитит вовсе (дамп n4.fo).
|
||||
* NumberingSuffixNormalizer дописывает пробел в lvlText; FOP отдаёт
|
||||
* лейбл отдельными TextPosition («1», «.», « »), поэтому проверка — по
|
||||
* склеенной последовательности TP (без нормализатора было бы «1.ITEM»:
|
||||
* tab — позиционный разрыв, не символ). Регрессия — аудит раскладки
|
||||
* (матрица N3).
|
||||
*/
|
||||
@Test
|
||||
void suffSpace_labelGetsSpace() throws Exception {
|
||||
Path pdf = convertPdf(numberingDocx(), "t");
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
StringBuilder stream = new StringBuilder();
|
||||
PDFTextStripper stripper = new PDFTextStripper() {
|
||||
@Override
|
||||
protected void processTextPosition(
|
||||
org.apache.pdfbox.text.TextPosition position) {
|
||||
stream.append(position.getUnicode());
|
||||
super.processTextPosition(position);
|
||||
}
|
||||
};
|
||||
stripper.setStartPage(1);
|
||||
stripper.setEndPage(doc.getNumberOfPages());
|
||||
stripper.getText(doc);
|
||||
assertTrue(stream.indexOf("1. ") >= 0, "лейбл «1. » не найден в потоке TP: "
|
||||
+ stream);
|
||||
}
|
||||
}
|
||||
|
||||
/** docx с numbering (lvlText «%1.», suff=space) и нумерованным абзацем «ITEM». */
|
||||
private static byte[] numberingDocx() throws IOException {
|
||||
String w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
putZip(zos, "[Content_Types].xml",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"
|
||||
+ "<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>"
|
||||
+ "<Default Extension=\"xml\" ContentType=\"application/xml\"/>"
|
||||
+ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/>"
|
||||
+ "<Override PartName=\"/word/numbering.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml\"/>"
|
||||
+ "</Types>");
|
||||
putZip(zos, "_rels/.rels",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
||||
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"word/document.xml\"/>"
|
||||
+ "</Relationships>");
|
||||
putZip(zos, "word/document.xml",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<w:document xmlns:w=\"" + w + "\"><w:body>"
|
||||
+ "<w:p><w:pPr><w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"1\"/></w:numPr></w:pPr>"
|
||||
+ "<w:r><w:t>ITEM</w:t></w:r></w:p>"
|
||||
+ "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/></w:sectPr>"
|
||||
+ "</w:body></w:document>");
|
||||
putZip(zos, "word/_rels/document.xml.rels",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
||||
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering\" Target=\"numbering.xml\"/>"
|
||||
+ "</Relationships>");
|
||||
putZip(zos, "word/numbering.xml",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<w:numbering xmlns:w=\"" + w + "\">"
|
||||
+ "<w:abstractNum w:abstractNumId=\"0\">"
|
||||
+ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/>"
|
||||
+ "<w:suff w:val=\"space\"/>"
|
||||
+ "<w:lvlText w:val=\"%1.\"/><w:lvlJc w:val=\"left\"/></w:lvl>"
|
||||
+ "</w:abstractNum>"
|
||||
+ "<w:num w:numId=\"1\"><w:abstractNumId w:val=\"0\"/></w:num>"
|
||||
+ "</w:numbering>");
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Дрейф-гейт: вендорный xslt/docx2fo.xslt = копия
|
||||
* org/docx4j/convert/out/fo/docx2fo.xslt из docx4j-export-fo +
|
||||
@@ -837,8 +977,36 @@ class WordPdfConverterTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** Минимальный transitional-docx с указанным телом w:body. */
|
||||
/** X левого края первого TextPosition, содержащего символ {@code ch}. */
|
||||
private static double xOfMarker(Path pdf, char ch) throws IOException {
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
double[] found = {Double.NaN};
|
||||
PDFTextStripper stripper = new PDFTextStripper() {
|
||||
@Override
|
||||
protected void processTextPosition(
|
||||
org.apache.pdfbox.text.TextPosition position) {
|
||||
if (Double.isNaN(found[0])
|
||||
&& position.getUnicode().indexOf(ch) >= 0) {
|
||||
found[0] = position.getXDirAdj();
|
||||
}
|
||||
super.processTextPosition(position);
|
||||
}
|
||||
};
|
||||
stripper.setStartPage(1);
|
||||
stripper.setEndPage(doc.getNumberOfPages());
|
||||
stripper.getText(doc);
|
||||
assertFalse(Double.isNaN(found[0]), "в PDF нет символа «" + ch + "»");
|
||||
return found[0];
|
||||
}
|
||||
}
|
||||
|
||||
/** Минимальный transitional-docx с указанным телом w:body и sectPr по умолчанию. */
|
||||
private static byte[] minimalDocx(String bodyXml) throws IOException {
|
||||
return minimalDocx(bodyXml, "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/></w:sectPr>");
|
||||
}
|
||||
|
||||
/** Минимальный transitional-docx с указанным телом w:body и sectPr. */
|
||||
private static byte[] minimalDocx(String bodyXml, String sectPrXml) throws IOException {
|
||||
String w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
@@ -858,7 +1026,7 @@ class WordPdfConverterTest {
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<w:document xmlns:w=\"" + w + "\"><w:body>"
|
||||
+ bodyXml
|
||||
+ "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/></w:sectPr>"
|
||||
+ sectPrXml
|
||||
+ "</w:body></w:document>");
|
||||
}
|
||||
return out.toByteArray();
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Юниты post-FO правок {@link LayoutPostRenderer}: padding-компенсация
|
||||
* таблиц. Теги — дословные образцы из FO-дампов аудита раскладки (b1/b2).
|
||||
*/
|
||||
class LayoutPostRendererTest {
|
||||
|
||||
private static String table(String startIndent, String firstCellAttrs) {
|
||||
return "<fo:table border-collapse=\"collapse\" display-align=\"before\" start-indent=\""
|
||||
+ startIndent + "\" width=\"85.9pt\">"
|
||||
+ "<fo:table-column column-number=\"1\" column-width=\"42.95pt\"/>"
|
||||
+ "<fo:table-body><fo:table-row>"
|
||||
+ "<fo:table-cell " + firstCellAttrs + ">"
|
||||
+ "<fo:block>Q</fo:block></fo:table-cell></fo:table-row></fo:table-body></fo:table>";
|
||||
}
|
||||
|
||||
private static final String CELL_PAD_508MM =
|
||||
"padding-after=\"0pt\" padding-before=\"0pt\" padding-before.conditionality=\"retain\""
|
||||
+ " padding-left=\"5.08mm\" padding-right=\"1.91mm\"";
|
||||
|
||||
/** b2-таблица: −14.4pt + 5.08mm (14.4pt) → 0pt, рамка на margin (Word). */
|
||||
@Test
|
||||
void mmPadding_compensatedToZero() {
|
||||
String fixed = LayoutPostRenderer.fix(table("-14.4pt", CELL_PAD_508MM));
|
||||
assertTrue(fixed.contains("start-indent=\"0pt\""), fixed);
|
||||
}
|
||||
|
||||
/** b1-таблица: −5.4pt + 1.91mm (5.414pt) → 0.01pt (mm-округление docx4j). */
|
||||
@Test
|
||||
void defaultCellMar_compensated() {
|
||||
String fixed = LayoutPostRenderer.fix(
|
||||
table("-5.4pt", "padding-left=\"1.91mm\" padding-right=\"1.91mm\""));
|
||||
assertTrue(fixed.contains("start-indent=\"0.01pt\""), fixed);
|
||||
}
|
||||
|
||||
/** tblInd-таблица: docx4j уже вычёл padding (0pt) → компенсация даёт tblInd. */
|
||||
@Test
|
||||
void ptPadding_compensated() {
|
||||
String fixed = LayoutPostRenderer.fix(table("0pt", "padding-left=\"5.4pt\""));
|
||||
assertTrue(fixed.contains("start-indent=\"5.4pt\""), fixed);
|
||||
}
|
||||
|
||||
/** Отрицательный итог сохраняется (Word тоже выводит за поле). */
|
||||
@Test
|
||||
void negativeSum_kept() {
|
||||
String fixed = LayoutPostRenderer.fix(table("-19.8pt", "padding-left=\"5.4pt\""));
|
||||
assertTrue(fixed.contains("start-indent=\"-14.4pt\""), fixed);
|
||||
}
|
||||
|
||||
/** Единица «in» тоже конвертируется. */
|
||||
@Test
|
||||
void inchPadding_converted() {
|
||||
String fixed = LayoutPostRenderer.fix(table("-72pt", "padding-left=\"1in\""));
|
||||
assertTrue(fixed.contains("start-indent=\"0pt\""), fixed);
|
||||
}
|
||||
|
||||
/** У первой ячейки нет padding-left — таблица не трогается (тот же массив). */
|
||||
@Test
|
||||
void noPaddingLeft_returnsSameString() {
|
||||
String fo = table("-5.4pt", "padding-after=\"0pt\" padding-right=\"1.91mm\"");
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
|
||||
/** Нет start-indent в pt — не трогаем. */
|
||||
@Test
|
||||
void noStartIndent_returnsSameString() {
|
||||
String fo = "<fo:table border-collapse=\"collapse\" width=\"85.9pt\">"
|
||||
+ "<fo:table-cell padding-left=\"5.08mm\"><fo:block>Q</fo:block></fo:table-cell>"
|
||||
+ "</fo:table>";
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
|
||||
/** Вложенные таблицы: внешняя компенсируется по своей первой ячейке. */
|
||||
@Test
|
||||
void nestedTables_outerFirstCellWins() {
|
||||
String inner = table("-5.4pt", "padding-left=\"5.4pt\"");
|
||||
String outer = "<fo:table start-indent=\"-5.4pt\"><fo:table-cell padding-left=\"5.4pt\">"
|
||||
+ inner + "</fo:table-cell></fo:table>";
|
||||
String fixed = LayoutPostRenderer.fix(outer);
|
||||
assertEquals(2, fixed.split("start-indent=\"0pt\"", -1).length - 1,
|
||||
"обе таблицы компенсированы: " + fixed);
|
||||
}
|
||||
|
||||
/** Две таблицы — обе правятся за один проход. */
|
||||
@Test
|
||||
void twoTables_bothCompensated() {
|
||||
String fo = table("-14.4pt", CELL_PAD_508MM) + table("-5.4pt", "padding-left=\"5.4pt\"");
|
||||
String fixed = LayoutPostRenderer.fix(fo);
|
||||
assertTrue(fixed.contains("start-indent=\"0pt\""), fixed);
|
||||
assertEquals(2, fixed.split("start-indent=\"0pt\"", -1).length - 1, fixed);
|
||||
}
|
||||
|
||||
/**
|
||||
* a240: Carlito-блок lineRule="auto" НЕ правится — 13.428pt есть
|
||||
* канонический «single» по метрикам Carlito/Calibri (2500/2048 em @11pt),
|
||||
* расхождения с Word нет (см. javadoc {@link LayoutPostRenderer}).
|
||||
*/
|
||||
@Test
|
||||
void carlitoAutoBlock_untouched() {
|
||||
String block = "<fo:block break-before=\"auto\" country=\"US\""
|
||||
+ " docx4j:baseline=\"10.329pt\" docx4j:line-box=\"13.428pt\""
|
||||
+ " docx4j:line-rule=\"auto\" font-family=\"Carlito Regular\""
|
||||
+ " font-size=\"11.0pt\" language=\"en\" line-height=\"13.428pt\""
|
||||
+ " space-after=\"10pt\" white-space-collapse=\"false\">";
|
||||
assertSame(block, LayoutPostRenderer.fix(block));
|
||||
}
|
||||
|
||||
/** Блок без хинта line-rule — не трогаем. */
|
||||
@Test
|
||||
void blockWithoutHint_untouched() {
|
||||
String block = "<fo:block font-family=\"Carlito Regular\" line-height=\"13.428pt\">";
|
||||
assertSame(block, LayoutPostRenderer.fix(block));
|
||||
}
|
||||
|
||||
/** FO-документ без таблиц и Carlito-auto-блоков — тот же экземпляр. */
|
||||
@Test
|
||||
void unrelatedFo_returnsSameString() {
|
||||
String fo = "<fo:root><fo:block font-family=\"DejaVu Sans\">text</fo:block></fo:root>";
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Юниты {@link NumberingSuffixNormalizer}: {@code w:suff w:val="space"} →
|
||||
* пробел в {@code w:lvlText} (Part 1 §17.3.1.28, дамп n4.fo аудита).
|
||||
*/
|
||||
class NumberingSuffixNormalizerTest {
|
||||
|
||||
private static String numbering(String lvls) {
|
||||
return "<w:numbering xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
|
||||
+ "<w:abstractNum w:abstractNumId=\"0\">" + lvls + "</w:abstractNum>"
|
||||
+ "</w:numbering>";
|
||||
}
|
||||
|
||||
/** lvl в порядке схемы CT_Lvl (wml.xsd): suff → lvlText → lvlJc. */
|
||||
private static String lvl(String lvlText, String suff) {
|
||||
return "<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/><w:numFmt w:val=\"decimal\"/>"
|
||||
+ suff + "<w:lvlText w:val=\"" + lvlText + "\"/><w:lvlJc w:val=\"left\"/></w:lvl>";
|
||||
}
|
||||
|
||||
/** suff=space: «%1.» → «%1. ». */
|
||||
@Test
|
||||
void suffSpace_spaceAppended() {
|
||||
String xml = numbering(lvl("%1.", "<w:suff w:val=\"space\"/>"));
|
||||
String fixed = NumberingSuffixNormalizer.rewrite(xml);
|
||||
assertTrue(fixed.contains("<w:lvlText w:val=\"%1. \"/>"), fixed);
|
||||
}
|
||||
|
||||
/** suff=tab — позиционный разделитель, здесь не чинится (Class C). */
|
||||
@Test
|
||||
void suffTab_returnsNull() {
|
||||
String xml = numbering(lvl("%1.", "<w:suff w:val=\"tab\"/>"));
|
||||
assertNull(NumberingSuffixNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** suff без атрибута/без lvl — не трогаем. */
|
||||
@Test
|
||||
void noSuff_returnsNull() {
|
||||
String xml = numbering(lvl("%1.", ""));
|
||||
assertNull(NumberingSuffixNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** lvlText уже с пробелом — дубль не заводим. */
|
||||
@Test
|
||||
void alreadySpaced_returnsNull() {
|
||||
String xml = numbering(lvl("%1. ", "<w:suff w:val=\"space\"/>"));
|
||||
assertNull(NumberingSuffixNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** Два уровня: правится только lvlText того же lvl, где suff=space. */
|
||||
@Test
|
||||
void twoLevels_onlyMatchingLevel() {
|
||||
String xml = numbering(
|
||||
lvl("%1.", "") + "<w:lvl w:ilvl=\"1\"><w:start w:val=\"1\"/>"
|
||||
+ "<w:numFmt w:val=\"lowerLetter\"/><w:suff w:val=\"space\"/>"
|
||||
+ "<w:lvlText w:val=\"%2)\"/><w:lvlJc w:val=\"left\"/></w:lvl>");
|
||||
String fixed = NumberingSuffixNormalizer.rewrite(xml);
|
||||
assertTrue(fixed.contains("<w:lvlText w:val=\"%1.\"/>"), "первый lvl цел: " + fixed);
|
||||
assertTrue(fixed.contains("<w:lvlText w:val=\"%2) \"/>"), fixed);
|
||||
}
|
||||
|
||||
/**
|
||||
* suff=space без своего lvlText: lvlText следующего lvl идёт после
|
||||
* {@code </w:lvl>} — за границу уровня не заходим.
|
||||
*/
|
||||
@Test
|
||||
void suffWithoutOwnLvlText_returnsNull() {
|
||||
String xml = numbering("<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/></w:lvl>"
|
||||
+ "<w:lvl w:ilvl=\"1\"><w:suff w:val=\"space\"/></w:lvl>"
|
||||
+ "<w:lvl w:ilvl=\"2\"><w:lvlText w:val=\"%3.\"/></w:lvl>");
|
||||
assertNull(NumberingSuffixNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
private static byte[] zip(Map<String, String> parts) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
for (Map.Entry<String, String> e : parts.entrySet()) {
|
||||
zos.putNextEntry(new ZipEntry(e.getKey()));
|
||||
zos.write(e.getValue().getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static Map<String, String> unzip(byte[] zip) throws IOException {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zip))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
out.put(entry.getName(),
|
||||
new String(zis.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** normalize: numbering с suff=space переупакован, прочие части целы. */
|
||||
@Test
|
||||
void normalize_rewritesNumberingPartKeepsOthers() throws IOException {
|
||||
byte[] src = zip(Map.of(
|
||||
"[Content_Types].xml", "<Types/>",
|
||||
"word/numbering.xml", numbering(lvl("%1.", "<w:suff w:val=\"space\"/>"))));
|
||||
byte[] fixed = NumberingSuffixNormalizer.normalize(src);
|
||||
assertNotSame(src, fixed);
|
||||
Map<String, String> parts = unzip(fixed);
|
||||
assertEquals("<Types/>", parts.get("[Content_Types].xml"));
|
||||
assertTrue(parts.get("word/numbering.xml").contains("<w:lvlText w:val=\"%1. \"/>"),
|
||||
parts.get("word/numbering.xml"));
|
||||
}
|
||||
|
||||
/** normalize: нечего менять → тот же массив. */
|
||||
@Test
|
||||
void normalize_noChange_returnsSameArray() throws IOException {
|
||||
byte[] src = zip(Map.of(
|
||||
"[Content_Types].xml", "<Types/>",
|
||||
"word/numbering.xml", numbering(lvl("%1.", ""))));
|
||||
assertSame(src, NumberingSuffixNormalizer.normalize(src));
|
||||
}
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Юниты {@link TableIndentNormalizer}: свёртка jc+tblInd в абсолютный tblInd.
|
||||
* Полоса фикстур: pgSz 11906 − pgMar 1134/850 → W = 9922 twips.
|
||||
*/
|
||||
class TableIndentNormalizerTest {
|
||||
|
||||
private static String doc(String body) {
|
||||
return "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
|
||||
+ "<w:body>" + body
|
||||
+ "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
|
||||
+ "<w:pgMar w:top=\"1134\" w:right=\"850\" w:bottom=\"1134\" w:left=\"1134\"/>"
|
||||
+ "</w:sectPr></w:body></w:document>";
|
||||
}
|
||||
|
||||
private static String table(String tblPrInner, String grid) {
|
||||
return "<w:tbl><w:tblPr>" + tblPrInner + "</w:tblPr>"
|
||||
+ "<w:tblGrid>" + grid + "</w:tblGrid>"
|
||||
+ "<w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl>";
|
||||
}
|
||||
|
||||
private static final String GRID_6000 =
|
||||
"<w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"3000\"/>";
|
||||
|
||||
/** center + tblInd 720: (9922−6000)/2+720 = 2681, jc удалён (MS-OI29500 §2.1.155). */
|
||||
@Test
|
||||
void centerWithIndent_rewritten() {
|
||||
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"2681\" w:type=\"dxa\"/>"), fixed);
|
||||
assertFalse(fixed.contains("<w:jc"), "jc удалён: " + fixed);
|
||||
}
|
||||
|
||||
/** right + tblInd 720: (9922−6000)+720 = 4642. */
|
||||
@Test
|
||||
void rightWithIndent_rewritten() {
|
||||
String xml = doc(table("<w:jc w:val=\"right\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"4642\" w:type=\"dxa\"/>"), fixed);
|
||||
assertFalse(fixed.contains("<w:jc"), fixed);
|
||||
}
|
||||
|
||||
/** Отрицательный tblInd сохраняется без клампинга (Word тоже выводит за поле). */
|
||||
@Test
|
||||
void negativeIndent_kept() {
|
||||
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"-720\" w:type=\"dxa\"/>", GRID_6000));
|
||||
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"1241\" w:type=\"dxa\"/>"), fixed);
|
||||
}
|
||||
|
||||
/** tblInd без jc — docx4j и так рендерит корректно, не трогаем. */
|
||||
@Test
|
||||
void indentWithoutJc_returnsNull() {
|
||||
String xml = doc(table("<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** jc без tblInd — аудит PASS (docx4j центрирует), не трогаем. */
|
||||
@Test
|
||||
void jcWithoutIndent_returnsNull() {
|
||||
String xml = doc(table("<w:jc w:val=\"center\"/>", GRID_6000));
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** tblInd=0 с jc — сдвига нет, не трогаем. */
|
||||
@Test
|
||||
void zeroIndent_returnsNull() {
|
||||
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"0\" w:type=\"dxa\"/>", GRID_6000));
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** tblW pct — фактическая ширина не равна Σ gridCol, пропускаем. */
|
||||
@Test
|
||||
void pctWidth_returnsNull() {
|
||||
String xml = doc(table("<w:tblW w:w=\"5000\" w:type=\"pct\"/><w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** gridCol без w:w — ширина неизвестна, пропускаем. */
|
||||
@Test
|
||||
void gridColWithoutWidth_returnsNull() {
|
||||
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>",
|
||||
"<w:gridCol w:w=\"3000\"/><w:gridCol/>"));
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** Две body-level секции — полоса неоднозначна, не трогаем ничего. */
|
||||
@Test
|
||||
void twoBodySections_returnsNull() {
|
||||
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000))
|
||||
.replace("</w:sectPr></w:body>",
|
||||
"</w:sectPr><w:sectPr><w:pgSz w:w=\"12240\"/></w:sectPr></w:body>");
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** sectPr внутри pPr — межсекционный разрыв, не body-level: одна секция остаётся. */
|
||||
@Test
|
||||
void paragraphSectPrNotCounted() {
|
||||
String xml = doc("<w:p><w:pPr><w:sectPr><w:pgSz w:w=\"11906\"/></w:sectPr></w:pPr></w:p>"
|
||||
+ table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"2681\" w:type=\"dxa\"/>"), fixed);
|
||||
}
|
||||
|
||||
/** Дефолты без pgMar: docx4j рендерит margin 1440 (замер) → W = 11906−2880 = 9026. */
|
||||
@Test
|
||||
void missingPgMar_usesMeasuredDefaults() {
|
||||
String xml = "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
|
||||
+ "<w:body>"
|
||||
+ table("<w:jc w:val=\"center\"/><w:tblInd w:w=\"100\" w:type=\"dxa\"/>", GRID_6000)
|
||||
+ "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/></w:sectPr></w:body></w:document>";
|
||||
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||
// (9026−6000)/2 + 100 = 1613
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"1613\" w:type=\"dxa\"/>"), fixed);
|
||||
}
|
||||
|
||||
/** Вложенная таблица со своим jc+tblInd правится, внешняя остаётся. */
|
||||
@Test
|
||||
void nestedTable_innerRewritten() {
|
||||
String inner = table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", "<w:gridCol w:w=\"2000\"/>");
|
||||
String outer = "<w:tbl><w:tblPr><w:tblInd w:w=\"100\" w:type=\"dxa\"/></w:tblPr>"
|
||||
+ "<w:tblGrid><w:gridCol w:w=\"6000\"/></w:tblGrid>"
|
||||
+ "<w:tr><w:tc>" + inner + "</w:tc></w:tr></w:tbl>";
|
||||
String fixed = TableIndentNormalizer.rewrite(doc(outer));
|
||||
// inner: (9922−2000)/2+720 = 4681
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"4681\" w:type=\"dxa\"/>"), fixed);
|
||||
assertTrue(fixed.contains("<w:tblInd w:w=\"100\" w:type=\"dxa\"/>"), fixed);
|
||||
}
|
||||
|
||||
/** Документ без таблиц — null (контракт rewrite). */
|
||||
@Test
|
||||
void noTables_returnsNull() {
|
||||
String xml = doc("<w:p><w:r><w:t>hi</w:t></w:r></w:p>");
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
/** Не-docx-часть (без w:body) — не трогаем, даже с w:tbl. */
|
||||
@Test
|
||||
void nonDocumentPart_returnsNull() {
|
||||
String xml = table("<w:jc w:val=\"center\"/>"
|
||||
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000);
|
||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||
}
|
||||
|
||||
private static byte[] zip(Map<String, String> parts) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
for (Map.Entry<String, String> e : parts.entrySet()) {
|
||||
zos.putNextEntry(new ZipEntry(e.getKey()));
|
||||
zos.write(e.getValue().getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static Map<String, String> unzip(byte[] zip) throws IOException {
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zip))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
out.put(entry.getName(),
|
||||
new String(zis.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** normalize: документ с jc+tblInd переупакован, прочие части целы. */
|
||||
@Test
|
||||
void normalize_rewritesDocumentPartKeepsOthers() throws IOException {
|
||||
byte[] src = zip(Map.of(
|
||||
"[Content_Types].xml", "<Types/>",
|
||||
"word/document.xml", doc(table(
|
||||
"<w:jc w:val=\"center\"/><w:tblInd w:w=\"720\" w:type=\"dxa\"/>",
|
||||
GRID_6000))));
|
||||
byte[] fixed = TableIndentNormalizer.normalize(src);
|
||||
assertNotSame(src, fixed);
|
||||
Map<String, String> parts = unzip(fixed);
|
||||
assertEquals("<Types/>", parts.get("[Content_Types].xml"));
|
||||
assertTrue(parts.get("word/document.xml").contains("w:w=\"2681\""),
|
||||
parts.get("word/document.xml"));
|
||||
}
|
||||
|
||||
/** normalize: нечего менять → тот же массив. */
|
||||
@Test
|
||||
void normalize_noChange_returnsSameArray() throws IOException {
|
||||
byte[] src = zip(Map.of(
|
||||
"[Content_Types].xml", "<Types/>",
|
||||
"word/document.xml", doc(table(
|
||||
"<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000))));
|
||||
assertSame(src, TableIndentNormalizer.normalize(src));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user