fix(core): SmartArt-текст по ECMA — фолбэк-алиас, autofit, lnSpc; phldrT не рисуется
PR checks / web (pull_request) Successful in 31s
PR checks / java (pull_request) Successful in 1m39s
Main: tests, deploy, autotests / web (push) Successful in 50s
Main: tests, deploy, autotests / java (push) Successful in 1m6s
Main: tests, deploy, autotests / images-app (push) Successful in 44s
Main: tests, deploy, autotests / images-web (push) Successful in 1m13s
Main: tests, deploy, autotests / deploy (push) Successful in 1m39s
Main: tests, deploy, autotests / autotests (push) Successful in 36s
Main: tests, deploy, autotests / rollback (push) Has been skipped

- DrawMlText: фолбэк-семейство темы (minorFont без a:latin) алиасится через
  BundledFontMapper.bundledFamily — раньше «Calibri» не находился в GlyphFont
  и текст молча ехал в более широкий DejaVu Sans, из-за чего подписи
  переносились и вылезали за фигуры (123@26pt: 49.6pt против бокса 39.7pt)
- DrawMlText: высота строки из a:lnSpc spcPct/spcPts (§21.1.2.4) — dsp-кэш
  запекает, напр., 90%; хелпер totalHeight — высота после переносов
- SmartArtRenderer: autofit только normAutofit (§21.1.2.1.2/.3 — отсутствие
  autofit-элемента имплицирует noAutofit); запечённый fontScale применяется,
  без него — подбор кегля под перенесённый текст (низ 4pt); эвристика по
  высоте одной строки удалена
- SmartArtRenderer: заполнитель dgm:prSet/@phldrT («[Текст]», §21.4.3.4) не
  рисуется — элемент UI, в PDF Word его не показывает; render() без CTDataModel,
  DrawingPreRenderer не резолвит dgm:relIds/@dm

