fix(core): SmartArt-текст по ECMA — фолбэк-алиас, autofit, lnSpc; phldrT не рисуется #59
@@ -5,6 +5,7 @@ import org.docx4j.dml.CTTextBody;
|
|||||||
import org.docx4j.dml.CTTextCharacterProperties;
|
import org.docx4j.dml.CTTextCharacterProperties;
|
||||||
import org.docx4j.dml.CTTextParagraph;
|
import org.docx4j.dml.CTTextParagraph;
|
||||||
import org.docx4j.dml.CTTextParagraphProperties;
|
import org.docx4j.dml.CTTextParagraphProperties;
|
||||||
|
import org.docx4j.dml.CTTextSpacing;
|
||||||
import org.docx4j.dml.TextFont;
|
import org.docx4j.dml.TextFont;
|
||||||
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||||
@@ -40,8 +41,18 @@ final class DrawMlText {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Один абзац: текст + начертание + выравнивание. */
|
/**
|
||||||
record Paragraph(String text, Style style, String align) {
|
* Один абзац: текст + начертание + выравнивание + межстрочный интервал
|
||||||
|
* из {@code a:lnSpc} (ECMA-376 §21.1.2.4): {@code spacingPct} — доля
|
||||||
|
* одинарного (a:spcPct/100000), {@code spacingPts} — фиксированная
|
||||||
|
* высота строки в pt (a:spcPts/100); оба null — одинарный.
|
||||||
|
*/
|
||||||
|
record Paragraph(String text, Style style, String align,
|
||||||
|
Double spacingPct, Double spacingPts) {
|
||||||
|
|
||||||
|
Paragraph(String text, Style style, String align) {
|
||||||
|
this(text, style, align, null, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Значения выравнивания DrawingML (a:pPr/@algn, a:bodyPr/@anchor). */
|
/** Значения выравнивания DrawingML (a:pPr/@algn, a:bodyPr/@anchor). */
|
||||||
@@ -59,12 +70,19 @@ final class DrawMlText {
|
|||||||
*
|
*
|
||||||
* @param txPr тело текста (может быть null)
|
* @param txPr тело текста (может быть null)
|
||||||
* @param colors палитра темы (для schemeClr в solidFill)
|
* @param colors палитра темы (для schemeClr в solidFill)
|
||||||
* @param fallbackFam семейство, если latin не указан/неизвестен
|
* @param fallbackFam семейство, если latin не указан/неизвестен;
|
||||||
|
* алиасится в бандл-семейство, как и явный latin
|
||||||
|
* (иначе «Calibri» из темы не находится в реестре
|
||||||
|
* {@link GlyphFont} и текст молча уезжает в DejaVu —
|
||||||
|
* шире, чем Calibri/Carlito у Word).
|
||||||
|
* Регрессия — DrawMlTextTest#fallbackFamilyAliasedToBundle.
|
||||||
* @param fallbackSize размер в pt, если sz нет
|
* @param fallbackSize размер в pt, если sz нет
|
||||||
*/
|
*/
|
||||||
static Style defaultStyle(CTTextBody txPr, DrawMlColor colors,
|
static Style defaultStyle(CTTextBody txPr, DrawMlColor colors,
|
||||||
String fallbackFam, double fallbackSize, Color fallbackColor) {
|
String fallbackFam, double fallbackSize, Color fallbackColor) {
|
||||||
Style base = new Style(fallbackSize, false, false, fallbackColor, fallbackFam);
|
Style base = new Style(fallbackSize, false, false, fallbackColor,
|
||||||
|
fallbackFam == null ? BundledFonts.FALLBACK_FAMILY
|
||||||
|
: BundledFontMapper.bundledFamily(fallbackFam));
|
||||||
if (txPr == null || txPr.getP().isEmpty()) {
|
if (txPr == null || txPr.getP().isEmpty()) {
|
||||||
return base;
|
return base;
|
||||||
}
|
}
|
||||||
@@ -103,9 +121,18 @@ final class DrawMlText {
|
|||||||
}
|
}
|
||||||
String align = p.getPPr() != null && p.getPPr().getAlgn() != null
|
String align = p.getPPr() != null && p.getPPr().getAlgn() != null
|
||||||
? p.getPPr().getAlgn().value() : null;
|
? p.getPPr().getAlgn().value() : null;
|
||||||
|
Double spacingPct = null;
|
||||||
|
Double spacingPts = null;
|
||||||
|
CTTextSpacing lnSpc = p.getPPr() == null ? null : p.getPPr().getLnSpc();
|
||||||
|
if (lnSpc != null && lnSpc.getSpcPct() != null && lnSpc.getSpcPct().getVal() > 0) {
|
||||||
|
spacingPct = lnSpc.getSpcPct().getVal() / 100000.0;
|
||||||
|
} else if (lnSpc != null && lnSpc.getSpcPts() != null
|
||||||
|
&& lnSpc.getSpcPts().getVal() > 0) {
|
||||||
|
spacingPts = lnSpc.getSpcPts().getVal() / 100.0;
|
||||||
|
}
|
||||||
String text = sb.toString();
|
String text = sb.toString();
|
||||||
if (!text.isBlank()) {
|
if (!text.isBlank()) {
|
||||||
out.add(new Paragraph(text, runStyle, align));
|
out.add(new Paragraph(text, runStyle, align, spacingPct, spacingPts));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
@@ -175,7 +202,9 @@ final class DrawMlText {
|
|||||||
/**
|
/**
|
||||||
* Рисует абзацы внутри прямоугольника: выравнивание по горизонтали
|
* Рисует абзацы внутри прямоугольника: выравнивание по горизонтали
|
||||||
* (align абзаца или {@code defAlign}) и по вертикали ({@code vAlign}:
|
* (align абзаца или {@code defAlign}) и по вертикали ({@code vAlign}:
|
||||||
* t/ctr/b).
|
* t/ctr/b). Высота строки — из {@code a:lnSpc} абзаца
|
||||||
|
* ({@link #lineFor}), поверх — множитель {@code lineHeightFactor}
|
||||||
|
* (lnSpcReduction из normAutofit).
|
||||||
*/
|
*/
|
||||||
static void paint(Graphics2D g, List<Paragraph> paragraphs, Rectangle2D box,
|
static void paint(Graphics2D g, List<Paragraph> paragraphs, Rectangle2D box,
|
||||||
String defAlign, String vAlign, double lineHeightFactor) {
|
String defAlign, String vAlign, double lineHeightFactor) {
|
||||||
@@ -190,7 +219,7 @@ final class DrawMlText {
|
|||||||
for (Paragraph p : paragraphs) {
|
for (Paragraph p : paragraphs) {
|
||||||
GlyphFont f = fontFor(p.style());
|
GlyphFont f = fontFor(p.style());
|
||||||
double sizePt = p.style().sizePt();
|
double sizePt = p.style().sizePt();
|
||||||
double lineH = (f.ascent(sizePt) + f.descent(sizePt)
|
double lineH = lineFor(p, f.ascent(sizePt) + f.descent(sizePt)
|
||||||
+ f.leading(sizePt)) * lineHeightFactor;
|
+ f.leading(sizePt)) * lineHeightFactor;
|
||||||
for (String line : wrapLines(p.text(), f, sizePt, box.getWidth())) {
|
for (String line : wrapLines(p.text(), f, sizePt, box.getWidth())) {
|
||||||
lines.add(new Line(line, p.style(), p.align(),
|
lines.add(new Line(line, p.style(), p.align(),
|
||||||
@@ -221,6 +250,36 @@ final class DrawMlText {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Высота строки абзаца: a:lnSpc/a:spcPts — фиксированная в pt,
|
||||||
|
* a:spcPct — доля одинарного (ascent+descent+leading), ничего —
|
||||||
|
* одинарный (ECMA-376 §21.1.2.4 CT_TextLineSpacing).
|
||||||
|
*/
|
||||||
|
private static double lineFor(Paragraph p, double single) {
|
||||||
|
if (p.spacingPts() != null) {
|
||||||
|
return p.spacingPts();
|
||||||
|
}
|
||||||
|
return p.spacingPct() != null ? single * p.spacingPct() : single;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Суммарная высота абзацев после переноса в боксе шириной boxWidth pt
|
||||||
|
* (та же разбивка, что в {@link #paint}) — мера для подбора кегля
|
||||||
|
* normAutofit. Регрессия — SmartArtRendererTest#normAutofitShrinksToFit.
|
||||||
|
*/
|
||||||
|
static double totalHeight(List<Paragraph> paragraphs, double boxWidth,
|
||||||
|
double lineHeightFactor) {
|
||||||
|
double total = 0;
|
||||||
|
for (Paragraph p : paragraphs) {
|
||||||
|
GlyphFont f = fontFor(p.style());
|
||||||
|
double sizePt = p.style().sizePt();
|
||||||
|
double lineH = lineFor(p, f.ascent(sizePt) + f.descent(sizePt)
|
||||||
|
+ f.leading(sizePt)) * lineHeightFactor;
|
||||||
|
total += wrapLines(p.text(), f, sizePt, boxWidth).size() * lineH;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Жадный перенос по пробелам; длинные слова режутся по символам.
|
* Жадный перенос по пробелам; длинные слова режутся по символам.
|
||||||
* Ширина набирается инкрементально ({@link GlyphFont#advance} аддитивен —
|
* Ширина набирается инкрементально ({@link GlyphFont#advance} аддитивен —
|
||||||
|
|||||||
+3
-12
@@ -18,8 +18,6 @@ import org.docx4j.dml.GraphicData;
|
|||||||
import org.docx4j.dml.STShapeType;
|
import org.docx4j.dml.STShapeType;
|
||||||
import org.docx4j.dml.chart.CTChartSpace;
|
import org.docx4j.dml.chart.CTChartSpace;
|
||||||
import org.docx4j.dml.chart.CTRelId;
|
import org.docx4j.dml.chart.CTRelId;
|
||||||
import org.docx4j.dml.diagram.CTDataModel;
|
|
||||||
import org.docx4j.dml.diagram.CTRelIds;
|
|
||||||
import org.docx4j.dml.diagram2008.CTDrawing;
|
import org.docx4j.dml.diagram2008.CTDrawing;
|
||||||
import org.docx4j.dml.picture.Pic;
|
import org.docx4j.dml.picture.Pic;
|
||||||
import org.docx4j.dml.wordprocessingDrawing.Anchor;
|
import org.docx4j.dml.wordprocessingDrawing.Anchor;
|
||||||
@@ -219,8 +217,7 @@ public final class DrawingPreRenderer {
|
|||||||
colors, cx, cy);
|
colors, cx, cy);
|
||||||
label = "график";
|
label = "график";
|
||||||
} else if (isDiagram) {
|
} else if (isDiagram) {
|
||||||
img = renderDiagram(part, (CTRelIds) ((JAXBElement<?>) payload).getValue(),
|
img = renderDiagram(part, colors, cx, cy);
|
||||||
colors, cx, cy);
|
|
||||||
label = "SmartArt";
|
label = "SmartArt";
|
||||||
}
|
}
|
||||||
if (img == null) {
|
if (img == null) {
|
||||||
@@ -252,21 +249,15 @@ public final class DrawingPreRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BufferedImage renderDiagram(Part part, CTRelIds refs,
|
private static BufferedImage renderDiagram(Part part, DrawMlColor colors, long cx, long cy) {
|
||||||
DrawMlColor colors, long cx, long cy) {
|
|
||||||
Part drawingPart = diagramDrawingPart(part);
|
Part drawingPart = diagramDrawingPart(part);
|
||||||
if (!(drawingPart instanceof JaxbXmlPart<?> jp)
|
if (!(drawingPart instanceof JaxbXmlPart<?> jp)
|
||||||
|| !(jp.getJaxbElement() instanceof CTDrawing drawing)) {
|
|| !(jp.getJaxbElement() instanceof CTDrawing drawing)) {
|
||||||
LOG.warn("dsp:drawing (SmartArt) не найден — схема пропущена");
|
LOG.warn("dsp:drawing (SmartArt) не найден — схема пропущена");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
CTDataModel data = null;
|
|
||||||
if (refs.getDm() != null && resolve(part, refs.getDm()) instanceof JaxbXmlPart<?> dp
|
|
||||||
&& dp.getJaxbElement() instanceof CTDataModel dm) {
|
|
||||||
data = dm;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
return SmartArtRenderer.render(drawing, data, colors, cx / 12700.0, cy / 12700.0);
|
return SmartArtRenderer.render(drawing, colors, cx / 12700.0, cy / 12700.0);
|
||||||
} catch (RuntimeException | OutOfMemoryError e) {
|
} catch (RuntimeException | OutOfMemoryError e) {
|
||||||
LOG.warn("рендер SmartArt упал: {}", e.toString());
|
LOG.warn("рендер SmartArt упал: {}", e.toString());
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+39
-97
@@ -11,11 +11,7 @@ import org.docx4j.dml.CTShapeStyle;
|
|||||||
import org.docx4j.dml.CTTextBodyProperties;
|
import org.docx4j.dml.CTTextBodyProperties;
|
||||||
import org.docx4j.dml.CTTextNormalAutofit;
|
import org.docx4j.dml.CTTextNormalAutofit;
|
||||||
import org.docx4j.dml.CTTransform2D;
|
import org.docx4j.dml.CTTransform2D;
|
||||||
import org.docx4j.dml.diagram.CTCxn;
|
|
||||||
import org.docx4j.dml.STTextAnchoringType;
|
import org.docx4j.dml.STTextAnchoringType;
|
||||||
import org.docx4j.dml.diagram.CTDataModel;
|
|
||||||
import org.docx4j.dml.diagram.STCxnType;
|
|
||||||
import org.docx4j.dml.diagram.CTPt;
|
|
||||||
import org.docx4j.dml.diagram2008.CTDrawing;
|
import org.docx4j.dml.diagram2008.CTDrawing;
|
||||||
import org.docx4j.dml.diagram2008.CTGroupShape;
|
import org.docx4j.dml.diagram2008.CTGroupShape;
|
||||||
import org.docx4j.dml.diagram2008.CTShape;
|
import org.docx4j.dml.diagram2008.CTShape;
|
||||||
@@ -28,9 +24,7 @@ import java.awt.geom.AffineTransform;
|
|||||||
import java.awt.geom.Rectangle2D;
|
import java.awt.geom.Rectangle2D;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SmartArt в растр. Рисуется {@code word/diagrams/drawing1.xml} — это
|
* SmartArt в растр. Рисуется {@code word/diagrams/drawing1.xml} — это
|
||||||
@@ -44,8 +38,10 @@ import java.util.Map;
|
|||||||
* относительно центра bounding box (ECMA-376 §20.1.7.6, Annex L.4.7.3
|
* относительно центра bounding box (ECMA-376 §20.1.7.6, Annex L.4.7.3
|
||||||
* и L.4.7.4). Регрессии — SmartArtRendererTest.
|
* и L.4.7.4). Регрессии — SmartArtRendererTest.
|
||||||
*
|
*
|
||||||
* Пустые подписи фигур Word показывает текстом-заполнителем из
|
* Текст-заполнитель dgm:prSet/@phldrT («[Текст]», ECMA-376 §21.4.3.4) —
|
||||||
* {@code data1.xml} (dgm:pt/dgm:prSet/@phldrT) — его берём оттуда же.
|
* элемент интерфейса редактирования: в dsp:кэше у таких фигур txBody пуст,
|
||||||
|
* и Word при экспорте в PDF ничего не рисует — мы тоже. Регрессия —
|
||||||
|
* SmartArtRendererTest#emptyTxBody_noPlaceholderInk.
|
||||||
*/
|
*/
|
||||||
final class SmartArtRenderer {
|
final class SmartArtRenderer {
|
||||||
|
|
||||||
@@ -79,7 +75,7 @@ final class SmartArtRenderer {
|
|||||||
private record Item(CTShape shape, AffineTransform toDiagram, double w, double h) {
|
private record Item(CTShape shape, AffineTransform toDiagram, double w, double h) {
|
||||||
}
|
}
|
||||||
|
|
||||||
static BufferedImage render(CTDrawing drawing, CTDataModel data, DrawMlColor colors,
|
static BufferedImage render(CTDrawing drawing, DrawMlColor colors,
|
||||||
double widthPt, double heightPt) {
|
double widthPt, double heightPt) {
|
||||||
List<Item> items = new ArrayList<>();
|
List<Item> items = new ArrayList<>();
|
||||||
collect(drawing.getSpTree().getSpOrGrpSp(), new AffineTransform(), items);
|
collect(drawing.getSpTree().getSpOrGrpSp(), new AffineTransform(), items);
|
||||||
@@ -123,9 +119,8 @@ final class SmartArtRenderer {
|
|||||||
g.translate(offX, offY);
|
g.translate(offX, offY);
|
||||||
g.scale(scale, scale);
|
g.scale(scale, scale);
|
||||||
|
|
||||||
Map<String, String> placeholders = placeholders(data);
|
|
||||||
for (Item it : items) {
|
for (Item it : items) {
|
||||||
drawShape(g, it, colors, placeholders);
|
drawShape(g, it, colors);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
g.dispose();
|
g.dispose();
|
||||||
@@ -190,52 +185,7 @@ final class SmartArtRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private static void drawShape(Graphics2D g, Item it, DrawMlColor colors) {
|
||||||
* Подписи-заполнители. Форма в drawing1.xml ссылается на dgm:pt
|
|
||||||
* type="pres", а phldrT лежит на dgm:pt type="node" — их связывает
|
|
||||||
* dgm:cxn type="presOf" (srcId=node, destId=pres).
|
|
||||||
*/
|
|
||||||
private static Map<String, String> placeholders(CTDataModel data) {
|
|
||||||
Map<String, String> out = new HashMap<>();
|
|
||||||
if (data == null || data.getPtLst() == null) {
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
Map<String, CTPt> byId = new HashMap<>();
|
|
||||||
for (CTPt pt : data.getPtLst().getPt()) {
|
|
||||||
if (pt.getModelId() != null) {
|
|
||||||
byId.put(pt.getModelId(), pt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (data.getCxnLst() != null) {
|
|
||||||
for (CTCxn cxn : data.getCxnLst().getCxn()) {
|
|
||||||
if (cxn.getType() != STCxnType.PRES_OF || cxn.getDestId() == null) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String text = phldrOf(byId.get(cxn.getSrcId()));
|
|
||||||
if (text != null) {
|
|
||||||
out.put(cxn.getDestId(), text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (CTPt pt : data.getPtLst().getPt()) {
|
|
||||||
String text = phldrOf(pt);
|
|
||||||
if (text != null && pt.getModelId() != null) {
|
|
||||||
out.putIfAbsent(pt.getModelId(), text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String phldrOf(CTPt pt) {
|
|
||||||
if (pt == null || pt.getPrSet() == null || pt.getPrSet().getPhldrT() == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String text = pt.getPrSet().getPhldrT();
|
|
||||||
return text.isBlank() ? null : text;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void drawShape(Graphics2D g, Item it, DrawMlColor colors,
|
|
||||||
Map<String, String> placeholders) {
|
|
||||||
CTShape sp = it.shape();
|
CTShape sp = it.shape();
|
||||||
CTShapeProperties spPr = sp.getSpPr();
|
CTShapeProperties spPr = sp.getSpPr();
|
||||||
|
|
||||||
@@ -324,62 +274,54 @@ final class SmartArtRenderer {
|
|||||||
paragraphs = DrawMlText.paragraphs(sp.getTxBody(), colors,
|
paragraphs = DrawMlText.paragraphs(sp.getTxBody(), colors,
|
||||||
colors.minorFontName(), 12, textColor);
|
colors.minorFontName(), 12, textColor);
|
||||||
}
|
}
|
||||||
if (paragraphs.isEmpty() && sp.getModelId() != null) {
|
|
||||||
String ph = placeholders.get(sp.getModelId());
|
|
||||||
if (ph != null) {
|
|
||||||
paragraphs = List.of(new DrawMlText.Paragraph(ph,
|
|
||||||
new DrawMlText.Style(9, false, false, textColor,
|
|
||||||
colors.minorFontName()), "ctr"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (paragraphs.isEmpty()) {
|
if (paragraphs.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// autofit по CT_TextBodyProperties: noAutofit — текст по заявленным
|
// autofit по ECMA-376 §21.1.2.1.2/.3: noAutofit, spAutoFit (§21.1.2.1.4 —
|
||||||
// размерам (переполнение не ужимается, как в Word); normAutofit —
|
// под размер текста ресайзится фигура, сам текст не масштабируется)
|
||||||
// fontScale/lnSpcReduction из XML, затем подбор кегля под прямоугольник.
|
// или отсутствие autofit-элемента (отсутствие имплицирует noAutofit) —
|
||||||
|
// текст рисуется заявленным кеглем. normAutofit — применяем запечённые
|
||||||
|
// Word-ом fontScale/lnSpcReduction из XML; если fontScale не запечён
|
||||||
|
// (устаревший или чужой кэш), Word пересчитывает autofit при рендере —
|
||||||
|
// и мы подбираем кегль так, чтобы высота надетого текста влезала в
|
||||||
|
// прямоугольник (до MIN_FONT_PT). Регрессии —
|
||||||
|
// SmartArtRendererTest#normAutofitShrinksToFit,
|
||||||
|
// #missingAutofitKeepsDeclaredSize.
|
||||||
double lineFactor = 1.0;
|
double lineFactor = 1.0;
|
||||||
boolean noAutofit = bodyPr != null && bodyPr.getNoAutofit() != null;
|
|
||||||
CTTextNormalAutofit na = bodyPr == null ? null : bodyPr.getNormAutofit();
|
CTTextNormalAutofit na = bodyPr == null ? null : bodyPr.getNormAutofit();
|
||||||
if (na != null) {
|
if (na != null) {
|
||||||
if (na.getFontScale() > 0 && na.getFontScale() != NORM_AUTOFIT_FULL) {
|
|
||||||
double k = na.getFontScale() / (double) NORM_AUTOFIT_FULL;
|
|
||||||
List<DrawMlText.Paragraph> scaled = new ArrayList<>();
|
|
||||||
for (DrawMlText.Paragraph p : paragraphs) {
|
|
||||||
scaled.add(new DrawMlText.Paragraph(p.text(),
|
|
||||||
p.style().derive(p.style().sizePt() * k,
|
|
||||||
null, null, null, null), p.align()));
|
|
||||||
}
|
|
||||||
paragraphs = scaled;
|
|
||||||
}
|
|
||||||
if (na.getLnSpcReduction() > 0) {
|
if (na.getLnSpcReduction() > 0) {
|
||||||
lineFactor = 1.0 - na.getLnSpcReduction() / (double) NORM_AUTOFIT_FULL;
|
lineFactor = 1.0 - na.getLnSpcReduction() / (double) NORM_AUTOFIT_FULL;
|
||||||
}
|
}
|
||||||
}
|
if (na.getFontScale() > 0 && na.getFontScale() != NORM_AUTOFIT_FULL) {
|
||||||
if (!noAutofit) {
|
paragraphs = scale(paragraphs, na.getFontScale() / (double) NORM_AUTOFIT_FULL);
|
||||||
// autosize: уменьшаем кегль, пока текст не влезет в прямоугольник
|
} else {
|
||||||
for (int attempt = 0; attempt < SHRINK_ATTEMPTS; attempt++) {
|
for (int attempt = 0; attempt < SHRINK_ATTEMPTS && p0(paragraphs) > MIN_FONT_PT;
|
||||||
double needed = 0;
|
attempt++) {
|
||||||
for (DrawMlText.Paragraph p : paragraphs) {
|
double needed = DrawMlText.totalHeight(paragraphs, tw, lineFactor);
|
||||||
needed += DrawMlText.textHeight(p.style());
|
if (needed <= th) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
paragraphs = scale(paragraphs,
|
||||||
|
Math.max(MIN_FONT_PT / p0(paragraphs), th / needed));
|
||||||
}
|
}
|
||||||
if (needed <= th || p0(paragraphs) <= MIN_FONT_PT) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
double factor = th / needed;
|
|
||||||
List<DrawMlText.Paragraph> shrunk = new ArrayList<>();
|
|
||||||
for (DrawMlText.Paragraph p : paragraphs) {
|
|
||||||
shrunk.add(new DrawMlText.Paragraph(p.text(),
|
|
||||||
p.style().derive(p.style().sizePt() * factor,
|
|
||||||
null, null, null, null), p.align()));
|
|
||||||
}
|
|
||||||
paragraphs = shrunk;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DrawMlText.paint(g, paragraphs, new Rectangle2D.Double(tx, ty, tw, th),
|
DrawMlText.paint(g, paragraphs, new Rectangle2D.Double(tx, ty, tw, th),
|
||||||
ALIGN_LEFT, vAlignOf(bodyPr), lineFactor);
|
ALIGN_LEFT, vAlignOf(bodyPr), lineFactor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Масштабирует кегль всех абзацев в k раз (a:spcPts — абсолютный, не масштабируется). */
|
||||||
|
private static List<DrawMlText.Paragraph> scale(List<DrawMlText.Paragraph> ps, double k) {
|
||||||
|
List<DrawMlText.Paragraph> out = new ArrayList<>(ps.size());
|
||||||
|
for (DrawMlText.Paragraph p : ps) {
|
||||||
|
out.add(new DrawMlText.Paragraph(p.text(),
|
||||||
|
p.style().derive(p.style().sizePt() * k, null, null, null, null),
|
||||||
|
p.align(), p.spacingPct(), p.spacingPts()));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/** Insets bodyPr: значение из XML (EMU) или дефолт ECMA (pt) -> pt. */
|
/** Insets bodyPr: значение из XML (EMU) или дефолт ECMA (pt) -> pt. */
|
||||||
private static double inset(Integer emu, double defaultPt) {
|
private static double inset(Integer emu, double defaultPt) {
|
||||||
return emu == null ? defaultPt : emu / EMU_PER_PT;
|
return emu == null ? defaultPt : emu / EMU_PER_PT;
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import org.docx4j.dml.CTTextBody;
|
|||||||
import org.docx4j.dml.CTTextCharacterProperties;
|
import org.docx4j.dml.CTTextCharacterProperties;
|
||||||
import org.docx4j.dml.CTTextParagraph;
|
import org.docx4j.dml.CTTextParagraph;
|
||||||
import org.docx4j.dml.CTTextParagraphProperties;
|
import org.docx4j.dml.CTTextParagraphProperties;
|
||||||
|
import org.docx4j.dml.CTTextSpacing;
|
||||||
|
import org.docx4j.dml.CTTextSpacingPercent;
|
||||||
import org.docx4j.dml.STTextAlignType;
|
import org.docx4j.dml.STTextAlignType;
|
||||||
import org.docx4j.dml.TextFont;
|
import org.docx4j.dml.TextFont;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -89,6 +91,62 @@ class DrawMlTextTest {
|
|||||||
assertEquals(Color.GRAY, base.color(), "без a:pPr/a:defRPr — фолбэк-цвет");
|
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
|
@Test
|
||||||
void paragraphsNullBodyAndRunStyles() {
|
void paragraphsNullBodyAndRunStyles() {
|
||||||
BundledFonts.init();
|
BundledFonts.init();
|
||||||
|
|||||||
+106
-1
@@ -6,11 +6,18 @@ import org.docx4j.dml.CTNoFillProperties;
|
|||||||
import org.docx4j.dml.CTPoint2D;
|
import org.docx4j.dml.CTPoint2D;
|
||||||
import org.docx4j.dml.CTPositiveSize2D;
|
import org.docx4j.dml.CTPositiveSize2D;
|
||||||
import org.docx4j.dml.CTPresetGeometry2D;
|
import org.docx4j.dml.CTPresetGeometry2D;
|
||||||
|
import org.docx4j.dml.CTRegularTextRun;
|
||||||
import org.docx4j.dml.CTSRgbColor;
|
import org.docx4j.dml.CTSRgbColor;
|
||||||
import org.docx4j.dml.CTShapeProperties;
|
import org.docx4j.dml.CTShapeProperties;
|
||||||
import org.docx4j.dml.CTSolidColorFillProperties;
|
import org.docx4j.dml.CTSolidColorFillProperties;
|
||||||
import org.docx4j.dml.CTTransform2D;
|
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.STShapeType;
|
||||||
|
import org.docx4j.dml.STTextAnchoringType;
|
||||||
import org.docx4j.dml.diagram2008.CTDrawing;
|
import org.docx4j.dml.diagram2008.CTDrawing;
|
||||||
import org.docx4j.dml.diagram2008.CTGroupShape;
|
import org.docx4j.dml.diagram2008.CTGroupShape;
|
||||||
import org.docx4j.dml.diagram2008.CTShape;
|
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.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Обход dsp:spTree и трансформации фигур: flipH/flipV применяются до
|
* Обход dsp:spTree и трансформации фигур: flipH/flipV применяются до
|
||||||
@@ -85,7 +93,7 @@ class SmartArtRendererTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static BufferedImage render(CTDrawing d) {
|
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) {
|
private static boolean reddish(BufferedImage img, double fx, double fy) {
|
||||||
@@ -220,4 +228,101 @@ class SmartArtRendererTest {
|
|||||||
BufferedImage img = render(tree(gs));
|
BufferedImage img = render(tree(gs));
|
||||||
assertTrue(reddish(img, 0.5, 0.5), "дочерний rect отрендерен как есть");
|
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 — кегль не ужат, текст выходит за фигуру");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user