Регрессии: DrawMlTextTest#fallbackFamilyAliasedToBundle,
#lineSpacingPct_compactsLines; SmartArtRendererTest#normAutofitShrinksToFit,
#missingAutofitKeepsDeclaredSize, #emptyTxBody_noPlaceholderInk.
mvn clean verify: 525 тестов зелёные, PMD + JaCoCo гейты пройдены.
This commit was merged in pull request #59.
This commit is contained in:
Pjandro
2026-10-26 11:33:59 +00:00
parent c67786151c
commit b29972fbf8
6 changed files with 275 additions and 119 deletions
@@ -6,6 +6,8 @@ import org.docx4j.dml.CTTextBody;
import org.docx4j.dml.CTTextCharacterProperties;
import org.docx4j.dml.CTTextParagraph;
import org.docx4j.dml.CTTextParagraphProperties;
import org.docx4j.dml.CTTextSpacing;
import org.docx4j.dml.CTTextSpacingPercent;
import org.docx4j.dml.STTextAlignType;
import org.docx4j.dml.TextFont;
import org.junit.jupiter.api.Test;
@@ -89,6 +91,62 @@ class DrawMlTextTest {
assertEquals(Color.GRAY, base.color(), "без a:pPr/a:defRPr — фолбэк-цвет");
}
/**
* Фолбэк-семейство (шрифт темы, когда у рана нет a:latin) алиасится
* в бандл: «Calibri» → Carlito. Без алиаса GlyphFont.of("Calibri")
* не находится, текст молча уезжает в DejaVu Sans — шире, чем Calibri
* у Word, из-за чего текст SmartArt переносился и вылезал за фигуру.
*/
@Test
void fallbackFamilyAliasedToBundle() {
DrawMlText.Style def = DrawMlText.defaultStyle(null, new DrawMlColor(null),
"Calibri", 9, Color.BLACK);
assertEquals("carlito", def.family());
}
/** a:lnSpc/a:spcPct (ECMA-376 §21.1.2.4) — высота строки как доля одинарного. */
@Test
void lineSpacingPct_compactsLines() {
BundledFonts.init();
DrawMlColor colors = new DrawMlColor(null);
CTTextBody body = new CTTextBody();
CTTextParagraph p = new CTTextParagraph();
CTTextParagraphProperties pPr = new CTTextParagraphProperties();
CTTextSpacing lnSpc = new CTTextSpacing();
CTTextSpacingPercent pct = new CTTextSpacingPercent();
pct.setVal(40000);
lnSpc.setSpcPct(pct);
pPr.setLnSpc(lnSpc);
p.setPPr(pPr);
CTRegularTextRun r = new CTRegularTextRun();
r.setT("A\nB");
p.getEGTextRun().add(r);
body.getP().add(p);
List<DrawMlText.Paragraph> paras = DrawMlText.paragraphs(body, colors,
"DejaVu Sans", 10, Color.BLACK);
assertEquals(0.4, paras.get(0).spacingPct(), 1e-9);
int compacted = lastInkY(paint(paras,
new Rectangle2D.Double(0, 0, 120, 80), null, "t"));
int normal = lastInkY(paint(List.of(new DrawMlText.Paragraph("A\nB", STYLE, null)),
new Rectangle2D.Double(0, 0, 120, 80), null, "t"));
assertTrue(compacted < normal - 8,
"интервал 40% — вторая строка заметно выше: compacted="
+ compacted + ", normal=" + normal);
}
/** Нижний ряд с тёмными чернилами. */
private static int lastInkY(BufferedImage img) {
for (int y = img.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < img.getWidth(); x++) {
int argb = img.getRGB(x, y);
if (argb >>> 24 > 0 && (argb & 0xFFFFFF) < 0x808080) {
return y;
}
}
}
return -1;
}
@Test
void paragraphsNullBodyAndRunStyles() {
BundledFonts.init();
@@ -6,11 +6,18 @@ import org.docx4j.dml.CTNoFillProperties;
import org.docx4j.dml.CTPoint2D;
import org.docx4j.dml.CTPositiveSize2D;
import org.docx4j.dml.CTPresetGeometry2D;
import org.docx4j.dml.CTRegularTextRun;
import org.docx4j.dml.CTSRgbColor;
import org.docx4j.dml.CTShapeProperties;
import org.docx4j.dml.CTSolidColorFillProperties;
import org.docx4j.dml.CTTransform2D;
import org.docx4j.dml.CTTextBody;
import org.docx4j.dml.CTTextBodyProperties;
import org.docx4j.dml.CTTextCharacterProperties;
import org.docx4j.dml.CTTextNormalAutofit;
import org.docx4j.dml.CTTextParagraph;
import org.docx4j.dml.STShapeType;
import org.docx4j.dml.STTextAnchoringType;
import org.docx4j.dml.diagram2008.CTDrawing;
import org.docx4j.dml.diagram2008.CTGroupShape;
import org.docx4j.dml.diagram2008.CTShape;
@@ -20,6 +27,7 @@ import java.awt.image.BufferedImage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Обход dsp:spTree и трансформации фигур: flipH/flipV применяются до
@@ -85,7 +93,7 @@ class SmartArtRendererTest {
}
private static BufferedImage render(CTDrawing d) {
return SmartArtRenderer.render(d, null, new DrawMlColor(null), SIDE_PT, SIDE_PT);
return SmartArtRenderer.render(d, new DrawMlColor(null), SIDE_PT, SIDE_PT);
}
private static boolean reddish(BufferedImage img, double fx, double fy) {
@@ -220,4 +228,101 @@ class SmartArtRendererTest {
BufferedImage img = render(tree(gs));
assertTrue(reddish(img, 0.5, 0.5), "дочерний rect отрендерен как есть");
}
/** rect w×h pt, noFill, с текстовым телом. */
private static CTShape textRect(double wPt, double hPt, CTTextBody txBody) {
CTShape sp = new CTShape();
CTTransform2D t = new CTTransform2D();
t.setOff(point(0, 0));
t.setExt(size(Math.round(wPt * 12700), Math.round(hPt * 12700)));
CTShapeProperties spPr = new CTShapeProperties();
spPr.setXfrm(t);
spPr.setNoFill(new CTNoFillProperties());
sp.setSpPr(spPr);
sp.setTxBody(txBody);
return sp;
}
/** txBody: bodyPr + абзацы раном 12pt. */
private static CTTextBody textBody(CTTextBodyProperties bodyPr, String... texts) {
CTTextBody tb = new CTTextBody();
tb.setBodyPr(bodyPr);
for (String s : texts) {
CTTextParagraph p = new CTTextParagraph();
CTRegularTextRun r = new CTRegularTextRun();
CTTextCharacterProperties rPr = new CTTextCharacterProperties();
rPr.setSz(1200);
r.setRPr(rPr);
r.setT(s);
p.getEGTextRun().add(r);
tb.getP().add(p);
}
return tb;
}
/** Есть ли тёмные чернила (цвет текста 0x595959) ниже yPt изображения. */
private static boolean hasInkBelow(BufferedImage img, double yPt) {
int y0 = Math.max(0, (int) Math.ceil(yPt * SmartArtRenderer.DPI / 72.0));
for (int y = y0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
int argb = img.getRGB(x, y);
if (argb >>> 24 > 0 && (argb & 0xFFFFFF) < 0x808080) {
return true;
}
}
}
return false;
}
/**
* ECMA-376 §21.4.3.4: phldrT («[Текст]») — заполнитель интерфейса
* редактирования; при пустом txBody Word в PDF ничего не рисует, и мы.
*/
@Test
void emptyTxBody_noPlaceholderInk() {
CTTextBody tb = new CTTextBody();
tb.setBodyPr(new CTTextBodyProperties());
tb.getP().add(new CTTextParagraph());
BufferedImage img = render(tree(textRect(60, 20, tb)));
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
assertEquals(0, img.getRGB(x, y) >>> 24,
"пустая фигура — никаких чернил (заполнитель не рисуется)");
}
}
}
/**
* §21.1.2.1.3: normAutofit без запечённого fontScale — Word пересчитывает
* autofit при рендере; и мы подбираем кегль под высоту надетого текста.
* Раньше эвристика проверяла высоту одной строки, и переносы вылезали
* из-под фигуры.
*/
@Test
void normAutofitShrinksToFit() {
CTTextBodyProperties bodyPr = new CTTextBodyProperties();
bodyPr.setAnchor(STTextAnchoringType.T);
bodyPr.setNormAutofit(new CTTextNormalAutofit());
BufferedImage img = render(tree(textRect(60, 40, textBody(bodyPr,
"альфа бета гамма дельта эпсилон зета эта йота капа лямбда"))));
double bottomPt = (SIDE_PT - 40 * (SIDE_PT / 60.0)) / 2.0 + 40 * (SIDE_PT / 60.0);
assertTrue(hasInkBelow(img, 0), "текст нарисован");
assertFalse(hasInkBelow(img, bottomPt + 2),
"normAutofit — перенесённый текст влезает в фигуру");
}
/**
* §21.1.2.1.2: отсутствие autofit-элемента имплицирует noAutofit —
* заявленный кегль не ужимается, переполнение уходит за фигуру (как Word).
* Раньше эвристика резала кегль и без normAutofit.
*/
@Test
void missingAutofitKeepsDeclaredSize() {
CTTextBodyProperties bodyPr = new CTTextBodyProperties();
bodyPr.setAnchor(STTextAnchoringType.T);
BufferedImage img = render(tree(textRect(60, 40, textBody(bodyPr, "A", "B", "C"))));
double bottomPt = (SIDE_PT - 40 * (SIDE_PT / 60.0)) / 2.0 + 40 * (SIDE_PT / 60.0);
assertTrue(hasInkBelow(img, bottomPt + 2),
"нет autofit — кегль не ужат, текст выходит за фигуру");
}
}