Диаграммы и SmartArt: пре-рендер w:drawing в PNG (pie, line, surface3D)
docx2fo.xslt умеет только a:graphicData/pic:pic — для c:chart и dgm:relIds там notImplemented, т.е. объект молча исчезал из PDF. Новый internal/chart рендерит их своим Java2D-движком в PNG 300 dpi и подменяет на pic:pic (шаг 3.5 в convertToStream: после setFontMapper, до FOSettings). surface3D: седловая ячейка режется диагональю с большей суммой значений (верхняя огибающая седла). При фиксированной w00–w11 второй треугольник становится невидимой щепкой, а видимая грань окрашивается не той полосой.
This commit is contained in:
@@ -9,6 +9,7 @@ import org.docx4j.convert.out.fo.renderers.FORendererApacheFOP;
|
||||
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
||||
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.FopFallbackFonts;
|
||||
|
||||
@@ -103,6 +104,11 @@ public final class WordPdfConverter {
|
||||
// с физическими TTF (учитывая и шрифты, встроенные в docx)
|
||||
pkg.setFontMapper(mapper);
|
||||
|
||||
// 3.5 Диаграммы (c:chart) и SmartArt (dgm:relIds) -> PNG.
|
||||
// docx2fo.xslt умеет только pic:pic; для chart/diagram там
|
||||
// notImplemented, т.е. без этого шага они просто исчезают.
|
||||
DrawingPreRenderer.run(pkg);
|
||||
|
||||
// 4. Настройки экспорта (FOP-конфиг с embed-шрифтами)
|
||||
FOSettings foSettings = new FOSettings(pkg);
|
||||
// FOP-конфиг знает только шрифты из fontsInUse, а символы
|
||||
|
||||
@@ -77,6 +77,18 @@ public class BundledFontMapper extends BestMatchingMapper {
|
||||
ALIASES = Map.copyOf(m);
|
||||
}
|
||||
|
||||
/**
|
||||
* Бандл-семейство для имени шрифта из документа (таблица алиасов)
|
||||
* или финальный fallback. Используется пре-рендером диаграмм
|
||||
* (internal/chart), которому нужен тот же шрифт, что и у текста PDF.
|
||||
*/
|
||||
public static String bundledFamily(String docFontName) {
|
||||
String family = ALIASES.get(docFontName.toLowerCase(Locale.ROOT));
|
||||
return family != null && BundledFonts.regular(family) != null
|
||||
? family
|
||||
: FALLBACK_FAMILY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вызывается docx4j при {@code package.setFontMapper(...)}: для каждого
|
||||
* имени шрифта, использованного в документе, нужно определить, каким
|
||||
|
||||
@@ -103,6 +103,9 @@ public final class BundledFonts {
|
||||
/** Ключ семейства (lowercase) -> начертание -> зарегистрированный PhysicalFont. */
|
||||
private static final Map<String, Map<String, PhysicalFont>> VARIANTS = new HashMap<>();
|
||||
|
||||
/** Ключ family/variant -> java.awt.Font (кэш, см. {@link #awtFont}). */
|
||||
private static final Map<String, java.awt.Font> AWT_FONTS = new HashMap<>();
|
||||
|
||||
/** Каталог, куда выгружены TTF (после init()). */
|
||||
private static Path extractDir;
|
||||
private static boolean inited = false;
|
||||
@@ -222,4 +225,31 @@ public final class BundledFonts {
|
||||
public static PhysicalFont boldItalic(String family) {
|
||||
return font(family, V_BOLD_ITALIC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Тот же TTF, но как {@link java.awt.Font} для Java2D (пре-рендер
|
||||
* диаграмм и SmartArt в растр, см. internal/chart). Шрифт читается
|
||||
* из выгруженного файла один раз и кешируется.
|
||||
*
|
||||
* @return базовый Font размера 1 (далее {@code deriveFont(size)}),
|
||||
* или null, если шрифт не найден / {@link #init()} не вызван
|
||||
*/
|
||||
public static synchronized java.awt.Font awtFont(String family, String variant) {
|
||||
String key = family + "/" + variant;
|
||||
java.awt.Font cached = AWT_FONTS.get(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
PhysicalFont pf = font(family, variant);
|
||||
if (pf == null || pf.getEmbeddedURI() == null) {
|
||||
return null;
|
||||
}
|
||||
try (InputStream in = Files.newInputStream(Path.of(pf.getEmbeddedURI()))) {
|
||||
java.awt.Font f = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, in);
|
||||
AWT_FONTS.put(key, f);
|
||||
return f;
|
||||
} catch (IOException | java.awt.FontFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Декартовы графики Word: линии, области, столбцы (и горизонтальные
|
||||
* столбцы). Остальные типы (разбросанный, пузырьковый, лепестковый)
|
||||
* здесь не рисуются — вызывающий их пропускает.
|
||||
*/
|
||||
final class CartesianPainter {
|
||||
|
||||
private CartesianPainter() {
|
||||
}
|
||||
|
||||
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
|
||||
boolean horizontal = spec.type == ChartSpec.Type.BAR_HORIZONTAL;
|
||||
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
|
||||
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
|
||||
|
||||
int nCat = 0;
|
||||
for (ChartSpec.Series s : spec.series) {
|
||||
nCat = Math.max(nCat, s.values.size());
|
||||
}
|
||||
if (nCat == 0) {
|
||||
return;
|
||||
}
|
||||
List<String> cats = categoriesOf(spec, nCat);
|
||||
|
||||
double[] range = ChartRenderer.valueRange(spec);
|
||||
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1], true);
|
||||
double lo = bounds[0];
|
||||
double hi = bounds[1];
|
||||
double unit = bounds[2];
|
||||
|
||||
DrawMlText.Style valStyle = valAxis.labelStyle;
|
||||
DrawMlText.Style catStyle = catAxis.labelStyle;
|
||||
|
||||
// 1. Поля под подписи осей
|
||||
double catGutter = 0;
|
||||
for (String c : cats) {
|
||||
catGutter = Math.max(catGutter, DrawMlText.textHeight(catStyle, g.getFontRenderContext()));
|
||||
}
|
||||
catGutter += 6;
|
||||
|
||||
// Word укрупняет шаг оси значений, если подписи не влезают: интервал
|
||||
// между делениями не меньше ~2,5 высоты строки подписи. В word-export.pdf
|
||||
// у line chart (область ~71 pt, подписи 9 pt) шаг вышел 2 (0…6),
|
||||
// а не 1 (0…5). Явные c:majorUnit/c:max не трогаем.
|
||||
if (valStyle != null && !valAxis.deleted
|
||||
&& valAxis.majorUnit == null && valAxis.max == null) {
|
||||
double labelH = DrawMlText.textHeight(valStyle, g.getFontRenderContext());
|
||||
double axisLen = Math.max(10,
|
||||
(horizontal ? box.getWidth() : box.getHeight()) - catGutter);
|
||||
while (hi - lo > unit && axisLen / ((hi - lo) / unit) < 2.5 * labelH) {
|
||||
unit = ChartRenderer.nextUnit(unit);
|
||||
double top = range[1] + (range[1] - range[0]) / 20.0;
|
||||
hi = Math.max(lo + unit, Math.ceil(top / unit - 1e-9) * unit);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> valLabels = new ArrayList<>();
|
||||
for (double v = lo; v <= hi + unit / 2; v += unit) {
|
||||
valLabels.add(ChartRenderer.formatValue(v, valAxis.numFmt));
|
||||
}
|
||||
double valGutter = 0;
|
||||
for (String l : valLabels) {
|
||||
valGutter = Math.max(valGutter, DrawMlText.textWidth(l, valStyle, g.getFontRenderContext()));
|
||||
}
|
||||
valGutter += 8;
|
||||
|
||||
Rectangle2D plot = horizontal
|
||||
? new Rectangle2D.Double(box.getX() + valGutter, box.getY() + catGutter,
|
||||
Math.max(10, box.getWidth() - valGutter),
|
||||
Math.max(10, box.getHeight() - catGutter))
|
||||
: new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
|
||||
Math.max(10, box.getWidth() - valGutter),
|
||||
Math.max(10, box.getHeight() - catGutter));
|
||||
|
||||
// 2. Сетка по делениям оси значений
|
||||
if (valAxis.gridlines && !valAxis.deleted) {
|
||||
g.setColor(valAxis.gridColor);
|
||||
g.setStroke(new BasicStroke(0.6f));
|
||||
int i = 0;
|
||||
for (double v = lo; v <= hi + unit / 2; v += unit, i++) {
|
||||
double t = (v - lo) / (hi - lo);
|
||||
if (horizontal) {
|
||||
double x = plot.getX() + t * plot.getWidth();
|
||||
g.draw(new java.awt.geom.Line2D.Double(x, plot.getY(),
|
||||
x, plot.getY() + plot.getHeight()));
|
||||
} else {
|
||||
double y = plot.getY() + (1 - t) * plot.getHeight();
|
||||
g.draw(new java.awt.geom.Line2D.Double(plot.getX(), y,
|
||||
plot.getX() + plot.getWidth(), y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Ряды
|
||||
switch (spec.type) {
|
||||
case LINE -> drawLines(g, spec, plot, palette, lo, hi, nCat, horizontal);
|
||||
case AREA -> drawAreas(g, spec, plot, palette, lo, hi, nCat, horizontal);
|
||||
case BAR, BAR_HORIZONTAL -> drawBars(g, spec, plot, palette, lo, hi, nCat, horizontal);
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Линия категории и подписи
|
||||
if (catAxis.axisLineColor != null && !catAxis.deleted) {
|
||||
g.setColor(catAxis.axisLineColor);
|
||||
g.setStroke(new BasicStroke((float) Math.max(0.5, catAxis.axisLineWidth)));
|
||||
if (horizontal) {
|
||||
g.draw(new java.awt.geom.Line2D.Double(plot.getX(), plot.getY(),
|
||||
plot.getX(), plot.getY() + plot.getHeight()));
|
||||
} else {
|
||||
double y = plot.getY() + plot.getHeight();
|
||||
g.draw(new java.awt.geom.Line2D.Double(plot.getX(), y,
|
||||
plot.getX() + plot.getWidth(), y));
|
||||
}
|
||||
}
|
||||
drawCategoryLabels(g, cats, plot, catStyle, horizontal);
|
||||
drawValueLabels(g, valLabels, plot, valStyle, lo, hi, horizontal);
|
||||
}
|
||||
|
||||
private static List<String> categoriesOf(ChartSpec spec, int nCat) {
|
||||
List<String> cats = new ArrayList<>();
|
||||
for (int i = 0; i < nCat; i++) {
|
||||
String label = null;
|
||||
if (i < spec.categories.size()) {
|
||||
label = spec.categories.get(i);
|
||||
}
|
||||
for (ChartSpec.Series s : spec.series) {
|
||||
if (label == null && i < s.categories.size()) {
|
||||
label = s.categories.get(i);
|
||||
}
|
||||
}
|
||||
cats.add(label == null ? "" : label);
|
||||
}
|
||||
return cats;
|
||||
}
|
||||
|
||||
private static void drawCategoryLabels(Graphics2D g, List<String> cats, Rectangle2D plot,
|
||||
DrawMlText.Style style, boolean horizontal) {
|
||||
if (style == null || cats.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
double n = cats.size();
|
||||
double h = DrawMlText.textHeight(style, g.getFontRenderContext()) + 2;
|
||||
for (int i = 0; i < n; i++) {
|
||||
String label = cats.get(i);
|
||||
if (label.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (horizontal) {
|
||||
double cy = plot.getY() + plot.getHeight() * (i + 0.5) / n;
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, style, "ctr")),
|
||||
new Rectangle2D.Double(plot.getX() - 60, cy - h / 2, 56, h),
|
||||
"r", "ctr", 1.0);
|
||||
} else {
|
||||
double cx = plot.getX() + plot.getWidth() * (i + 0.5) / n;
|
||||
double w = DrawMlText.textWidth(label, style, g.getFontRenderContext());
|
||||
double slot = plot.getWidth() / n;
|
||||
// Word прячет подписи, которые не помещаются в слот
|
||||
if (w > slot * 1.15) {
|
||||
continue;
|
||||
}
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, style, "ctr")),
|
||||
new Rectangle2D.Double(cx - w / 2, plot.getY() + plot.getHeight() + 3,
|
||||
w, h),
|
||||
"ctr", "t", 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void drawValueLabels(Graphics2D g, List<String> labels, Rectangle2D plot,
|
||||
DrawMlText.Style style, double lo, double hi,
|
||||
boolean horizontal) {
|
||||
if (style == null) {
|
||||
return;
|
||||
}
|
||||
double h = DrawMlText.textHeight(style, g.getFontRenderContext()) + 2;
|
||||
double span = hi - lo;
|
||||
for (int i = 0; i < labels.size(); i++) {
|
||||
double t = span == 0 ? 0 : i / (double) (labels.size() - 1);
|
||||
double w = DrawMlText.textWidth(labels.get(i), style, g.getFontRenderContext());
|
||||
if (horizontal) {
|
||||
double x = plot.getX() + t * plot.getWidth();
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(labels.get(i), style, "ctr")),
|
||||
new Rectangle2D.Double(x - w / 2, plot.getY() - h - 3, w, h),
|
||||
"ctr", "t", 1.0);
|
||||
} else {
|
||||
double y = plot.getY() + plot.getHeight() * (1 - t);
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(labels.get(i), style, "r")),
|
||||
new Rectangle2D.Double(plot.getX() - w - 6, y - h / 2, w, h),
|
||||
"r", "ctr", 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static double valuePos(double v, double lo, double hi, Rectangle2D plot,
|
||||
boolean horizontal) {
|
||||
double t = (v - lo) / (hi - lo);
|
||||
return horizontal
|
||||
? plot.getX() + t * plot.getWidth()
|
||||
: plot.getY() + (1 - t) * plot.getHeight();
|
||||
}
|
||||
|
||||
private static double catPos(int i, int n, Rectangle2D plot, boolean horizontal) {
|
||||
double t = (i + 0.5) / n;
|
||||
return horizontal
|
||||
? plot.getY() + t * plot.getHeight()
|
||||
: plot.getX() + t * plot.getWidth();
|
||||
}
|
||||
|
||||
private static void drawLines(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
||||
List<Color> palette, double lo, double hi, int nCat,
|
||||
boolean horizontal) {
|
||||
for (int si = 0; si < spec.series.size(); si++) {
|
||||
ChartSpec.Series s = spec.series.get(si);
|
||||
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
|
||||
double width = s.lineWidth > 0 ? s.lineWidth : 2.25;
|
||||
g.setColor(c);
|
||||
g.setStroke(new BasicStroke((float) width, BasicStroke.CAP_ROUND,
|
||||
BasicStroke.JOIN_ROUND));
|
||||
List<Double> along = new ArrayList<>();
|
||||
List<Double> cross = new ArrayList<>();
|
||||
for (int i = 0; i < s.values.size(); i++) {
|
||||
Double v = s.values.get(i);
|
||||
if (v == null) {
|
||||
continue;
|
||||
}
|
||||
along.add(catPos(i, nCat, plot, horizontal));
|
||||
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
||||
}
|
||||
if (along.size() > 1) {
|
||||
g.draw(ChartRenderer.polyline(along, cross, false));
|
||||
}
|
||||
if (s.marker) {
|
||||
g.setColor(c);
|
||||
for (int i = 0; i < along.size(); i++) {
|
||||
double a = along.get(i);
|
||||
double b = cross.get(i);
|
||||
double r = 2.2;
|
||||
if (horizontal) {
|
||||
g.fill(new Rectangle2D.Double(a - r, b - r, 2 * r, 2 * r));
|
||||
} else {
|
||||
g.fill(new java.awt.geom.Ellipse2D.Double(a - r, b - r, 2 * r, 2 * r));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
||||
List<Color> palette, double lo, double hi, int nCat,
|
||||
boolean horizontal) {
|
||||
double baseline = horizontal ? plot.getX() : plot.getY() + plot.getHeight();
|
||||
for (int si = 0; si < spec.series.size(); si++) {
|
||||
ChartSpec.Series s = spec.series.get(si);
|
||||
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
|
||||
List<Double> along = new ArrayList<>();
|
||||
List<Double> cross = new ArrayList<>();
|
||||
for (int i = 0; i < s.values.size(); i++) {
|
||||
Double v = s.values.get(i);
|
||||
if (v == null) {
|
||||
continue;
|
||||
}
|
||||
along.add(catPos(i, nCat, plot, horizontal));
|
||||
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
||||
}
|
||||
if (along.size() < 2) {
|
||||
continue;
|
||||
}
|
||||
Path2D p = new Path2D.Double();
|
||||
p.moveTo(toX(along.get(0), cross.get(0), baseline, horizontal),
|
||||
toY(along.get(0), cross.get(0), baseline, horizontal));
|
||||
for (int i = 0; i < along.size(); i++) {
|
||||
p.lineTo(toX(along.get(i), cross.get(i), baseline, horizontal),
|
||||
toY(along.get(i), cross.get(i), baseline, horizontal));
|
||||
}
|
||||
p.lineTo(toX(along.get(along.size() - 1), cross.get(cross.size() - 1),
|
||||
baseline, horizontal),
|
||||
toY(along.get(along.size() - 1), cross.get(cross.size() - 1),
|
||||
baseline, horizontal));
|
||||
p.lineTo(toX(along.get(0), cross.get(0), baseline, horizontal),
|
||||
toY(along.get(0), cross.get(0), baseline, horizontal));
|
||||
p.closePath();
|
||||
g.setColor(DrawMlColor.withAlpha(c, 0.55));
|
||||
g.fill(p);
|
||||
g.setColor(c);
|
||||
g.setStroke(new BasicStroke(1.2f));
|
||||
g.draw(p);
|
||||
}
|
||||
}
|
||||
|
||||
/** (вдоль категории, вдоль значения) -> экранные координаты. */
|
||||
private static double toX(double along, double cross, double baseline, boolean horizontal) {
|
||||
return horizontal ? cross : along;
|
||||
}
|
||||
|
||||
private static double toY(double along, double cross, double baseline, boolean horizontal) {
|
||||
return horizontal ? along : cross;
|
||||
}
|
||||
|
||||
private static void drawBars(Graphics2D g, ChartSpec spec, Rectangle2D plot,
|
||||
List<Color> palette, double lo, double hi, int nCat,
|
||||
boolean horizontal) {
|
||||
int nSer = spec.series.size();
|
||||
double slot = (horizontal ? plot.getHeight() : plot.getWidth()) / nCat;
|
||||
double group = slot * 0.82;
|
||||
double bar = group / Math.max(1, nSer);
|
||||
double zero = valuePos(0, lo, hi, plot, horizontal);
|
||||
for (int si = 0; si < nSer; si++) {
|
||||
ChartSpec.Series s = spec.series.get(si);
|
||||
for (int i = 0; i < s.values.size(); i++) {
|
||||
Double v = s.values.get(i);
|
||||
if (v == null) {
|
||||
continue;
|
||||
}
|
||||
Color c = s.fillAt(i, palette);
|
||||
g.setColor(c);
|
||||
double center = catPos(i, nCat, plot, horizontal);
|
||||
double start = center - group / 2 + si * bar;
|
||||
double end = valuePos(v, lo, hi, plot, horizontal);
|
||||
if (horizontal) {
|
||||
g.fill(new Rectangle2D.Double(Math.min(zero, end), start,
|
||||
Math.abs(end - zero), bar * 0.92));
|
||||
} else {
|
||||
g.fill(new Rectangle2D.Double(start, Math.min(zero, end),
|
||||
bar * 0.92, Math.abs(end - zero)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import ru.pjandro.wordpdf.internal.chart.DrawMlText.Paragraph;
|
||||
import ru.pjandro.wordpdf.internal.chart.DrawMlText.Style;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.geom.Line2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.geom.RoundRectangle2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Рендер графика DrawingML в растр. Кадрирование (рамка chartSpace),
|
||||
* заголовок и легенда общие; область построения рисует специфичный
|
||||
* художник: {@link PiePainter}, {@link CartesianPainter} или
|
||||
* {@link Surface3dPainter}.
|
||||
*
|
||||
* Все размеры внутри — в пунктах (pt), как в Word; растр создаётся с
|
||||
* множителем {@link #DPI}.
|
||||
*/
|
||||
final class ChartRenderer {
|
||||
|
||||
/** Разрешение растра: 300 dpi, чтобы подписи не мылились при печати. */
|
||||
static final int DPI = 300;
|
||||
|
||||
private static final double PADDING = 4.0;
|
||||
|
||||
private ChartRenderer() {
|
||||
}
|
||||
|
||||
static BufferedImage render(ChartSpec spec, double widthPt, double heightPt,
|
||||
DrawMlColor colors) {
|
||||
int w = Math.max(16, (int) Math.round(widthPt * DPI / 72.0));
|
||||
int h = Math.max(16, (int) Math.round(heightPt * DPI / 72.0));
|
||||
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
try {
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
|
||||
RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
|
||||
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
|
||||
RenderingHints.VALUE_STROKE_PURE);
|
||||
g.scale(DPI / 72.0, DPI / 72.0);
|
||||
drawFrame(g, spec, widthPt, heightPt);
|
||||
|
||||
Rectangle2D box = new Rectangle2D.Double(PADDING, PADDING,
|
||||
widthPt - 2 * PADDING, heightPt - 2 * PADDING);
|
||||
List<Color> palette = ChartSpec.palette(colors);
|
||||
|
||||
double titleH = drawTitle(g, spec, box);
|
||||
box = new Rectangle2D.Double(box.getX(), box.getY() + titleH,
|
||||
box.getWidth(), box.getHeight() - titleH);
|
||||
|
||||
Legend legend = measureLegend(g, spec, palette);
|
||||
double legendH = legend == null ? 0 : legend.height;
|
||||
if (legend != null && "b".equals(spec.legendPos)) {
|
||||
legend.draw(g, box.getX(), box.getY() + box.getHeight() - legendH,
|
||||
box.getWidth());
|
||||
box = new Rectangle2D.Double(box.getX(), box.getY(),
|
||||
box.getWidth(), box.getHeight() - legendH);
|
||||
} else if (legend != null && "t".equals(spec.legendPos)) {
|
||||
legend.draw(g, box.getX(), box.getY(), box.getWidth());
|
||||
box = new Rectangle2D.Double(box.getX(), box.getY() + legendH,
|
||||
box.getWidth(), box.getHeight() - legendH);
|
||||
}
|
||||
|
||||
switch (spec.type) {
|
||||
case PIE, PIE3D, DOUGHNUT ->
|
||||
PiePainter.paint(g, spec, box, palette, legend);
|
||||
case LINE, AREA, BAR, BAR_HORIZONTAL ->
|
||||
CartesianPainter.paint(g, spec, box, palette);
|
||||
case SURFACE3D ->
|
||||
Surface3dPainter.paint(g, spec, box, palette);
|
||||
default -> { /* UNSUPPORTED: вызывающий не должен сюда доходить */ }
|
||||
}
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
/** a:spPr chartSpace: заливка и тонкая скруглённая рамка. */
|
||||
private static void drawFrame(Graphics2D g, ChartSpec spec, double w, double h) {
|
||||
if (spec.chartFill != null) {
|
||||
g.setColor(spec.chartFill);
|
||||
g.fill(new RoundRectangle2D.Double(0, 0, w, h, 3, 3));
|
||||
}
|
||||
if (spec.chartBorder != null) {
|
||||
g.setColor(spec.chartBorder);
|
||||
g.setStroke(new BasicStroke((float) Math.max(0.5, spec.chartBorderWidth)));
|
||||
g.draw(new RoundRectangle2D.Double(0.25, 0.25, w - 0.5, h - 0.5, 3, 3));
|
||||
}
|
||||
}
|
||||
|
||||
/** Заголовок сверху; возвращает занятую высоту. */
|
||||
private static double drawTitle(Graphics2D g, ChartSpec spec, Rectangle2D box) {
|
||||
if (spec.title == null || spec.titleStyle == null) {
|
||||
return 0;
|
||||
}
|
||||
double lineH = DrawMlText.textHeight(spec.titleStyle, g.getFontRenderContext());
|
||||
double width = DrawMlText.textWidth(spec.title, spec.titleStyle, g.getFontRenderContext());
|
||||
double height = lineH + 4;
|
||||
if (width > box.getWidth()) {
|
||||
DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")),
|
||||
new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height * 2),
|
||||
"ctr", "t", 1.0);
|
||||
return height * 2;
|
||||
}
|
||||
DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")),
|
||||
new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height),
|
||||
"ctr", "ctr", 1.0);
|
||||
return height;
|
||||
}
|
||||
|
||||
/** Легенда: метки + квадратики цветов, одна строка по центру. */
|
||||
static final class Legend {
|
||||
/** lineWidth > 0 — маркер-отрезок (линейный ряд), иначе — квадратик.
|
||||
* В Word у линейных рядов в легенде короткая линия той же толщины,
|
||||
* что и сама линия; у круговых — маленький квадратик. */
|
||||
record Entry(String label, Color color, double lineWidth) {
|
||||
Entry(String label, Color color) {
|
||||
this(label, color, -1);
|
||||
}
|
||||
}
|
||||
|
||||
final List<Entry> entries = new ArrayList<>();
|
||||
Style style;
|
||||
double height;
|
||||
double totalWidth;
|
||||
double square;
|
||||
double lineLen;
|
||||
|
||||
void draw(Graphics2D g, double x, double y, double boxWidth) {
|
||||
double startX = x + (boxWidth - totalWidth) / 2.0;
|
||||
double midY = y + height / 2.0;
|
||||
for (Entry e : entries) {
|
||||
g.setColor(e.color());
|
||||
if (e.lineWidth() > 0) {
|
||||
g.setStroke(new BasicStroke((float) e.lineWidth(),
|
||||
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
|
||||
g.draw(new Line2D.Double(startX, midY, startX + lineLen, midY));
|
||||
startX += lineLen + 3;
|
||||
} else {
|
||||
g.fill(new Rectangle2D.Double(startX, midY - square / 2.0, square, square));
|
||||
startX += square + 3;
|
||||
}
|
||||
double tw = DrawMlText.textWidth(e.label(), style, g.getFontRenderContext());
|
||||
DrawMlText.paint(g, List.of(new Paragraph(e.label(), style, "l")),
|
||||
new Rectangle2D.Double(startX, y, tw, height), "l", "ctr", 1.0);
|
||||
startX += tw + 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Legend measureLegend(Graphics2D g, ChartSpec spec, List<Color> palette) {
|
||||
if (spec.legendPos == null) {
|
||||
return null;
|
||||
}
|
||||
Style style = spec.legendStyle != null ? spec.legendStyle
|
||||
: new Style(9, false, false, new Color(0x59, 0x59, 0x59), "carlito");
|
||||
Legend legend = new Legend();
|
||||
legend.style = style;
|
||||
switch (spec.type) {
|
||||
case PIE, PIE3D, DOUGHNUT -> {
|
||||
ChartSpec.Series s = spec.series.isEmpty() ? null : spec.series.get(0);
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < s.values.size(); i++) {
|
||||
String label = i < s.categories.size() ? s.categories.get(i) : "";
|
||||
legend.entries.add(new Legend.Entry(label, s.fillAt(i, palette)));
|
||||
}
|
||||
}
|
||||
case SURFACE3D -> {
|
||||
List<Double> vals = spec.series.isEmpty()
|
||||
? List.of() : spec.series.get(0).values;
|
||||
double min = Double.MAX_VALUE;
|
||||
double max = -Double.MAX_VALUE;
|
||||
for (ChartSpec.Series s : spec.series) {
|
||||
for (Double v : s.values) {
|
||||
if (v != null) {
|
||||
min = Math.min(min, v);
|
||||
max = Math.max(max, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (min > max) {
|
||||
return null;
|
||||
}
|
||||
double[] bounds = axisBounds(spec.valAxis, min, max);
|
||||
double unit = bounds[2];
|
||||
double lo = bounds[0];
|
||||
double hi = bounds[1];
|
||||
int idx = 0;
|
||||
for (double b = lo; b < hi - 1e-9; b += unit) {
|
||||
Color c = spec.bandColors.isEmpty()
|
||||
? palette.get(idx % palette.size())
|
||||
: spec.bandColors.get(idx % spec.bandColors.size());
|
||||
legend.entries.add(new Legend.Entry(
|
||||
formatValue(b, "General") + "-" + formatValue(b + unit, "General"), c));
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
for (int i = 0; i < spec.series.size(); i++) {
|
||||
ChartSpec.Series s = spec.series.get(i);
|
||||
Color c = s.lineColor != null ? s.lineColor
|
||||
: s.fillAt(0, palette);
|
||||
boolean lineLike = spec.type == ChartSpec.Type.LINE;
|
||||
legend.entries.add(new Legend.Entry(s.name == null ? "" : s.name, c,
|
||||
lineLike ? Math.max(1.0, s.lineWidth > 0 ? s.lineWidth : 2.25) : -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (legend.entries.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
// Размер маркера легенды в Word зависит от типа: у круговой диаграммы
|
||||
// квадратик ~0,3 кегля (замер по word-export.pdf — 12 px при 9 pt и 300 dpi),
|
||||
// у прочих ~0,55 кегля (21 px), у линейных рядов — отрезок ~2,4 кегля
|
||||
// (89 px) толщиной с линию ряда.
|
||||
boolean pie = spec.type == ChartSpec.Type.PIE || spec.type == ChartSpec.Type.PIE3D
|
||||
|| spec.type == ChartSpec.Type.DOUGHNUT;
|
||||
legend.square = style.sizePt() * (pie ? 0.32 : 0.55);
|
||||
legend.lineLen = style.sizePt() * 2.4;
|
||||
double width = 0;
|
||||
for (Legend.Entry e : legend.entries) {
|
||||
double marker = e.lineWidth() > 0 ? legend.lineLen : legend.square;
|
||||
width += marker + 3 + DrawMlText.textWidth(e.label(), style, g.getFontRenderContext()) + 8;
|
||||
}
|
||||
legend.totalWidth = width;
|
||||
legend.height = Math.max(Math.max(legend.square, legend.lineLen * 0.2),
|
||||
DrawMlText.textHeight(style, g.getFontRenderContext())) + 4;
|
||||
return legend;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Общие вычисления осей
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** Диапазон всех значений всех рядов. */
|
||||
static double[] valueRange(ChartSpec spec) {
|
||||
double min = Double.MAX_VALUE;
|
||||
double max = -Double.MAX_VALUE;
|
||||
for (ChartSpec.Series s : spec.series) {
|
||||
for (Double v : s.values) {
|
||||
if (v != null) {
|
||||
min = Math.min(min, v);
|
||||
max = Math.max(max, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (min > max) {
|
||||
return new double[]{0, 1};
|
||||
}
|
||||
if (min > 0) {
|
||||
min = 0;
|
||||
}
|
||||
if (max < 0) {
|
||||
max = 0;
|
||||
}
|
||||
if (min == max) {
|
||||
max = min + 1;
|
||||
}
|
||||
return new double[]{min, max};
|
||||
}
|
||||
|
||||
/**
|
||||
* «Круглый» шаг делений (1/2/5 * 10^n), как подбирает Word.
|
||||
*/
|
||||
static double niceUnit(double raw) {
|
||||
if (raw <= 0 || !Double.isFinite(raw)) {
|
||||
return 1;
|
||||
}
|
||||
double exp = Math.floor(Math.log10(raw));
|
||||
double base = Math.pow(10, exp);
|
||||
double frac = raw / base;
|
||||
if (frac <= 1) {
|
||||
return base;
|
||||
}
|
||||
if (frac <= 2) {
|
||||
return 2 * base;
|
||||
}
|
||||
if (frac <= 5) {
|
||||
return 5 * base;
|
||||
}
|
||||
return 10 * base;
|
||||
}
|
||||
|
||||
/** Следующий «круглый» шаг после unit: 1→2→5→10… (в тех же 10^n). */
|
||||
static double nextUnit(double unit) {
|
||||
double exp = Math.floor(Math.log10(unit) + 1e-9);
|
||||
double base = Math.pow(10, exp);
|
||||
double frac = unit / base;
|
||||
if (frac < 2 - 1e-9) {
|
||||
return 2 * base;
|
||||
}
|
||||
if (frac < 5 - 1e-9) {
|
||||
return 5 * base;
|
||||
}
|
||||
return 10 * base;
|
||||
}
|
||||
|
||||
/** Границы оси + шаг: min/max округляются до кратных unit. */
|
||||
static double[] axisBounds(ChartSpec.AxisSpec axis, double dataMin, double dataMax) {
|
||||
return axisBounds(axis, dataMin, dataMax, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param padMax для декартовых осей Word поднимает верхнюю границу за
|
||||
* максимум данных: «первое деление выше Ymax + (Ymax − Ymin)/20»
|
||||
* (KB101939). Без этого линия упёрта в верхнюю границу области
|
||||
* построения, а в Word она занимает 5/6 высоты.
|
||||
* Для surface3D отступ не нужен: там ось задаётся полосами
|
||||
* (c:bandFmts — ровно 5 полос до максимума данных).
|
||||
*/
|
||||
static double[] axisBounds(ChartSpec.AxisSpec axis, double dataMin, double dataMax,
|
||||
boolean padMax) {
|
||||
double unit = axis != null && axis.majorUnit != null
|
||||
? axis.majorUnit
|
||||
: niceUnit((dataMax - dataMin) / 5.0);
|
||||
// Линейная ось значений без явного c:min всегда начинается с нуля
|
||||
// (так делает Word) — иначе surface3D теряет нижнюю полосу и легенда
|
||||
// съезжает с «0-1 … 4-5» на «1-2 … 4-5».
|
||||
double lo = axis != null && axis.min != null ? axis.min
|
||||
: (dataMin >= 0 ? 0 : Math.floor(dataMin / unit) * unit);
|
||||
double hi;
|
||||
if (axis != null && axis.max != null) {
|
||||
hi = axis.max;
|
||||
} else {
|
||||
double top = padMax ? dataMax + (dataMax - dataMin) / 20.0 : dataMax;
|
||||
hi = Math.max(lo + unit, Math.ceil(top / unit - 1e-9) * unit);
|
||||
}
|
||||
if (hi <= lo) {
|
||||
hi = lo + unit;
|
||||
}
|
||||
return new double[]{lo, hi, unit};
|
||||
}
|
||||
|
||||
/** Формат числа для подписей оси ("General" -> без лишних нулей). */
|
||||
static String formatValue(double v, String fmt) {
|
||||
if (fmt != null && !fmt.equalsIgnoreCase("General")) {
|
||||
if (fmt.contains("0.00")) {
|
||||
return String.format(java.util.Locale.ROOT, "%.2f", v);
|
||||
}
|
||||
if (fmt.contains("0.0")) {
|
||||
return String.format(java.util.Locale.ROOT, "%.1f", v);
|
||||
}
|
||||
}
|
||||
if (Math.abs(v - Math.rint(v)) < 1e-9) {
|
||||
return String.valueOf((long) Math.rint(v));
|
||||
}
|
||||
String s = String.format(java.util.Locale.ROOT, "%.2f", v);
|
||||
return s.replaceAll("0+$", "").replaceAll("\\.$", "");
|
||||
}
|
||||
|
||||
/** Контур многоугольника по точкам. */
|
||||
static Path2D polyline(List<Double> xs, List<Double> ys, boolean close) {
|
||||
Path2D p = new Path2D.Double();
|
||||
for (int i = 0; i < xs.size(); i++) {
|
||||
if (i == 0) {
|
||||
p.moveTo(xs.get(i), ys.get(i));
|
||||
} else {
|
||||
p.lineTo(xs.get(i), ys.get(i));
|
||||
}
|
||||
}
|
||||
if (close) {
|
||||
p.closePath();
|
||||
}
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import org.docx4j.dml.CTShapeProperties;
|
||||
import org.docx4j.dml.CTTextBody;
|
||||
import org.docx4j.dml.chart.CTAxDataSource;
|
||||
import org.docx4j.dml.chart.CTAxPos;
|
||||
import org.docx4j.dml.chart.CTBoolean;
|
||||
import org.docx4j.dml.chart.CTBandFmt;
|
||||
import org.docx4j.dml.chart.CTBandFmts;
|
||||
import org.docx4j.dml.chart.CTBarChart;
|
||||
import org.docx4j.dml.chart.CTBarSer;
|
||||
import org.docx4j.dml.chart.CTCatAx;
|
||||
import org.docx4j.dml.chart.CTChart;
|
||||
import org.docx4j.dml.chart.CTChartLines;
|
||||
import org.docx4j.dml.chart.CTChartSpace;
|
||||
import org.docx4j.dml.chart.CTDateAx;
|
||||
import org.docx4j.dml.chart.CTDPt;
|
||||
import org.docx4j.dml.chart.CTDoughnutChart;
|
||||
import org.docx4j.dml.chart.CTLineChart;
|
||||
import org.docx4j.dml.chart.CTLineSer;
|
||||
import org.docx4j.dml.chart.CTMarker;
|
||||
import org.docx4j.dml.chart.STMarkerStyle;
|
||||
import org.docx4j.dml.chart.CTNumDataSource;
|
||||
import org.docx4j.dml.chart.CTNumVal;
|
||||
import org.docx4j.dml.chart.CTPlotArea;
|
||||
import org.docx4j.dml.chart.CTSerAx;
|
||||
import org.docx4j.dml.chart.CTSerTx;
|
||||
import org.docx4j.dml.chart.CTSurface3DChart;
|
||||
import org.docx4j.dml.chart.CTSurfaceSer;
|
||||
import org.docx4j.dml.chart.CTScaling;
|
||||
import org.docx4j.dml.chart.CTPie3DChart;
|
||||
import org.docx4j.dml.chart.CTPieChart;
|
||||
import org.docx4j.dml.chart.CTPieSer;
|
||||
import org.docx4j.dml.chart.CTStrVal;
|
||||
import org.docx4j.dml.chart.CTTitle;
|
||||
import org.docx4j.dml.chart.CTTx;
|
||||
import org.docx4j.dml.chart.CTValAx;
|
||||
import org.docx4j.dml.chart.CTView3D;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Модель графика DrawingML (c:chartSpace), сокращённая до того, что
|
||||
* действительно нужно для растрового рендера: тип, ряды, категории,
|
||||
* оси, легенда, заголовок, параметры 3D и цвета полос surface.
|
||||
*
|
||||
* Данные берутся из кэшей ({@code c:numCache}/{@code c:strCache}):
|
||||
* внешний xlsx (c:externalData) не читается — Word всегда кладёт
|
||||
* кэш значений в xml графика.
|
||||
*/
|
||||
final class ChartSpec {
|
||||
|
||||
/** Встроенный заголовок Word для графика с пустым c:title. */
|
||||
static final String AUTO_TITLE = "Chart Title";
|
||||
|
||||
enum Type {
|
||||
PIE, PIE3D, DOUGHNUT, BAR, BAR_HORIZONTAL, LINE, AREA, SURFACE3D, UNSUPPORTED
|
||||
}
|
||||
|
||||
/** Один ряд: значения + стили (ряд и переопределения по точкам). */
|
||||
static final class Series {
|
||||
String name;
|
||||
final List<Double> values = new ArrayList<>();
|
||||
final List<String> categories = new ArrayList<>();
|
||||
Color fill;
|
||||
final Map<Integer, Color> pointFills = new HashMap<>();
|
||||
Color lineColor;
|
||||
double lineWidth = -1;
|
||||
boolean lineNoFill;
|
||||
boolean outlineNoFill;
|
||||
Color outlineColor;
|
||||
double outlineWidth = -1;
|
||||
boolean marker = true;
|
||||
String markerSymbol;
|
||||
|
||||
Color fillAt(int i, List<Color> palette) {
|
||||
Color c = pointFills.get(i);
|
||||
if (c != null) {
|
||||
return c;
|
||||
}
|
||||
return fill != null ? fill : palette.get(i % palette.size());
|
||||
}
|
||||
}
|
||||
|
||||
/** Одна ось: границы, деления, сетка, стиль подписей. */
|
||||
static final class AxisSpec {
|
||||
boolean deleted;
|
||||
String pos = "b";
|
||||
Double min;
|
||||
Double max;
|
||||
Double majorUnit;
|
||||
boolean gridlines;
|
||||
Color gridColor = new Color(0xD9, 0xD9, 0xD9);
|
||||
Color axisLineColor = new Color(0xBF, 0xBF, 0xBF);
|
||||
double axisLineWidth = 0.75;
|
||||
DrawMlText.Style labelStyle;
|
||||
String numFmt = "General";
|
||||
}
|
||||
|
||||
Type type = Type.UNSUPPORTED;
|
||||
String title;
|
||||
DrawMlText.Style titleStyle;
|
||||
DrawMlText.Style legendStyle;
|
||||
String legendPos = "b";
|
||||
final List<Series> series = new ArrayList<>();
|
||||
final List<String> categories = new ArrayList<>();
|
||||
AxisSpec valAxis;
|
||||
AxisSpec catAxis;
|
||||
AxisSpec serAxis;
|
||||
double rotX = 30;
|
||||
double rotY = 0;
|
||||
double depthPercent = 100;
|
||||
double perspective = 30;
|
||||
boolean rightAngledAxes = true;
|
||||
final List<Color> bandColors = new ArrayList<>();
|
||||
boolean wireframe;
|
||||
Color chartFill = Color.WHITE;
|
||||
Color chartBorder = new Color(0xBF, 0xBF, 0xBF);
|
||||
double chartBorderWidth = 0.75;
|
||||
|
||||
/** package-private: тестам нужен пустой spec без CTChartSpace. */
|
||||
ChartSpec() {
|
||||
}
|
||||
|
||||
/** Цвета акцента темы — базовая палитра рядов (как в Word). */
|
||||
static List<Color> palette(DrawMlColor colors) {
|
||||
List<Color> p = new ArrayList<>();
|
||||
for (String name : new String[]{"accent1", "accent2", "accent3",
|
||||
"accent4", "accent5", "accent6"}) {
|
||||
p.add(colors.schemeColor(name));
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Разбор c:chartSpace. */
|
||||
static ChartSpec parse(CTChartSpace space, DrawMlColor colors) {
|
||||
ChartSpec spec = new ChartSpec();
|
||||
CTChart chart = space.getChart();
|
||||
if (chart == null) {
|
||||
return spec;
|
||||
}
|
||||
List<Color> palette = palette(colors);
|
||||
|
||||
readChartFrame(space, spec, colors);
|
||||
readView3D(chart, spec);
|
||||
|
||||
CTPlotArea pa = chart.getPlotArea();
|
||||
if (pa != null) {
|
||||
for (Object group : pa.getAreaChartOrArea3DChartOrLineChart()) {
|
||||
readGroup(group, spec, colors, palette);
|
||||
}
|
||||
for (Object ax : pa.getValAxOrCatAxOrDateAx()) {
|
||||
AxisSpec a = readAxis(ax, colors);
|
||||
if (ax instanceof CTValAx) {
|
||||
spec.valAxis = a;
|
||||
} else if (ax instanceof CTCatAx) {
|
||||
spec.catAxis = a;
|
||||
} else if (ax instanceof CTSerAx) {
|
||||
spec.serAxis = a;
|
||||
} else if (ax instanceof CTDateAx && spec.catAxis == null) {
|
||||
spec.catAxis = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
readLegend(chart, spec, colors);
|
||||
readTitle(chart, spec, colors);
|
||||
if (spec.categories.isEmpty() && !spec.series.isEmpty()) {
|
||||
spec.categories.addAll(spec.series.get(0).categories);
|
||||
}
|
||||
return spec;
|
||||
}
|
||||
|
||||
private static void readChartFrame(CTChartSpace space, ChartSpec spec, DrawMlColor colors) {
|
||||
CTShapeProperties sp = space.getSpPr();
|
||||
if (sp == null) {
|
||||
return;
|
||||
}
|
||||
if (sp.getSolidFill() != null) {
|
||||
Color c = colors.resolveFill(sp.getSolidFill());
|
||||
if (c != null) {
|
||||
spec.chartFill = c;
|
||||
}
|
||||
}
|
||||
if (sp.getLn() != null) {
|
||||
if (sp.getLn().getNoFill() != null) {
|
||||
spec.chartBorder = null;
|
||||
} else if (sp.getLn().getSolidFill() != null) {
|
||||
Color c = colors.resolveFill(sp.getLn().getSolidFill());
|
||||
if (c != null) {
|
||||
spec.chartBorder = c;
|
||||
}
|
||||
}
|
||||
if (sp.getLn().getW() != null) {
|
||||
spec.chartBorderWidth = emuToPt(sp.getLn().getW());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void readView3D(CTChart chart, ChartSpec spec) {
|
||||
CTView3D v = chart.getView3D();
|
||||
if (v == null) {
|
||||
return;
|
||||
}
|
||||
if (v.getRotX() != null) {
|
||||
spec.rotX = v.getRotX().getVal();
|
||||
}
|
||||
if (v.getRotY() != null) {
|
||||
int ry = v.getRotY().getVal();
|
||||
spec.rotY = ry < 0 ? ry + 360 : ry;
|
||||
}
|
||||
if (v.getDepthPercent() != null) {
|
||||
spec.depthPercent = v.getDepthPercent().getVal();
|
||||
}
|
||||
if (v.getPerspective() != null) {
|
||||
spec.perspective = v.getPerspective().getVal();
|
||||
}
|
||||
if (v.getRAngAx() != null) {
|
||||
spec.rightAngledAxes = isTrue(v.getRAngAx());
|
||||
}
|
||||
}
|
||||
|
||||
private static void readGroup(Object group, ChartSpec spec, DrawMlColor colors,
|
||||
List<Color> palette) {
|
||||
if (group instanceof CTPie3DChart g) {
|
||||
spec.type = Type.PIE3D;
|
||||
for (CTPieSer s : g.getSer()) {
|
||||
spec.series.add(readPieSer(s, colors, palette));
|
||||
}
|
||||
} else if (group instanceof CTPieChart g) {
|
||||
spec.type = Type.PIE;
|
||||
for (CTPieSer s : g.getSer()) {
|
||||
spec.series.add(readPieSer(s, colors, palette));
|
||||
}
|
||||
} else if (group instanceof CTDoughnutChart g) {
|
||||
spec.type = Type.DOUGHNUT;
|
||||
for (CTPieSer s : g.getSer()) {
|
||||
spec.series.add(readPieSer(s, colors, palette));
|
||||
}
|
||||
} else if (group instanceof CTLineChart g) {
|
||||
spec.type = Type.LINE;
|
||||
for (CTLineSer s : g.getSer()) {
|
||||
Series ser = new Series();
|
||||
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
|
||||
readLineProps(s.getSpPr(), ser, colors, palette,
|
||||
spec.series.size());
|
||||
CTMarker m = s.getMarker();
|
||||
if (m != null) {
|
||||
ser.marker = m.getSymbol() == null
|
||||
|| m.getSymbol().getVal() != STMarkerStyle.NONE;
|
||||
if (m.getSymbol() != null) {
|
||||
ser.markerSymbol = m.getSymbol().getVal().value();
|
||||
}
|
||||
}
|
||||
spec.series.add(ser);
|
||||
}
|
||||
} else if (group instanceof CTBarChart g) {
|
||||
boolean horizontal = g.getBarDir() != null
|
||||
&& g.getBarDir().getVal() != null
|
||||
&& g.getBarDir().getVal().value().equalsIgnoreCase("bar");
|
||||
spec.type = horizontal ? Type.BAR_HORIZONTAL : Type.BAR;
|
||||
for (CTBarSer s : g.getSer()) {
|
||||
Series ser = new Series();
|
||||
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
|
||||
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
|
||||
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
||||
}
|
||||
spec.series.add(ser);
|
||||
}
|
||||
} else if (group instanceof org.docx4j.dml.chart.CTAreaChart g) {
|
||||
spec.type = Type.AREA;
|
||||
for (org.docx4j.dml.chart.CTAreaSer s : g.getSer()) {
|
||||
Series ser = new Series();
|
||||
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
|
||||
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
|
||||
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
||||
}
|
||||
readLineProps(s.getSpPr(), ser, colors, palette, spec.series.size());
|
||||
spec.series.add(ser);
|
||||
}
|
||||
} else if (group instanceof CTSurface3DChart g) {
|
||||
spec.type = Type.SURFACE3D;
|
||||
spec.wireframe = isTrue(g.getWireframe());
|
||||
for (CTSurfaceSer s : g.getSer()) {
|
||||
Series ser = new Series();
|
||||
readCommon(s.getTx(), s.getCat(), s.getVal(), List.of(), ser, colors, palette);
|
||||
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
|
||||
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
||||
}
|
||||
spec.series.add(ser);
|
||||
}
|
||||
CTBandFmts bf = g.getBandFmts();
|
||||
if (bf != null) {
|
||||
for (CTBandFmt b : bf.getBandFmt()) {
|
||||
Color c = b.getSpPr() != null && b.getSpPr().getSolidFill() != null
|
||||
? colors.resolveFill(b.getSpPr().getSolidFill())
|
||||
: null;
|
||||
spec.bandColors.add(c != null ? c
|
||||
: palette.get((int) (b.getIdx().getVal() % palette.size())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Series readPieSer(CTPieSer s, DrawMlColor colors, List<Color> palette) {
|
||||
Series ser = new Series();
|
||||
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors, palette);
|
||||
if (s.getSpPr() != null) {
|
||||
if (s.getSpPr().getSolidFill() != null) {
|
||||
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
|
||||
}
|
||||
if (s.getSpPr().getLn() != null) {
|
||||
if (s.getSpPr().getLn().getNoFill() != null) {
|
||||
ser.outlineNoFill = true;
|
||||
} else if (s.getSpPr().getLn().getSolidFill() != null) {
|
||||
ser.outlineColor = colors.resolveFill(s.getSpPr().getLn().getSolidFill());
|
||||
}
|
||||
if (s.getSpPr().getLn().getW() != null) {
|
||||
ser.outlineWidth = emuToPt(s.getSpPr().getLn().getW());
|
||||
}
|
||||
}
|
||||
}
|
||||
return ser;
|
||||
}
|
||||
|
||||
/** Общее для всех типов: имя, категории, значения, переопределения точек. */
|
||||
private static void readCommon(CTSerTx tx, CTAxDataSource cat, CTNumDataSource val,
|
||||
List<CTDPt> dPts, Series ser, DrawMlColor colors,
|
||||
List<Color> palette) {
|
||||
ser.name = seriesName(tx);
|
||||
ser.categories.addAll(categoryNames(cat));
|
||||
if (val != null) {
|
||||
var num = val.getNumRef() != null ? val.getNumRef().getNumCache() : val.getNumLit();
|
||||
if (num != null) {
|
||||
int count = num.getPtCount() != null ? (int) num.getPtCount().getVal() : -1;
|
||||
for (CTNumVal v : num.getPt()) {
|
||||
while (ser.values.size() < (int) v.getIdx()) {
|
||||
ser.values.add(null);
|
||||
}
|
||||
ser.values.add(parseDouble(v.getV()));
|
||||
}
|
||||
if (count > ser.values.size()) {
|
||||
while (ser.values.size() < count) {
|
||||
ser.values.add(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (CTDPt dp : dPts) {
|
||||
if (dp.getSpPr() == null || dp.getSpPr().getSolidFill() == null
|
||||
|| dp.getIdx() == null) {
|
||||
continue;
|
||||
}
|
||||
Color c = colors.resolveFill(dp.getSpPr().getSolidFill());
|
||||
if (c != null) {
|
||||
ser.pointFills.put((int) dp.getIdx().getVal(), c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** a:ln ряда (цвет и толщина линии графика). */
|
||||
private static void readLineProps(CTShapeProperties sp, Series ser, DrawMlColor colors,
|
||||
List<Color> palette, int seriesIndex) {
|
||||
if (sp == null) {
|
||||
return;
|
||||
}
|
||||
if (sp.getLn() == null) {
|
||||
return;
|
||||
}
|
||||
if (sp.getLn().getNoFill() != null) {
|
||||
ser.lineNoFill = true;
|
||||
return;
|
||||
}
|
||||
if (sp.getLn().getSolidFill() != null) {
|
||||
ser.lineColor = colors.resolveFill(sp.getLn().getSolidFill());
|
||||
}
|
||||
if (sp.getLn().getW() != null) {
|
||||
ser.lineWidth = emuToPt(sp.getLn().getW());
|
||||
}
|
||||
}
|
||||
|
||||
private static void readLegend(CTChart chart, ChartSpec spec, DrawMlColor colors) {
|
||||
if (chart.getLegend() == null) {
|
||||
spec.legendPos = null;
|
||||
return;
|
||||
}
|
||||
var legend = chart.getLegend();
|
||||
if (isTrue(legend.getOverlay())) {
|
||||
// легенда поверх области построения — не резервируем место
|
||||
spec.legendPos = null;
|
||||
}
|
||||
if (legend.getLegendPos() != null && legend.getLegendPos().getVal() != null) {
|
||||
spec.legendPos = legend.getLegendPos().getVal().value();
|
||||
}
|
||||
spec.legendStyle = DrawMlText.defaultStyle(legend.getTxPr(), colors,
|
||||
colors.minorFontName(), 9, new Color(0x59, 0x59, 0x59));
|
||||
}
|
||||
|
||||
/**
|
||||
* Заголовок: явный текст (c:title/c:tx) или автозаголовок из имени
|
||||
* первого ряда (Word так и делает, когда c:autoTitleDeleted = 0).
|
||||
*/
|
||||
static void readTitle(CTChart chart, ChartSpec spec, DrawMlColor colors) {
|
||||
CTTitle t = chart.getTitle();
|
||||
if (t == null) {
|
||||
return;
|
||||
}
|
||||
String text = null;
|
||||
CTTx tx = t.getTx();
|
||||
if (tx != null) {
|
||||
if (tx.getStrRef() != null && tx.getStrRef().getStrCache() != null
|
||||
&& !tx.getStrRef().getStrCache().getPt().isEmpty()) {
|
||||
text = tx.getStrRef().getStrCache().getPt().get(0).getV();
|
||||
}
|
||||
if (text == null && tx.getRich() != null) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (DrawMlText.Paragraph p : DrawMlText.paragraphs(
|
||||
tx.getRich(), colors, colors.minorFontName(), 14, Color.DARK_GRAY)) {
|
||||
sb.append(p.text());
|
||||
}
|
||||
text = sb.toString();
|
||||
}
|
||||
}
|
||||
// Пустой c:title при autoTitleDeleted=0 — это автозаголовок Word:
|
||||
// для круговых диаграмм он берётся из имени ряда, для остальных
|
||||
// типов рисуется встроенный плейсхолдер (в эталоне — "Chart Title",
|
||||
// в XML его нет, Word подставляет строку из своего UI-языка).
|
||||
boolean deleted = chart.getAutoTitleDeleted() != null
|
||||
&& chart.getAutoTitleDeleted().isVal();
|
||||
if ((text == null || text.isBlank()) && !deleted) {
|
||||
boolean circular = spec.type == Type.PIE || spec.type == Type.PIE3D
|
||||
|| spec.type == Type.DOUGHNUT;
|
||||
if (circular && !spec.series.isEmpty()) {
|
||||
text = spec.series.get(0).name;
|
||||
} else {
|
||||
text = AUTO_TITLE;
|
||||
}
|
||||
}
|
||||
if (text == null || text.isBlank()) {
|
||||
return;
|
||||
}
|
||||
spec.title = text;
|
||||
spec.titleStyle = DrawMlText.defaultStyle(t.getTxPr(), colors,
|
||||
colors.minorFontName(), 14, new Color(0x59, 0x59, 0x59));
|
||||
}
|
||||
|
||||
private static AxisSpec readAxis(Object ax, DrawMlColor colors) {
|
||||
AxisSpec a = new AxisSpec();
|
||||
CTScaling scaling;
|
||||
CTBoolean deleted;
|
||||
CTAxPos pos;
|
||||
CTChartLines grid;
|
||||
CTTextBody txPr;
|
||||
CTShapeProperties spPr;
|
||||
String numFmt;
|
||||
if (ax instanceof CTCatAx c) {
|
||||
scaling = c.getScaling();
|
||||
deleted = c.getDelete();
|
||||
pos = c.getAxPos();
|
||||
grid = c.getMajorGridlines();
|
||||
txPr = c.getTxPr();
|
||||
spPr = c.getSpPr();
|
||||
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
||||
} else if (ax instanceof CTValAx c) {
|
||||
scaling = c.getScaling();
|
||||
deleted = c.getDelete();
|
||||
pos = c.getAxPos();
|
||||
grid = c.getMajorGridlines();
|
||||
txPr = c.getTxPr();
|
||||
spPr = c.getSpPr();
|
||||
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
||||
if (c.getMajorUnit() != null) {
|
||||
a.majorUnit = c.getMajorUnit().getVal();
|
||||
}
|
||||
} else if (ax instanceof CTSerAx c) {
|
||||
scaling = c.getScaling();
|
||||
deleted = c.getDelete();
|
||||
pos = c.getAxPos();
|
||||
grid = c.getMajorGridlines();
|
||||
txPr = c.getTxPr();
|
||||
spPr = c.getSpPr();
|
||||
numFmt = "General";
|
||||
} else if (ax instanceof CTDateAx c) {
|
||||
scaling = c.getScaling();
|
||||
deleted = c.getDelete();
|
||||
pos = c.getAxPos();
|
||||
grid = c.getMajorGridlines();
|
||||
txPr = c.getTxPr();
|
||||
spPr = c.getSpPr();
|
||||
numFmt = c.getNumFmt() != null ? c.getNumFmt().getFormatCode() : "General";
|
||||
} else {
|
||||
return a;
|
||||
}
|
||||
a.deleted = isTrue(deleted);
|
||||
a.pos = pos != null && pos.getVal() != null ? pos.getVal().value() : a.pos;
|
||||
a.numFmt = numFmt;
|
||||
if (scaling != null) {
|
||||
if (scaling.getMin() != null) {
|
||||
a.min = scaling.getMin().getVal();
|
||||
}
|
||||
if (scaling.getMax() != null) {
|
||||
a.max = scaling.getMax().getVal();
|
||||
}
|
||||
}
|
||||
a.gridlines = grid != null;
|
||||
if (grid != null && grid.getSpPr() != null && grid.getSpPr().getLn() != null
|
||||
&& grid.getSpPr().getLn().getSolidFill() != null) {
|
||||
Color g = colors.resolveFill(grid.getSpPr().getLn().getSolidFill());
|
||||
if (g != null) {
|
||||
a.gridColor = g;
|
||||
}
|
||||
}
|
||||
if (spPr != null && spPr.getLn() != null) {
|
||||
if (spPr.getLn().getNoFill() != null) {
|
||||
a.axisLineColor = null;
|
||||
} else if (spPr.getLn().getSolidFill() != null) {
|
||||
Color c = colors.resolveFill(spPr.getLn().getSolidFill());
|
||||
if (c != null) {
|
||||
a.axisLineColor = c;
|
||||
}
|
||||
}
|
||||
if (spPr.getLn().getW() != null) {
|
||||
a.axisLineWidth = emuToPt(spPr.getLn().getW());
|
||||
}
|
||||
}
|
||||
a.labelStyle = DrawMlText.defaultStyle(txPr, colors,
|
||||
colors.minorFontName(), 9, new Color(0x59, 0x59, 0x59));
|
||||
return a;
|
||||
}
|
||||
|
||||
private static String seriesName(CTSerTx tx) {
|
||||
if (tx == null) {
|
||||
return null;
|
||||
}
|
||||
if (tx.getV() != null) {
|
||||
return tx.getV();
|
||||
}
|
||||
if (tx.getStrRef() != null && tx.getStrRef().getStrCache() != null
|
||||
&& !tx.getStrRef().getStrCache().getPt().isEmpty()) {
|
||||
return tx.getStrRef().getStrCache().getPt().get(0).getV();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<String> categoryNames(CTAxDataSource cat) {
|
||||
List<String> out = new ArrayList<>();
|
||||
if (cat == null) {
|
||||
return out;
|
||||
}
|
||||
var str = cat.getStrRef() != null ? cat.getStrRef().getStrCache() : cat.getStrLit();
|
||||
if (str != null) {
|
||||
for (CTStrVal v : str.getPt()) {
|
||||
while (out.size() < v.getIdx()) {
|
||||
out.add("");
|
||||
}
|
||||
out.add(v.getV() == null ? "" : v.getV());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
var num = cat.getNumRef() != null ? cat.getNumRef().getNumCache() : cat.getNumLit();
|
||||
if (num != null) {
|
||||
for (CTNumVal v : num.getPt()) {
|
||||
while (out.size() < v.getIdx()) {
|
||||
out.add("");
|
||||
}
|
||||
out.add(v.getV() == null ? "" : v.getV());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Double parseDouble(String s) {
|
||||
if (s == null || s.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Double.parseDouble(s.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isTrue(CTBoolean b) {
|
||||
return b != null && b.isVal();
|
||||
}
|
||||
|
||||
/** EMU -> points (1 pt = 12700 EMU). */
|
||||
static double emuToPt(long emu) {
|
||||
return emu / 12700.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import jakarta.xml.bind.JAXBElement;
|
||||
import org.docx4j.dml.BaseStyles;
|
||||
import org.docx4j.dml.CTAngle;
|
||||
import org.docx4j.dml.CTColor;
|
||||
import org.docx4j.dml.CTColorScheme;
|
||||
import org.docx4j.dml.CTFixedPercentage;
|
||||
import org.docx4j.dml.CTHslColor;
|
||||
import org.docx4j.dml.CTPercentage;
|
||||
import org.docx4j.dml.CTPositiveFixedAngle;
|
||||
import org.docx4j.dml.CTPositiveFixedPercentage;
|
||||
import org.docx4j.dml.CTPositivePercentage;
|
||||
import org.docx4j.dml.CTScRgbColor;
|
||||
import org.docx4j.dml.CTSRgbColor;
|
||||
import org.docx4j.dml.CTSchemeColor;
|
||||
import org.docx4j.dml.CTSolidColorFillProperties;
|
||||
import org.docx4j.dml.CTSystemColor;
|
||||
import org.docx4j.dml.FontCollection;
|
||||
import org.docx4j.dml.STSchemeColorVal;
|
||||
import org.docx4j.dml.Theme;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Палитра цветов DrawingML: цвета схемы из word/theme/theme1.xml плюс
|
||||
* разбор {@code a:color} (srgbClr / schemeClr / sysClr / hslClr) с
|
||||
* трансформациями (lumMod, lumOff, tint, shade, satMod, hueOff, alpha...).
|
||||
*
|
||||
* Нужен и для графиков (c:solidFill / a:solidFill), и для SmartArt: оба
|
||||
* используют одни и те же ссылки на цвета темы (accent1..6, tx1, lt1).
|
||||
*/
|
||||
final class DrawMlColor {
|
||||
|
||||
/** Цвета темы по имени (lowercase): dk1/lt1/dk2/lt2/accent1..6/hlink/folHlink. */
|
||||
private final Map<String, Color> scheme = new HashMap<>();
|
||||
|
||||
/** Шрифты схемы ("+mn-lt"/"+mj-ma" в графиках разрешаются в них). */
|
||||
private final String minorFont;
|
||||
private final String majorFont;
|
||||
|
||||
/** Значение по умолчанию, когда у part'а нет темы. */
|
||||
private static final String[] OFFICE_DEFAULT = {
|
||||
"dk1", "000000", "lt1", "FFFFFF", "dk2", "44546A", "lt2", "E7E6E6",
|
||||
"accent1", "4472C4", "accent2", "ED7D31", "accent3", "A5A5A5",
|
||||
"accent4", "FFC000", "accent5", "5B9BD5", "accent6", "70AD47",
|
||||
"hlink", "0563C1", "folHlink", "954F72",
|
||||
};
|
||||
|
||||
DrawMlColor(Theme theme) {
|
||||
for (int i = 0; i < OFFICE_DEFAULT.length; i += 2) {
|
||||
scheme.put(OFFICE_DEFAULT[i], decodeHex(OFFICE_DEFAULT[i + 1]));
|
||||
}
|
||||
String minor = "Calibri";
|
||||
String major = "Calibri Light";
|
||||
if (theme != null && theme.getThemeElements() != null) {
|
||||
BaseStyles el = theme.getThemeElements();
|
||||
CTColorScheme cs = el.getClrScheme();
|
||||
if (cs != null) {
|
||||
put("dk1", cs.getDk1());
|
||||
put("lt1", cs.getLt1());
|
||||
put("dk2", cs.getDk2());
|
||||
put("lt2", cs.getLt2());
|
||||
put("accent1", cs.getAccent1());
|
||||
put("accent2", cs.getAccent2());
|
||||
put("accent3", cs.getAccent3());
|
||||
put("accent4", cs.getAccent4());
|
||||
put("accent5", cs.getAccent5());
|
||||
put("accent6", cs.getAccent6());
|
||||
put("hlink", cs.getHlink());
|
||||
put("folHlink", cs.getFolHlink());
|
||||
}
|
||||
BaseStyles.FontScheme fs = el.getFontScheme();
|
||||
if (fs != null) {
|
||||
minor = latinOf(fs.getMinorFont(), minor);
|
||||
major = latinOf(fs.getMajorFont(), major);
|
||||
}
|
||||
}
|
||||
this.minorFont = minor;
|
||||
this.majorFont = major;
|
||||
}
|
||||
|
||||
private void put(String name, CTColor c) {
|
||||
Color resolved = c == null ? null : baseOf(c);
|
||||
if (resolved != null) {
|
||||
scheme.put(name, resolved);
|
||||
}
|
||||
}
|
||||
|
||||
private static String latinOf(FontCollection fc, String def) {
|
||||
if (fc == null || fc.getLatin() == null || fc.getLatin().getTypeface() == null) {
|
||||
return def;
|
||||
}
|
||||
return fc.getLatin().getTypeface();
|
||||
}
|
||||
|
||||
String minorFontName() {
|
||||
return minorFont;
|
||||
}
|
||||
|
||||
String majorFontName() {
|
||||
return majorFont;
|
||||
}
|
||||
|
||||
/** Цвет схемы по имени (accent1, tx1, bg1...). Нет имени -> чёрный. */
|
||||
Color schemeColor(String name) {
|
||||
if (name == null) {
|
||||
return Color.BLACK;
|
||||
}
|
||||
String n = name.toLowerCase(Locale.ROOT);
|
||||
// Word: bg1/tx1 — псевдонимы lt1/dk1
|
||||
if (n.equals("bg1")) {
|
||||
n = "lt1";
|
||||
} else if (n.equals("tx1")) {
|
||||
n = "dk1";
|
||||
}
|
||||
Color c = scheme.get(n);
|
||||
return c != null ? c : Color.BLACK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Разбор {@code a:color}: базовый цвет + трансформации в порядке
|
||||
* следования. null -> null (вызывающий решает значение по умолчанию).
|
||||
*/
|
||||
Color resolve(CTColor c) {
|
||||
if (c == null) {
|
||||
return null;
|
||||
}
|
||||
Color base = baseOf(c);
|
||||
if (base == null) {
|
||||
return null;
|
||||
}
|
||||
java.util.List<JAXBElement<?>> transforms = transformsOf(c);
|
||||
if (transforms.isEmpty()) {
|
||||
return base;
|
||||
}
|
||||
double[] hsl = RgbHsl.toHsl(base);
|
||||
int alpha = 255;
|
||||
boolean hslDirty = false;
|
||||
Color rgb = base;
|
||||
for (JAXBElement<?> el : transforms) {
|
||||
String kind = el.getName().getLocalPart();
|
||||
int val = percentOf(el.getValue());
|
||||
if (val == Integer.MIN_VALUE) {
|
||||
continue;
|
||||
}
|
||||
double p = val / 100000.0;
|
||||
switch (kind) {
|
||||
case "lumMod" -> {
|
||||
hsl = RgbHsl.toHsl(toRgb(hsl));
|
||||
hsl[2] = clamp01(hsl[2] * p);
|
||||
hslDirty = true;
|
||||
}
|
||||
case "lumOff" -> {
|
||||
hsl = RgbHsl.toHsl(toRgb(hsl));
|
||||
hsl[2] = clamp01(hsl[2] + p);
|
||||
hslDirty = true;
|
||||
}
|
||||
case "satMod" -> {
|
||||
hsl = RgbHsl.toHsl(toRgb(hsl));
|
||||
hsl[1] = clamp01(hsl[1] * p);
|
||||
hslDirty = true;
|
||||
}
|
||||
case "satOff" -> {
|
||||
hsl = RgbHsl.toHsl(toRgb(hsl));
|
||||
hsl[1] = clamp01(hsl[1] + p);
|
||||
hslDirty = true;
|
||||
}
|
||||
case "hueMod" -> {
|
||||
hsl = RgbHsl.toHsl(toRgb(hsl));
|
||||
hsl[0] = (hsl[0] * p) % 360.0;
|
||||
hslDirty = true;
|
||||
}
|
||||
case "hueOff" -> {
|
||||
hsl = RgbHsl.toHsl(toRgb(hsl));
|
||||
hsl[0] = (hsl[0] + val / 60000.0) % 360.0;
|
||||
hslDirty = true;
|
||||
}
|
||||
case "tint" -> rgb = tint(rgb, p);
|
||||
case "shade" -> rgb = scaleRgb(rgb, p);
|
||||
case "alpha" -> alpha = clamp255((int) Math.round(alpha * p));
|
||||
case "alphaOff" -> alpha = clamp255((int) Math.round(clamp01((alpha / 255.0) + p) * 255));
|
||||
case "grayscl" -> {
|
||||
double lum = 0.299 * rgb.getRed() + 0.587 * rgb.getGreen() + 0.114 * rgb.getBlue();
|
||||
int l = clamp255((int) Math.round(lum));
|
||||
rgb = new Color(l, l, l);
|
||||
}
|
||||
default -> { /* прочие трансформации не поддерживаются */ }
|
||||
}
|
||||
}
|
||||
if (hslDirty) {
|
||||
rgb = toRgb(hsl);
|
||||
}
|
||||
return alpha == 255 ? rgb
|
||||
: new Color(rgb.getRed(), rgb.getGreen(), rgb.getBlue(), clamp255(alpha));
|
||||
}
|
||||
|
||||
/**
|
||||
* Разбор {@code a:solidFill} (a:ln/a:spPr): обёртка над тем же
|
||||
* набором цветов, что и {@code a:color}.
|
||||
*/
|
||||
Color resolveFill(CTSolidColorFillProperties fill) {
|
||||
if (fill == null) {
|
||||
return null;
|
||||
}
|
||||
CTColor c = new CTColor();
|
||||
c.setScrgbClr(fill.getScrgbClr());
|
||||
c.setSrgbClr(fill.getSrgbClr());
|
||||
c.setHslClr(fill.getHslClr());
|
||||
c.setSysClr(fill.getSysClr());
|
||||
c.setSchemeClr(fill.getSchemeClr());
|
||||
c.setPrstClr(fill.getPrstClr());
|
||||
return resolve(c);
|
||||
}
|
||||
|
||||
/** Цвет стоп-точки градиента (a:gs) — тот же набор, что и у solidFill. */
|
||||
Color resolveStop(org.docx4j.dml.CTGradientStop gs) {
|
||||
if (gs == null) {
|
||||
return null;
|
||||
}
|
||||
CTColor c = new CTColor();
|
||||
c.setScrgbClr(gs.getScrgbClr());
|
||||
c.setSrgbClr(gs.getSrgbClr());
|
||||
c.setHslClr(gs.getHslClr());
|
||||
c.setSysClr(gs.getSysClr());
|
||||
c.setSchemeClr(gs.getSchemeClr());
|
||||
c.setPrstClr(gs.getPrstClr());
|
||||
return resolve(c);
|
||||
}
|
||||
|
||||
/** Цвет из a:fontRef (стилевая матрица SmartArt) — тот же набор детей. */
|
||||
Color resolveFontRef(org.docx4j.dml.CTFontReference ref) {
|
||||
if (ref == null) {
|
||||
return null;
|
||||
}
|
||||
CTColor c = new CTColor();
|
||||
c.setScrgbClr(ref.getScrgbClr());
|
||||
c.setSrgbClr(ref.getSrgbClr());
|
||||
c.setHslClr(ref.getHslClr());
|
||||
c.setSysClr(ref.getSysClr());
|
||||
c.setSchemeClr(ref.getSchemeClr());
|
||||
c.setPrstClr(ref.getPrstClr());
|
||||
return resolve(c);
|
||||
}
|
||||
|
||||
/** Базовый цвет без трансформаций. */
|
||||
private Color baseOf(CTColor c) {
|
||||
if (c.getSrgbClr() != null) {
|
||||
CTSRgbColor s = c.getSrgbClr();
|
||||
return s.getVal() == null ? null : decodeHex(s.getVal());
|
||||
}
|
||||
if (c.getSchemeClr() != null) {
|
||||
CTSchemeColor sc = c.getSchemeClr();
|
||||
STSchemeColorVal v = sc.getVal();
|
||||
return v == null ? null : schemeColor(v.value());
|
||||
}
|
||||
if (c.getScrgbClr() != null) {
|
||||
CTScRgbColor s = c.getScrgbClr();
|
||||
return new Color(
|
||||
clamp255((int) Math.round(s.getR() * 255)),
|
||||
clamp255((int) Math.round(s.getG() * 255)),
|
||||
clamp255((int) Math.round(s.getB() * 255)));
|
||||
}
|
||||
if (c.getHslClr() != null) {
|
||||
CTHslColor h = c.getHslClr();
|
||||
return RgbHsl.fromHsl(h.getHue() / 60000.0, h.getSat() / 100000.0, h.getLum() / 100000.0);
|
||||
}
|
||||
if (c.getSysClr() != null) {
|
||||
CTSystemColor s = c.getSysClr();
|
||||
return "window".equalsIgnoreCase(s.getVal()) ? Color.WHITE : Color.BLACK;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static java.util.List<JAXBElement<?>> transformsOf(CTColor c) {
|
||||
if (c.getSrgbClr() != null) {
|
||||
return c.getSrgbClr().getEGColorTransform();
|
||||
}
|
||||
if (c.getSchemeClr() != null) {
|
||||
return c.getSchemeClr().getEGColorTransform();
|
||||
}
|
||||
if (c.getSysClr() != null) {
|
||||
return c.getSysClr().getEGColorTransform();
|
||||
}
|
||||
return java.util.List.of();
|
||||
}
|
||||
|
||||
/** Все классы процентных/угловых трансформаций имеют getVal() в стотысячных. */
|
||||
private static int percentOf(Object o) {
|
||||
if (o instanceof CTPercentage v) {
|
||||
return v.getVal();
|
||||
}
|
||||
if (o instanceof CTPositivePercentage v) {
|
||||
return v.getVal();
|
||||
}
|
||||
if (o instanceof CTFixedPercentage v) {
|
||||
return v.getVal();
|
||||
}
|
||||
if (o instanceof CTPositiveFixedPercentage v) {
|
||||
return v.getVal();
|
||||
}
|
||||
if (o instanceof CTAngle v) {
|
||||
return v.getVal();
|
||||
}
|
||||
if (o instanceof CTPositiveFixedAngle v) {
|
||||
return v.getVal();
|
||||
}
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
|
||||
/** Осветление: c*p + white*(1-p) (a:tint в DrawingML). */
|
||||
static Color tint(Color c, double p) {
|
||||
return new Color(
|
||||
clamp255((int) Math.round(c.getRed() * p + 255 * (1 - p))),
|
||||
clamp255((int) Math.round(c.getGreen() * p + 255 * (1 - p))),
|
||||
clamp255((int) Math.round(c.getBlue() * p + 255 * (1 - p))));
|
||||
}
|
||||
|
||||
/** Затемнение: c*p (a:shade). */
|
||||
static Color scaleRgb(Color c, double p) {
|
||||
return new Color(clamp255((int) Math.round(c.getRed() * p)),
|
||||
clamp255((int) Math.round(c.getGreen() * p)),
|
||||
clamp255((int) Math.round(c.getBlue() * p)));
|
||||
}
|
||||
|
||||
/** Затемнение на фиксированную долю (для боковых граней 3D). */
|
||||
static Color darken(Color c, double amount) {
|
||||
return scaleRgb(c, 1.0 - amount);
|
||||
}
|
||||
|
||||
static Color withAlpha(Color c, double alpha) {
|
||||
return new Color(c.getRed(), c.getGreen(), c.getBlue(),
|
||||
(int) Math.round(clamp01(alpha) * 255));
|
||||
}
|
||||
|
||||
private static Color toRgb(double[] hsl) {
|
||||
return RgbHsl.fromHsl(hsl[0], hsl[1], hsl[2]);
|
||||
}
|
||||
|
||||
private static int clamp255(int v) {
|
||||
return Math.max(0, Math.min(255, v));
|
||||
}
|
||||
|
||||
private static double clamp01(double v) {
|
||||
return Math.max(0.0, Math.min(1.0, v));
|
||||
}
|
||||
|
||||
static Color decodeHex(String hex) {
|
||||
long v = Long.parseLong(hex, 16);
|
||||
return new Color((int) ((v >> 16) & 0xFF), (int) ((v >> 8) & 0xFF), (int) (v & 0xFF));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import org.docx4j.dml.CTRegularTextRun;
|
||||
import org.docx4j.dml.CTTextBody;
|
||||
import org.docx4j.dml.CTTextCharacterProperties;
|
||||
import org.docx4j.dml.CTTextParagraph;
|
||||
import org.docx4j.dml.CTTextParagraphProperties;
|
||||
import org.docx4j.dml.TextFont;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.Font;
|
||||
import java.awt.font.FontRenderContext;
|
||||
import java.awt.font.TextLayout;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Текст DrawingML (a:txPr / a:txBody) для Java2D: разбор начертания
|
||||
* (a:defRPr / a:rPr: sz, b, i, solidFill, latin) и разбивка на строки.
|
||||
*
|
||||
* Шрифты берутся из того же бандла, что и у текста PDF
|
||||
* ({@link BundledFontMapper#bundledFamily}), поэтому подпись диаграммы
|
||||
* рисуется тем же Carlito/Tinos, что и абзацы документа.
|
||||
*/
|
||||
final class DrawMlText {
|
||||
|
||||
/** Начертание одного запуска текста. */
|
||||
record Style(double sizePt, boolean bold, boolean italic, Color color, String family) {
|
||||
|
||||
Style derive(Double size, Boolean bold, Boolean italic, Color clr, String fam) {
|
||||
return new Style(
|
||||
size != null ? size : sizePt,
|
||||
bold != null ? bold : this.bold,
|
||||
italic != null ? italic : this.italic,
|
||||
clr != null ? clr : this.color,
|
||||
fam != null ? fam : this.family);
|
||||
}
|
||||
}
|
||||
|
||||
/** Один абзац: текст + начертание + выравнивание. */
|
||||
record Paragraph(String text, Style style, String align) {
|
||||
}
|
||||
|
||||
private DrawMlText() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Стиль по умолчанию из {@code a:txPr} (первый {@code a:pPr/a:defRPr}).
|
||||
*
|
||||
* @param txPr тело текста (может быть null)
|
||||
* @param colors палитра темы (для schemeClr в solidFill)
|
||||
* @param fallbackFam семейство, если latin не указан/неизвестен
|
||||
* @param fallbackSize размер в pt, если sz нет
|
||||
*/
|
||||
static Style defaultStyle(CTTextBody txPr, DrawMlColor colors,
|
||||
String fallbackFam, double fallbackSize, Color fallbackColor) {
|
||||
Style base = new Style(fallbackSize, false, false, fallbackColor, fallbackFam);
|
||||
if (txPr == null || txPr.getP().isEmpty()) {
|
||||
return base;
|
||||
}
|
||||
CTTextParagraphProperties pPr = txPr.getP().get(0).getPPr();
|
||||
if (pPr == null) {
|
||||
return base;
|
||||
}
|
||||
return applyTo(pPr.getDefRPr(), base, colors, fallbackFam);
|
||||
}
|
||||
|
||||
/** Начертания абзацев тела текста (a:p -> a:r/a:t) с учётом defRPr. */
|
||||
static List<Paragraph> paragraphs(CTTextBody body, DrawMlColor colors,
|
||||
String fallbackFam, double fallbackSize,
|
||||
Color fallbackColor) {
|
||||
List<Paragraph> out = new ArrayList<>();
|
||||
if (body == null) {
|
||||
return out;
|
||||
}
|
||||
Style def = defaultStyle(body, colors, fallbackFam, fallbackSize, fallbackColor);
|
||||
for (CTTextParagraph p : body.getP()) {
|
||||
Style paraStyle = def;
|
||||
if (p.getPPr() != null) {
|
||||
paraStyle = applyTo(p.getPPr().getDefRPr(), paraStyle, colors, fallbackFam);
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Style runStyle = paraStyle;
|
||||
for (Object run : p.getEGTextRun()) {
|
||||
if (run instanceof CTRegularTextRun r) {
|
||||
if (r.getRPr() != null) {
|
||||
runStyle = applyTo(r.getRPr(), paraStyle, colors, fallbackFam);
|
||||
}
|
||||
if (r.getT() != null) {
|
||||
sb.append(r.getT());
|
||||
}
|
||||
}
|
||||
}
|
||||
String align = p.getPPr() != null && p.getPPr().getAlgn() != null
|
||||
? p.getPPr().getAlgn().value() : null;
|
||||
String text = sb.toString();
|
||||
if (!text.isBlank()) {
|
||||
out.add(new Paragraph(text, runStyle, align));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Применяет a:defRPr / a:rPr к наследуемому стилю. */
|
||||
private static Style applyTo(CTTextCharacterProperties rPr, Style inherit,
|
||||
DrawMlColor colors, String fallbackFam) {
|
||||
if (rPr == null) {
|
||||
return inherit;
|
||||
}
|
||||
Double size = rPr.getSz() != null ? rPr.getSz() / 100.0 : null;
|
||||
Boolean bold = rPr.isB();
|
||||
Boolean italic = rPr.isI();
|
||||
Color color = null;
|
||||
if (rPr.getNoFill() != null) {
|
||||
color = new Color(0, 0, 0, 0);
|
||||
} else if (rPr.getSolidFill() != null) {
|
||||
color = colors.resolveFill(rPr.getSolidFill());
|
||||
}
|
||||
String family = null;
|
||||
TextFont latin = rPr.getLatin();
|
||||
if (latin != null && latin.getTypeface() != null) {
|
||||
family = resolveFamily(latin.getTypeface(), colors, fallbackFam);
|
||||
}
|
||||
return inherit.derive(size, bold, italic, color, family);
|
||||
}
|
||||
|
||||
/** "+mn-lt"/"+mj-mt" -> шрифт темы; иначе имя как есть (через алиасы бандла). */
|
||||
private static String resolveFamily(String typeface, DrawMlColor colors, String fallbackFam) {
|
||||
String name = switch (typeface) {
|
||||
case "+mn-lt", "+mn-ea", "+mn-cs" -> colors.minorFontName();
|
||||
case "+mj-lt", "+mj-ea", "+mj-cs" -> colors.majorFontName();
|
||||
default -> typeface;
|
||||
};
|
||||
return BundledFontMapper.bundledFamily(name != null ? name : fallbackFam);
|
||||
}
|
||||
|
||||
/** java.awt.Font для стиля; null -> логический SansSerif. */
|
||||
static Font fontFor(Style style) {
|
||||
String variant = style.bold() && style.italic() ? BundledFonts.V_BOLD_ITALIC
|
||||
: style.bold() ? BundledFonts.V_BOLD
|
||||
: style.italic() ? BundledFonts.V_ITALIC
|
||||
: BundledFonts.V_REGULAR;
|
||||
Font base = BundledFonts.awtFont(style.family(), variant);
|
||||
int flags = (style.bold() ? Font.BOLD : 0) | (style.italic() ? Font.ITALIC : 0);
|
||||
if (base == null) {
|
||||
return new Font(Font.SANS_SERIF, flags, 1).deriveFont((float) style.sizePt());
|
||||
}
|
||||
return base.deriveFont((float) style.sizePt());
|
||||
}
|
||||
|
||||
/**
|
||||
* Рисует абзацы внутри прямоугольника: выравнивание по горизонтали
|
||||
* (align абзаца или {@code defAlign}) и по вертикали ({@code vAlign}:
|
||||
* t/ctr/b).
|
||||
*/
|
||||
static void paint(Graphics2D g, List<Paragraph> paragraphs, Rectangle2D box,
|
||||
String defAlign, String vAlign, double lineHeightFactor) {
|
||||
if (paragraphs.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
FontRenderContext frc = g.getFontRenderContext();
|
||||
record Line(String text, Style style, String align, double width, double height,
|
||||
double ascent) {
|
||||
}
|
||||
List<Line> lines = new ArrayList<>();
|
||||
double totalHeight = 0;
|
||||
for (Paragraph p : paragraphs) {
|
||||
Font f = fontFor(p.style());
|
||||
TextLayout metrics = new TextLayout("Xg", f, frc);
|
||||
double lineH = (metrics.getAscent() + metrics.getDescent()
|
||||
+ metrics.getLeading()) * lineHeightFactor;
|
||||
for (String line : wrapLines(p.text(), f, frc, box.getWidth())) {
|
||||
double w = new TextLayout(line, f, frc).getAdvance();
|
||||
lines.add(new Line(line, p.style(), p.align(), w, lineH,
|
||||
metrics.getAscent() * lineHeightFactor));
|
||||
totalHeight += lineH;
|
||||
}
|
||||
}
|
||||
double y = box.getY();
|
||||
if ("ctr".equals(vAlign)) {
|
||||
y += (box.getHeight() - totalHeight) / 2.0;
|
||||
} else if ("b".equals(vAlign)) {
|
||||
y += box.getHeight() - totalHeight;
|
||||
}
|
||||
y = Math.max(box.getY(), y);
|
||||
for (Line line : lines) {
|
||||
g.setFont(fontFor(line.style()));
|
||||
g.setColor(line.style().color());
|
||||
double x = box.getX();
|
||||
String align = line.align() != null ? line.align() : defAlign;
|
||||
if ("ctr".equals(align)) {
|
||||
x += (box.getWidth() - line.width()) / 2.0;
|
||||
} else if ("r".equals(align) || "far".equals(align)) {
|
||||
x += box.getWidth() - line.width();
|
||||
}
|
||||
g.drawString(line.text(), (float) x, (float) (y + line.ascent()));
|
||||
y += line.height();
|
||||
}
|
||||
}
|
||||
|
||||
/** Жадный перенос по пробелам; длинные слова режутся по символам. */
|
||||
private static List<String> wrapLines(String text, Font f, FontRenderContext frc,
|
||||
double maxWidth) {
|
||||
List<String> out = new ArrayList<>();
|
||||
double limit = Math.max(1, maxWidth);
|
||||
for (String hard : text.split("\\n")) {
|
||||
if (hard.isEmpty()) {
|
||||
out.add("");
|
||||
continue;
|
||||
}
|
||||
StringBuilder cur = new StringBuilder();
|
||||
double curWidth = 0;
|
||||
for (String word : hard.split(" ")) {
|
||||
if (word.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String candidate = cur.length() == 0 ? word : cur + " " + word;
|
||||
double w = new TextLayout(candidate, f, frc).getAdvance();
|
||||
if (w <= limit || cur.length() == 0) {
|
||||
cur.setLength(0);
|
||||
cur.append(candidate);
|
||||
curWidth = w;
|
||||
continue;
|
||||
}
|
||||
out.add(cur.toString());
|
||||
cur.setLength(0);
|
||||
cur.append(word);
|
||||
curWidth = new TextLayout(word, f, frc).getAdvance();
|
||||
while (curWidth > limit && cur.length() > 1) {
|
||||
int cut = cur.length() - 1;
|
||||
while (cut > 1 && new TextLayout(cur.substring(0, cut), f, frc)
|
||||
.getAdvance() > limit) {
|
||||
cut--;
|
||||
}
|
||||
out.add(cur.substring(0, cut));
|
||||
cur.delete(0, cut);
|
||||
curWidth = new TextLayout(cur.toString(), f, frc).getAdvance();
|
||||
}
|
||||
}
|
||||
if (cur.length() > 0) {
|
||||
out.add(cur.toString());
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Ширина строки в тех же единицах, что и размер шрифта. */
|
||||
static double textWidth(String text, Style style, FontRenderContext frc) {
|
||||
return new java.awt.font.TextLayout(text, fontFor(style), frc).getAdvance();
|
||||
}
|
||||
|
||||
/** Высота строки (ascent+descent+leading) для стиля. */
|
||||
static double textHeight(Style style, FontRenderContext frc) {
|
||||
Font f = fontFor(style);
|
||||
java.awt.font.TextLayout tl = new java.awt.font.TextLayout("Xpg", f, frc);
|
||||
return tl.getAscent() + tl.getDescent() + tl.getLeading();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import jakarta.xml.bind.JAXBElement;
|
||||
import org.docx4j.dml.CTBlip;
|
||||
import org.docx4j.dml.CTBlipFillProperties;
|
||||
import org.docx4j.dml.CTGeomGuideList;
|
||||
import org.docx4j.dml.CTNonVisualDrawingProps;
|
||||
import org.docx4j.dml.CTNonVisualPictureProperties;
|
||||
import org.docx4j.dml.CTPoint2D;
|
||||
import org.docx4j.dml.CTPositiveSize2D;
|
||||
import org.docx4j.dml.CTPresetGeometry2D;
|
||||
import org.docx4j.dml.CTRelativeRect;
|
||||
import org.docx4j.dml.CTShapeProperties;
|
||||
import org.docx4j.dml.CTStretchInfoProperties;
|
||||
import org.docx4j.dml.CTTransform2D;
|
||||
import org.docx4j.dml.Graphic;
|
||||
import org.docx4j.dml.GraphicData;
|
||||
import org.docx4j.dml.STShapeType;
|
||||
import org.docx4j.dml.chart.CTChartSpace;
|
||||
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.picture.Pic;
|
||||
import org.docx4j.dml.wordprocessingDrawing.Anchor;
|
||||
import org.docx4j.dml.wordprocessingDrawing.Inline;
|
||||
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
||||
import org.docx4j.openpackaging.parts.JaxbXmlPart;
|
||||
import org.docx4j.openpackaging.parts.Part;
|
||||
import org.docx4j.openpackaging.parts.ThemePart;
|
||||
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
|
||||
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
|
||||
import org.docx4j.wml.Drawing;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Выключатель «диаграммы не умеют в FO»: до экспорта в XSL-FO каждая
|
||||
* DrawingML-диаграмма (c:chart) и SmartArt-схема (dgm:relIds) рендерится
|
||||
* в PNG и подменяется обычной картинкой pic:pic — единственный вид
|
||||
* a:graphic, который docx2fo.xslt действительно умеет выкладывать.
|
||||
*
|
||||
* Порядок вызова важен: {@link #run} должен отработать после загрузки
|
||||
* пакета и до создания FOSettings, иначе FOP увидит исходные chart/diagram
|
||||
* и молча их выбросит (notImplemented в шаблоне).
|
||||
*/
|
||||
public final class DrawingPreRenderer {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DrawingPreRenderer.class);
|
||||
|
||||
private static final String CHART_ELEMENT =
|
||||
"{http://schemas.openxmlformats.org/drawingml/2006/chart}chart";
|
||||
private static final String DIAGRAM_ELEMENT =
|
||||
"{http://schemas.openxmlformats.org/drawingml/2006/diagram}relIds";
|
||||
private static final String PICTURE_URI =
|
||||
"http://schemas.openxmlformats.org/drawingml/2006/picture";
|
||||
private static final String DIAGRAM_DRAWING_REL =
|
||||
"http://schemas.microsoft.com/office/2007/relationships/diagramDrawing";
|
||||
|
||||
private DrawingPreRenderer() {
|
||||
}
|
||||
|
||||
/** Рендерит все диаграммы пакета в PNG и подменяет их картинками. */
|
||||
public static void run(WordprocessingMLPackage pkg) {
|
||||
ThemePart themePart = null;
|
||||
for (Part p : new ArrayList<>(pkg.getParts().getParts().values())) {
|
||||
if (p instanceof ThemePart tp) {
|
||||
themePart = tp;
|
||||
break;
|
||||
}
|
||||
}
|
||||
DrawMlColor colors = new DrawMlColor(themePart == null ? null : themePart.getJaxbElement());
|
||||
|
||||
// Снимок: createImagePart докидывает части в тот же реестр,
|
||||
// обход живого HashMap дал бы ConcurrentModificationException.
|
||||
List<Part> parts = new ArrayList<>(pkg.getParts().getParts().values());
|
||||
Set<Part> handled = new HashSet<>();
|
||||
int[] idSeq = {1000};
|
||||
for (Part p : parts) {
|
||||
if (!handled.add(p)) {
|
||||
continue;
|
||||
}
|
||||
List<Object> content = contentOf(p);
|
||||
if (content == null || content.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
walk(p, content, pkg, colors, idSeq);
|
||||
}
|
||||
}
|
||||
|
||||
/** Содержимое части, в котором могут лежать w:drawing. */
|
||||
private static List<Object> contentOf(Part part) {
|
||||
if (!(part instanceof JaxbXmlPart<?> jaxb)) {
|
||||
return null;
|
||||
}
|
||||
Object root = jaxb.getJaxbElement();
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
if (root instanceof org.docx4j.wml.Document doc) {
|
||||
return doc.getBody() == null ? doc.getContent() : doc.getBody().getContent();
|
||||
}
|
||||
if (root instanceof org.docx4j.wml.CTFootnotes fn) {
|
||||
return cast(fn.getFootnote());
|
||||
}
|
||||
if (root instanceof org.docx4j.wml.CTEndnotes en) {
|
||||
return cast(en.getEndnote());
|
||||
}
|
||||
return invokeList(root, "getContent");
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void walk(Part part, List<Object> content, WordprocessingMLPackage pkg,
|
||||
DrawMlColor colors, int[] idSeq) {
|
||||
for (Object o : content) {
|
||||
Object v = o instanceof JAXBElement ? ((JAXBElement<?>) o).getValue() : o;
|
||||
if (v instanceof Drawing drawing) {
|
||||
replaceDrawing(part, drawing, pkg, colors, idSeq);
|
||||
continue;
|
||||
}
|
||||
List<Object> nested = invokeList(v, "getContent");
|
||||
if (nested != null && !nested.isEmpty() && nested != content) {
|
||||
walk(part, nested, pkg, colors, idSeq);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Object> cast(List<?> l) {
|
||||
return (List<Object>) l;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Object> invokeList(Object target, String getter) {
|
||||
try {
|
||||
Method m = target.getClass().getMethod(getter);
|
||||
Object r = m.invoke(target);
|
||||
return r instanceof List ? (List<Object>) r : null;
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void replaceDrawing(Part part, Drawing drawing, WordprocessingMLPackage pkg,
|
||||
DrawMlColor colors, int[] idSeq) {
|
||||
for (Object wrapper : drawing.getAnchorOrInline()) {
|
||||
Graphic graphic;
|
||||
long cx;
|
||||
long cy;
|
||||
if (wrapper instanceof Inline inline) {
|
||||
graphic = inline.getGraphic();
|
||||
cx = inline.getExtent() == null ? 0 : inline.getExtent().getCx();
|
||||
cy = inline.getExtent() == null ? 0 : inline.getExtent().getCy();
|
||||
} else if (wrapper instanceof Anchor anchor) {
|
||||
graphic = anchor.getGraphic();
|
||||
cx = anchor.getExtent() == null ? 0 : anchor.getExtent().getCx();
|
||||
cy = anchor.getExtent() == null ? 0 : anchor.getExtent().getCy();
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (graphic == null || graphic.getGraphicData() == null) {
|
||||
continue;
|
||||
}
|
||||
if (cx <= 0 || cy <= 0) {
|
||||
log.warn("drawing без wp:extent — оставлен как есть");
|
||||
continue;
|
||||
}
|
||||
GraphicData gd = graphic.getGraphicData();
|
||||
String uri = gd.getUri();
|
||||
BufferedImage img = null;
|
||||
String label = null;
|
||||
if (PICTURE_URI.equals(uri)) {
|
||||
continue; // уже картинка
|
||||
}
|
||||
if (gd.getAny().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Object payload = gd.getAny().get(0);
|
||||
if (payload instanceof JAXBElement<?> el) {
|
||||
String name = el.getName() == null ? "" : el.getName().toString();
|
||||
if (CHART_ELEMENT.equals(name)) {
|
||||
img = renderChart(part, (CTRelId) el.getValue(), pkg, colors, cx, cy);
|
||||
label = "график";
|
||||
} else if (DIAGRAM_ELEMENT.equals(name)) {
|
||||
img = renderDiagram(part, (CTRelIds) el.getValue(), pkg, colors, cx, cy);
|
||||
label = "SmartArt";
|
||||
}
|
||||
}
|
||||
if (img == null) {
|
||||
if (label != null) {
|
||||
log.warn("не удалось отрендерить {} — объект удалён из документа", label);
|
||||
gd.getAny().clear();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
swapForPicture(part, gd, img, cx, cy, idSeq, pkg);
|
||||
}
|
||||
}
|
||||
|
||||
private static BufferedImage renderChart(Part part, CTRelId ref, WordprocessingMLPackage pkg,
|
||||
DrawMlColor colors, long cx, long cy) {
|
||||
Part target = resolve(part, ref.getId());
|
||||
if (!(target instanceof JaxbXmlPart<?> jp) || !(jp.getJaxbElement() instanceof CTChartSpace space)) {
|
||||
log.warn("chart-часть не найдена по r:id={}", ref.getId());
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
ChartSpec spec = ChartSpec.parse(space, colors);
|
||||
return ChartRenderer.render(spec, cx / 12700.0, cy / 12700.0, colors);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("рендер графика r:id={} упал: {}", ref.getId(), e.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static BufferedImage renderDiagram(Part part, CTRelIds refs, WordprocessingMLPackage pkg,
|
||||
DrawMlColor colors, long cx, long cy) {
|
||||
Part drawingPart = diagramDrawingPart(part);
|
||||
if (!(drawingPart instanceof JaxbXmlPart<?> jp)
|
||||
|| !(jp.getJaxbElement() instanceof CTDrawing drawing)) {
|
||||
log.warn("dsp:drawing (SmartArt) не найден — схема пропущена");
|
||||
return null;
|
||||
}
|
||||
CTDataModel data = null;
|
||||
if (refs.getDm() != null && resolve(part, refs.getDm()) instanceof JaxbXmlPart<?> dp
|
||||
&& dp.getJaxbElement() instanceof CTDataModel dm) {
|
||||
data = dm;
|
||||
}
|
||||
try {
|
||||
return SmartArtRenderer.render(drawing, data, colors, cx / 12700.0, cy / 12700.0);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("рендер SmartArt упал: {}", e.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* part.getOwningRelationshipPart() — это rels того, кто ссылается на
|
||||
* часть (для document.xml это пакетный .rels). Нужны собственные rels
|
||||
* части, они в Base.getRelationshipsPart().
|
||||
*/
|
||||
private static RelationshipsPart relsOf(Part part) {
|
||||
return part.getRelationshipsPart();
|
||||
}
|
||||
|
||||
private static Part diagramDrawingPart(Part dataPart) {
|
||||
RelationshipsPart rels = relsOf(dataPart);
|
||||
if (rels == null || rels.getRelationships() == null) {
|
||||
return null;
|
||||
}
|
||||
var rel = rels.getRelationshipByType(DIAGRAM_DRAWING_REL);
|
||||
return rel == null ? null : rels.getPart(rel);
|
||||
}
|
||||
|
||||
private static Part resolve(Part part, String relId) {
|
||||
RelationshipsPart rels = relsOf(part);
|
||||
if (rels == null || relId == null || rels.getRelationships() == null) {
|
||||
return null;
|
||||
}
|
||||
var rel = rels.getRelationshipByID(relId);
|
||||
return rel == null ? null : rels.getPart(rel);
|
||||
}
|
||||
|
||||
/** a:graphic -> pic:pic того же размера; PNG кладётся в ImagePart этой же части. */
|
||||
private static void swapForPicture(Part part, GraphicData gd, BufferedImage img,
|
||||
long cx, long cy, int[] idSeq,
|
||||
WordprocessingMLPackage pkg) {
|
||||
byte[] png;
|
||||
try {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ImageIO.write(img, "png", bos);
|
||||
png = bos.toByteArray();
|
||||
} catch (Exception e) {
|
||||
log.warn("PNG не собран: {}", e.toString());
|
||||
return;
|
||||
}
|
||||
BinaryPartAbstractImage imagePart;
|
||||
try {
|
||||
imagePart = BinaryPartAbstractImage.createImagePart(pkg, part, png);
|
||||
} catch (Exception e) {
|
||||
log.warn("ImagePart не создан: {}", e.toString());
|
||||
return;
|
||||
}
|
||||
String relId = relIdFor(part, imagePart);
|
||||
if (relId == null) {
|
||||
log.warn("r:id для ImagePart {} не найден", imagePart.getPartName());
|
||||
return;
|
||||
}
|
||||
|
||||
Pic pic = new Pic();
|
||||
org.docx4j.dml.picture.CTPictureNonVisual nv = new org.docx4j.dml.picture.CTPictureNonVisual();
|
||||
CTNonVisualDrawingProps props = new CTNonVisualDrawingProps();
|
||||
props.setId(idSeq[0]++);
|
||||
props.setName("Диаграмма " + props.getId());
|
||||
nv.setCNvPr(props);
|
||||
nv.setCNvPicPr(new CTNonVisualPictureProperties());
|
||||
pic.setNvPicPr(nv);
|
||||
|
||||
CTBlipFillProperties blipFill = new CTBlipFillProperties();
|
||||
CTBlip blip = new CTBlip();
|
||||
blip.setEmbed(relId);
|
||||
blipFill.setBlip(blip);
|
||||
CTStretchInfoProperties stretch = new CTStretchInfoProperties();
|
||||
stretch.setFillRect(new CTRelativeRect());
|
||||
blipFill.setStretch(stretch);
|
||||
pic.setBlipFill(blipFill);
|
||||
|
||||
CTShapeProperties spPr = new CTShapeProperties();
|
||||
CTTransform2D xfrm = new CTTransform2D();
|
||||
CTPoint2D off = new CTPoint2D();
|
||||
off.setX(0);
|
||||
off.setY(0);
|
||||
CTPositiveSize2D ext = new CTPositiveSize2D();
|
||||
ext.setCx(cx);
|
||||
ext.setCy(cy);
|
||||
xfrm.setOff(off);
|
||||
xfrm.setExt(ext);
|
||||
spPr.setXfrm(xfrm);
|
||||
CTPresetGeometry2D geom = new CTPresetGeometry2D();
|
||||
geom.setPrst(STShapeType.RECT);
|
||||
geom.setAvLst(new CTGeomGuideList());
|
||||
spPr.setPrstGeom(geom);
|
||||
pic.setSpPr(spPr);
|
||||
|
||||
gd.setUri(PICTURE_URI);
|
||||
gd.getAny().clear();
|
||||
gd.getAny().add(pic);
|
||||
}
|
||||
|
||||
private static String relIdFor(Part part, Part target) {
|
||||
RelationshipsPart rels = relsOf(part);
|
||||
if (rels == null || rels.getRelationships() == null) {
|
||||
return null;
|
||||
}
|
||||
var rel = rels.getRel(target.getPartName());
|
||||
return rel == null ? null : rel.getId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.Arc2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Point2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Секторная диаграмма: 2D (pie/doughnut) и 3D (pie3D) одним кодом —
|
||||
* у 2D-варианта глубина экструзии равна нулю.
|
||||
*
|
||||
* 3D в Word — это круг, наклонённый на c:view3D/rotX вокруг горизонтальной
|
||||
* оси, с экструзией вниз. Рисуется художником алгоритма: сектора от задних
|
||||
* к передним, у каждого сначала боковая стенка и торцы, затем верхняя
|
||||
* грань.
|
||||
*/
|
||||
final class PiePainter {
|
||||
|
||||
/** Доля радиуса, уходящая в глубину при depthPercent=100. */
|
||||
private static final double DEPTH_RATIO = 0.22;
|
||||
|
||||
/**
|
||||
* Word рисует pie3D чуть более «пологим» и с запасом вокруг торта:
|
||||
* замер по word-export.pdf (300 dpi, область 219,2×149,1 pt) — силуэт 540×316 px,
|
||||
* ry/rx = 0,475 при rotX=30° (sin 30° = 0,5) и радиус 270 px из
|
||||
* вписанного 288 px. Без этих поправок торт на 8% выше эталона.
|
||||
*/
|
||||
private static final double TILT_CORRECTION = 0.95;
|
||||
private static final double FIT_MARGIN = 0.865;
|
||||
|
||||
private PiePainter() {
|
||||
}
|
||||
|
||||
private record Slice(double startDeg, double sweepDeg, Color color,
|
||||
Color outline, double outlineWidth) {
|
||||
double midDeg() {
|
||||
return startDeg + sweepDeg / 2.0;
|
||||
}
|
||||
}
|
||||
|
||||
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette,
|
||||
ChartRenderer.Legend legend) {
|
||||
if (spec.series.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ChartSpec.Series s = spec.series.get(0);
|
||||
double total = 0;
|
||||
for (Double v : s.values) {
|
||||
if (v != null && v > 0) {
|
||||
total += v;
|
||||
}
|
||||
}
|
||||
if (total <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean threeD = spec.type == ChartSpec.Type.PIE3D;
|
||||
double tilt = threeD ? Math.sin(Math.toRadians(clampRotX(spec.rotX))) * TILT_CORRECTION : 1.0;
|
||||
double depthPct = threeD ? spec.depthPercent / 100.0 : 0.0;
|
||||
double depthRatio = DEPTH_RATIO * depthPct;
|
||||
|
||||
// Подбираем радиус так, чтобы эллипс вместе с экструзией влез в box
|
||||
double rx = Math.min(box.getWidth() / 2.0,
|
||||
box.getHeight() / (2.0 * tilt + 2.0 * depthRatio));
|
||||
rx = Math.max(4, rx * FIT_MARGIN);
|
||||
double ry = rx * tilt;
|
||||
double depth = rx * depthRatio;
|
||||
double cx = box.getCenterX();
|
||||
double cy = box.getY() + ry + (box.getHeight() - (2 * ry + depth)) / 2.0;
|
||||
|
||||
List<Slice> slices = new ArrayList<>();
|
||||
double angle = 0;
|
||||
for (int i = 0; i < s.values.size(); i++) {
|
||||
Double v = s.values.get(i);
|
||||
if (v == null || v <= 0) {
|
||||
continue;
|
||||
}
|
||||
double sweep = 360.0 * v / total;
|
||||
Color fill = s.fillAt(i, palette);
|
||||
Color outline = s.outlineNoFill ? null
|
||||
: (s.outlineColor != null ? s.outlineColor : Color.WHITE);
|
||||
double ow = s.outlineWidth > 0 ? s.outlineWidth : 1.0;
|
||||
slices.add(new Slice(angle, sweep, fill, outline, ow));
|
||||
angle += sweep;
|
||||
}
|
||||
|
||||
// Задние сектора раньше, передние позже: дальняя сторона торта —
|
||||
// это 12 часов (midDeg≈0/360, cos≈1), поэтому сортировка по cos
|
||||
// должна быть убывающей, иначе дальние сектора рисуются поверх
|
||||
// передних и перекрывают их торцы.
|
||||
slices.sort(Comparator.comparingDouble(
|
||||
(Slice sl) -> -Math.cos(Math.toRadians(sl.midDeg()))));
|
||||
|
||||
for (Slice sl : slices) {
|
||||
drawSlice(g, sl, cx, cy, rx, ry, depth,
|
||||
spec.type == ChartSpec.Type.DOUGHNUT ? 0.5 : 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
private static double clampRotX(double rotX) {
|
||||
return Math.max(0, Math.min(90, rotX));
|
||||
}
|
||||
|
||||
/**
|
||||
* Один сектор. Углы Word: от 12 часов по часовой. Перевод в параметрический
|
||||
* угол Java: theta = 90 - wordAngle (y на экране растёт вниз).
|
||||
*/
|
||||
private static void drawSlice(Graphics2D g, Slice sl, double cx, double cy,
|
||||
double rx, double ry, double depth, double holeRatio) {
|
||||
double thetaStart = 90.0 - sl.startDeg();
|
||||
double thetaSweep = -sl.sweepDeg();
|
||||
|
||||
if (depth > 0.01) {
|
||||
drawWalls(g, sl, cx, cy, rx, ry, depth);
|
||||
}
|
||||
Arc2D.Double top = new Arc2D.Double(cx - rx, cy - ry, 2 * rx, 2 * ry,
|
||||
thetaStart, thetaSweep, Arc2D.PIE);
|
||||
g.setColor(sl.color());
|
||||
g.fill(top);
|
||||
if (holeRatio > 0) {
|
||||
double hrx = rx * holeRatio;
|
||||
double hry = ry * holeRatio;
|
||||
Path2D hole = new Path2D.Double();
|
||||
hole.append(new Arc2D.Double(cx - hrx, cy - hry, 2 * hrx, 2 * hry,
|
||||
thetaStart, thetaSweep, Arc2D.PIE), false);
|
||||
g.setColor(Color.WHITE);
|
||||
g.fill(hole);
|
||||
}
|
||||
if (sl.outline() != null) {
|
||||
g.setColor(sl.outline());
|
||||
g.setStroke(new BasicStroke((float) sl.outlineWidth()));
|
||||
g.draw(top);
|
||||
}
|
||||
}
|
||||
|
||||
/** Боковая стенка дуги + торцы радиальных граней (видимая нижняя половина). */
|
||||
private static void drawWalls(Graphics2D g, Slice sl, double cx, double cy,
|
||||
double rx, double ry, double depth) {
|
||||
double thetaStart = 90.0 - sl.startDeg();
|
||||
double thetaEnd = thetaStart - sl.sweepDeg();
|
||||
// Боковая стенка цилиндра в Word освещена сбоку: слева ~0,75 от цвета
|
||||
// сектора, справа ~0,40 (замер по word-export.pdf, 300 dpi: ×0,71 у x=250,
|
||||
// ×0,58 у x=440, ×0,40 у x=640). Плоская заливка делает пирог
|
||||
// «бумажным», поэтому стенку красят горизонтальным градиентом.
|
||||
Color left = DrawMlColor.darken(sl.color(), 0.25);
|
||||
Color right = DrawMlColor.darken(sl.color(), 0.60);
|
||||
|
||||
// Видимая часть дуги: sin(theta) < 0 (нижняя половина эллипса)
|
||||
List<double[]> visible = visibleArc(thetaStart, thetaEnd);
|
||||
for (double[] seg : visible) {
|
||||
Path2D wall = new Path2D.Double();
|
||||
boolean first = true;
|
||||
// шаг 1°: при 4° хорда между точками дуги отстаёт от дуги на
|
||||
// десятки пикселей (эллипс пологий) и вдоль границы сектора
|
||||
// остаётся белый клин между стенкой соседнего сектора и торцом
|
||||
for (double t = seg[0]; t <= seg[1] + 1e-9; t += 1.0) {
|
||||
Point2D p = point(cx, cy, rx, ry, t);
|
||||
if (first) {
|
||||
wall.moveTo(p.getX(), p.getY());
|
||||
first = false;
|
||||
} else {
|
||||
wall.lineTo(p.getX(), p.getY());
|
||||
}
|
||||
}
|
||||
Point2D end = point(cx, cy, rx, ry, seg[1]);
|
||||
wall.lineTo(end.getX(), end.getY() + depth);
|
||||
for (double t = seg[1]; t >= seg[0] - 1e-9; t -= 1.0) {
|
||||
Point2D p = point(cx, cy, rx, ry, t);
|
||||
wall.lineTo(p.getX(), p.getY() + depth);
|
||||
}
|
||||
wall.closePath();
|
||||
g.setPaint(new java.awt.GradientPaint(
|
||||
new Point2D.Double(cx - rx, 0), left,
|
||||
new Point2D.Double(cx + rx, 0), right));
|
||||
g.fill(wall);
|
||||
if (sl.outline() != null) {
|
||||
g.setColor(sl.outline());
|
||||
g.setStroke(new BasicStroke((float) sl.outlineWidth()));
|
||||
g.draw(wall);
|
||||
}
|
||||
}
|
||||
|
||||
// Торцы: радиальные грани на границах сектора. Видна только та грань,
|
||||
// чья внешняя нормаль смотрит «вверх» по экрану (камера наклонена на
|
||||
// rotX: грань видна, если её нормаль в плоскости круга имеет
|
||||
// составляющую к наблюдателю). Для начальной границы сектора внешняя
|
||||
// нормаль — это dP/dt, для конечной — обратная, отсюда разные признаки
|
||||
// cos(t). Прежний признак sin(t)<0 рисовал обе грани общей границы
|
||||
// соседних секторов, и торец дальнего сектора выползал наружу.
|
||||
for (int e = 0; e < 2; e++) {
|
||||
double t = e == 0 ? thetaStart : thetaEnd;
|
||||
double outwardUp = e == 0 ? -Math.cos(Math.toRadians(t))
|
||||
: Math.cos(Math.toRadians(t));
|
||||
if (outwardUp >= 0 || Math.sin(Math.toRadians(t)) >= 0) {
|
||||
continue;
|
||||
}
|
||||
Point2D p = point(cx, cy, rx, ry, t);
|
||||
Path2D face = new Path2D.Double();
|
||||
face.moveTo(cx, cy);
|
||||
face.lineTo(p.getX(), p.getY());
|
||||
face.lineTo(p.getX(), p.getY() + depth);
|
||||
face.lineTo(cx, cy + depth);
|
||||
face.closePath();
|
||||
g.setColor(DrawMlColor.darken(sl.color(), 0.30));
|
||||
g.fill(face);
|
||||
if (sl.outline() != null) {
|
||||
g.setColor(sl.outline());
|
||||
g.setStroke(new BasicStroke((float) sl.outlineWidth()));
|
||||
g.draw(face);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Пересечение дуги [a,b] (может идти по убыванию) с нижней полуокружностью
|
||||
* sin(theta) < 0. Возвращает сегменты в порядке возрастания угла.
|
||||
*/
|
||||
private static List<double[]> visibleArc(double a, double b) {
|
||||
double lo = Math.min(a, b);
|
||||
double hi = Math.max(a, b);
|
||||
List<double[]> out = new ArrayList<>();
|
||||
// нормализуем в [0,360) и идём по виткам
|
||||
double span = hi - lo;
|
||||
if (span >= 360) {
|
||||
out.add(new double[]{lo, lo + 360});
|
||||
return out;
|
||||
}
|
||||
for (double base = Math.floor(lo / 360.0) * 360.0; base < hi + 360; base += 360.0) {
|
||||
double segLo = Math.max(lo, base + 180.0);
|
||||
double segHi = Math.min(hi, base + 360.0);
|
||||
if (segHi > segLo + 1e-9) {
|
||||
out.add(new double[]{segLo, segHi});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Point2D point(double cx, double cy, double rx, double ry, double thetaDeg) {
|
||||
double t = Math.toRadians(thetaDeg);
|
||||
return new Point2D.Double(cx + rx * Math.cos(t), cy - ry * Math.sin(t));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import java.awt.geom.Area;
|
||||
import java.awt.geom.Ellipse2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.geom.RoundRectangle2D;
|
||||
|
||||
/**
|
||||
* Пресеты геометрии DrawingML (a:prstGeom) в объёме, который нужен
|
||||
* SmartArt-схемам: прямоугольники, эллипсы, шестерни и круговые стрелки.
|
||||
*
|
||||
* Неизвестный пресет -> прямоугольник (вызывающий логирует подмену):
|
||||
* для подписанной схемы это заметнее, чем пустое место.
|
||||
*/
|
||||
final class PrstGeomShapes {
|
||||
|
||||
private PrstGeomShapes() {
|
||||
}
|
||||
|
||||
/** Форма с необязательным отверстием (у шестерней — центральная втулка). */
|
||||
record Shape(Area area, Area hole) {
|
||||
Area filled() {
|
||||
if (hole == null) {
|
||||
return area;
|
||||
}
|
||||
Area a = new Area(area);
|
||||
a.subtract(hole);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param prst имя пресета из a:prstGeom/@prst
|
||||
* @param adj целочисленные adjs из a:avLst (в стотысячных долях/градусах*60000)
|
||||
*/
|
||||
static Shape build(String prst, int[] adj, double x, double y, double w, double h) {
|
||||
String p = prst == null ? "rect" : prst;
|
||||
switch (p) {
|
||||
case "rect" -> {
|
||||
return new Shape(new Area(new Rectangle2D.Double(x, y, w, h)), null);
|
||||
}
|
||||
case "roundRect" -> {
|
||||
double arc = Math.min(w, h) * 0.12;
|
||||
return new Shape(new Area(new RoundRectangle2D.Double(x, y, w, h, arc, arc)), null);
|
||||
}
|
||||
case "ellipse", "oval" -> {
|
||||
return new Shape(new Area(new Ellipse2D.Double(x, y, w, h)), null);
|
||||
}
|
||||
case "gear6", "gear9" -> {
|
||||
int teeth = p.equals("gear6") ? 6 : 9;
|
||||
return gear(x, y, w, h, teeth);
|
||||
}
|
||||
case "circularArrow", "leftCircularArrow", "rightCircularArrow",
|
||||
"curvedRightArrow", "curvedLeftArrow" -> {
|
||||
return circularArrow(x, y, w, h, adj,
|
||||
p.equals("leftCircularArrow") || p.equals("curvedLeftArrow"));
|
||||
}
|
||||
default -> {
|
||||
return new Shape(new Area(new Rectangle2D.Double(x, y, w, h)), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Шестерня: зубчатый венец + (опционально) центральное отверстие.
|
||||
* Внешний радиус немного меньше w/2 (× 0.92), чтобы соседние
|
||||
* шестерни в drawing1.xml не слипались там, где их ext-ы близко
|
||||
* (Word использует тот же приём — эффективный радиус ≈ 0.97·ext/2).
|
||||
* Зуб узкий и короткий, впадины — глубокие.
|
||||
*/
|
||||
private static Shape gear(double x, double y, double w, double h, int teeth) {
|
||||
double cx = x + w / 2.0;
|
||||
double cy = y + h / 2.0;
|
||||
double r = Math.min(w, h) / 2.0 * 0.82;
|
||||
double toothH = r * 0.18;
|
||||
double body = r - toothH;
|
||||
Path2D path = new Path2D.Double();
|
||||
double step = 2 * Math.PI / teeth;
|
||||
// зуб: основание -> подъём -> вершина (плоская) -> спуск
|
||||
double toothWidth = step * 0.30;
|
||||
for (int i = 0; i < teeth; i++) {
|
||||
double a = i * step;
|
||||
double a0 = a - toothWidth;
|
||||
double a1 = a + toothWidth;
|
||||
double gap1 = a + step - toothWidth;
|
||||
if (i == 0) {
|
||||
path.moveTo(cx + body * Math.cos(a0), cy + body * Math.sin(a0));
|
||||
} else {
|
||||
path.lineTo(cx + body * Math.cos(a0), cy + body * Math.sin(a0));
|
||||
}
|
||||
path.lineTo(cx + r * Math.cos(a0 + toothWidth * 0.5),
|
||||
cy + r * Math.sin(a0 + toothWidth * 0.5));
|
||||
path.lineTo(cx + r * Math.cos(a1 - toothWidth * 0.5),
|
||||
cy + r * Math.sin(a1 - toothWidth * 0.5));
|
||||
path.lineTo(cx + body * Math.cos(a1), cy + body * Math.sin(a1));
|
||||
// впадина: плоская дуга по body между зубьями
|
||||
path.lineTo(cx + body * Math.cos(gap1), cy + body * Math.sin(gap1));
|
||||
}
|
||||
path.closePath();
|
||||
return new Shape(new Area(path), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Круговая стрелка: сектор кольца + треугольный наконечник.
|
||||
* adj2/adj3 — углы начала/конца в 1/60000 градуса (0 = на 3 часа,
|
||||
* по часовой, т.к. y на экране растёт вниз).
|
||||
*/
|
||||
private static Shape circularArrow(double x, double y, double w, double h,
|
||||
int[] adj, boolean arrowAtStart) {
|
||||
double cx = x + w / 2.0;
|
||||
double cy = y + h / 2.0;
|
||||
double rOuter = Math.min(w, h) / 2.0 * 0.92;
|
||||
// adj1 у реальных схем даёт невидимую полоску — держим минимум.
|
||||
double thickness = Math.max(rOuter * pct(adj, 0, 40000), rOuter * 0.07);
|
||||
double rInner = Math.max(1, rOuter - thickness);
|
||||
double startDeg = deg(adj, 1, 2700000);
|
||||
double endDeg = deg(adj, 2, 3600000);
|
||||
if (Math.abs(endDeg - startDeg) < 1) {
|
||||
endDeg = startDeg + 270;
|
||||
}
|
||||
|
||||
double a0 = Math.toRadians(startDeg);
|
||||
double a1 = Math.toRadians(endDeg);
|
||||
if (a1 < a0) {
|
||||
a1 += 2 * Math.PI;
|
||||
}
|
||||
Path2D path = new Path2D.Double();
|
||||
arcSegment(path, cx, cy, rOuter, a0, a1, true);
|
||||
arcSegment(path, cx, cy, rInner, a1, a0, false);
|
||||
path.closePath();
|
||||
Area area = new Area(path);
|
||||
|
||||
// Наконечник: размеры берём от толщины кольца — adjs у реальных
|
||||
// схем (adj4/adj5) дают либо абсурдный угол, либо невидимый «усик».
|
||||
// headOut ограничен, чтобы он не вылезал сильно за rOuter (иначе
|
||||
// кольцо цепляется с шестерёнкой, центр которой совпадает со стрелкой).
|
||||
double rMid = (rOuter + rInner) / 2.0;
|
||||
double headOut = Math.min(thickness * 1.15, thickness * 2.0);
|
||||
double tipAngle = arrowAtStart ? a0 - thickness * 1.7 / rMid : a1 + thickness * 1.7 / rMid;
|
||||
double baseAngle = thickness * 0.9 / rMid;
|
||||
double base = arrowAtStart ? a0 : a1;
|
||||
Path2D head = new Path2D.Double();
|
||||
head.moveTo(cx + (rOuter + headOut * 0.2) * Math.cos(base - Math.copySign(baseAngle, base - tipAngle)),
|
||||
cy + (rOuter + headOut * 0.2) * Math.sin(base - Math.copySign(baseAngle, base - tipAngle)));
|
||||
head.lineTo(cx + rMid * Math.cos(tipAngle), cy + rMid * Math.sin(tipAngle));
|
||||
head.lineTo(cx + Math.max(1, rInner - headOut) * Math.cos(base - Math.copySign(baseAngle, base - tipAngle)),
|
||||
cy + Math.max(1, rInner - headOut) * Math.sin(base - Math.copySign(baseAngle, base - tipAngle)));
|
||||
head.closePath();
|
||||
area.add(new Area(head));
|
||||
return new Shape(area, null);
|
||||
}
|
||||
|
||||
private static void arcSegment(Path2D path, double cx, double cy, double r,
|
||||
double a0, double a1, boolean forward) {
|
||||
int steps = Math.max(2, (int) (Math.abs(a1 - a0) / Math.toRadians(4)));
|
||||
for (int i = 0; i <= steps; i++) {
|
||||
double t = a0 + (a1 - a0) * i / steps;
|
||||
double px = cx + r * Math.cos(t);
|
||||
double py = cy + r * Math.sin(t);
|
||||
if (i == 0 && (path.getCurrentPoint() == null
|
||||
|| Math.abs(path.getCurrentPoint().getX() - px) > 1e-9
|
||||
|| Math.abs(path.getCurrentPoint().getY() - py) > 1e-9)) {
|
||||
path.moveTo(px, py);
|
||||
} else {
|
||||
path.lineTo(px, py);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static double pct(int[] adj, int idx, int def) {
|
||||
int v = adj != null && idx < adj.length ? adj[idx] : def;
|
||||
return v / 100000.0;
|
||||
}
|
||||
|
||||
private static double deg(int[] adj, int idx, int def) {
|
||||
int v = adj != null && idx < adj.length ? adj[idx] : def;
|
||||
return v / 60000.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
/**
|
||||
* Конвертация RGB <-> HSL. Нужна для трансформаций цвета из DrawingML
|
||||
* (lumMod/lumOff/satMod/hueOff работают в пространстве тона/насыщенность/
|
||||
* светлота, а не в RGB).
|
||||
*/
|
||||
final class RgbHsl {
|
||||
|
||||
private RgbHsl() {
|
||||
}
|
||||
|
||||
/** @return {hue 0..360, saturation 0..1, luminance 0..1} */
|
||||
static double[] toHsl(Color c) {
|
||||
double r = c.getRed() / 255.0;
|
||||
double g = c.getGreen() / 255.0;
|
||||
double b = c.getBlue() / 255.0;
|
||||
double max = Math.max(r, Math.max(g, b));
|
||||
double min = Math.min(r, Math.min(g, b));
|
||||
double l = (max + min) / 2.0;
|
||||
double h = 0.0;
|
||||
double s = 0.0;
|
||||
if (max != min) {
|
||||
double d = max - min;
|
||||
s = l > 0.5f ? d / (2f - max - min) : d / (max + min);
|
||||
if (max == r) {
|
||||
h = (g - b) / d + (g < b ? 6f : 0f);
|
||||
} else if (max == g) {
|
||||
h = (b - r) / d + 2f;
|
||||
} else {
|
||||
h = (r - g) / d + 4f;
|
||||
}
|
||||
h *= 60.0;
|
||||
}
|
||||
return new double[]{h, s, l};
|
||||
}
|
||||
|
||||
static Color fromHsl(double h, double s, double l) {
|
||||
double hh = (((h % 360) + 360) % 360) / 360.0;
|
||||
double ss = Math.max(0, Math.min(1, s));
|
||||
double ll = Math.max(0, Math.min(1, l));
|
||||
double r, g, b;
|
||||
if (ss == 0.0) {
|
||||
r = g = b = ll;
|
||||
} else {
|
||||
double q = ll < 0.5 ? ll * (1.0 + ss) : ll + ss - ll * ss;
|
||||
double p = 2.0 * ll - q;
|
||||
r = hueToRgb(p, q, hh + 1.0 / 3.0);
|
||||
g = hueToRgb(p, q, hh);
|
||||
b = hueToRgb(p, q, hh - 1.0 / 3.0);
|
||||
}
|
||||
return new Color(clamp(Math.round(r * 255)),
|
||||
clamp(Math.round(g * 255)), clamp(Math.round(b * 255)));
|
||||
}
|
||||
|
||||
private static int clamp(long v) {
|
||||
return (int) Math.max(0, Math.min(255, v));
|
||||
}
|
||||
|
||||
private static double hueToRgb(double p, double q, double t) {
|
||||
if (t < 0.0) {
|
||||
t += 1.0;
|
||||
}
|
||||
if (t > 1.0) {
|
||||
t -= 1.0;
|
||||
}
|
||||
if (t < 1.0 / 6.0) {
|
||||
return p + (q - p) * 6.0 * t;
|
||||
}
|
||||
if (t < 0.5) {
|
||||
return q;
|
||||
}
|
||||
if (t < 2.0 / 3.0) {
|
||||
return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import org.docx4j.dml.CTGeomGuide;
|
||||
import org.docx4j.dml.CTGradientFillProperties;
|
||||
import org.docx4j.dml.CTGradientStop;
|
||||
import org.docx4j.dml.CTPoint2D;
|
||||
import org.docx4j.dml.CTPositiveSize2D;
|
||||
import org.docx4j.dml.CTPresetGeometry2D;
|
||||
import org.docx4j.dml.CTShapeProperties;
|
||||
import org.docx4j.dml.CTShapeStyle;
|
||||
import org.docx4j.dml.CTTextBody;
|
||||
import org.docx4j.dml.CTTransform2D;
|
||||
import org.docx4j.dml.diagram.CTCxn;
|
||||
import org.docx4j.dml.diagram.CTDataModel;
|
||||
import org.docx4j.dml.diagram.STCxnType;
|
||||
import org.docx4j.dml.diagram.CTElemPropSet;
|
||||
import org.docx4j.dml.diagram.CTPt;
|
||||
import org.docx4j.dml.diagram2008.CTDrawing;
|
||||
import org.docx4j.dml.diagram2008.CTShape;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.Area;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* SmartArt в растр. Рисуется {@code word/diagrams/drawing1.xml} — это
|
||||
* кэш уже разложенной Word-ом схемы: у каждой фигуры есть абсолютная
|
||||
* позиция, пресет геометрии, заливка, обводка и текст. Поэтому
|
||||
* собственный движок раскладки SmartArt не нужен.
|
||||
*
|
||||
* Пустые подписи фигур Word показывает текстом-заполнителем из
|
||||
* {@code data1.xml} (dgm:pt/dgm:prSet/@phldrT) — его берём оттуда же.
|
||||
*/
|
||||
final class SmartArtRenderer {
|
||||
|
||||
static final int DPI = ChartRenderer.DPI;
|
||||
|
||||
private SmartArtRenderer() {
|
||||
}
|
||||
|
||||
private record Item(CTShape shape, double x, double y, double w, double h, double rotDeg) {
|
||||
}
|
||||
|
||||
static BufferedImage render(CTDrawing drawing, CTDataModel data, DrawMlColor colors,
|
||||
double widthPt, double heightPt) {
|
||||
List<Item> items = new ArrayList<>();
|
||||
for (Object o : drawing.getSpTree().getSpOrGrpSp()) {
|
||||
if (!(o instanceof CTShape sp)) {
|
||||
continue;
|
||||
}
|
||||
CTTransform2D t = sp.getSpPr() == null ? null : sp.getSpPr().getXfrm();
|
||||
if (t == null || t.getExt() == null) {
|
||||
continue;
|
||||
}
|
||||
CTPoint2D off = t.getOff();
|
||||
CTPositiveSize2D ext = t.getExt();
|
||||
double rot = t.getRot() / 60000.0;
|
||||
items.add(new Item(sp,
|
||||
(off == null ? 0 : off.getX()) / 12700.0,
|
||||
(off == null ? 0 : off.getY()) / 12700.0,
|
||||
ext.getCx() / 12700.0,
|
||||
ext.getCy() / 12700.0,
|
||||
rot));
|
||||
}
|
||||
int w = Math.max(16, (int) Math.round(widthPt * DPI / 72.0));
|
||||
int h = Math.max(16, (int) Math.round(heightPt * DPI / 72.0));
|
||||
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
try {
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
|
||||
RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
|
||||
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
|
||||
RenderingHints.VALUE_STROKE_PURE);
|
||||
g.scale(DPI / 72.0, DPI / 72.0);
|
||||
if (items.isEmpty()) {
|
||||
return img;
|
||||
}
|
||||
double minX = Double.MAX_VALUE;
|
||||
double minY = Double.MAX_VALUE;
|
||||
double maxX = -Double.MAX_VALUE;
|
||||
double maxY = -Double.MAX_VALUE;
|
||||
for (Item it : items) {
|
||||
minX = Math.min(minX, it.x());
|
||||
minY = Math.min(minY, it.y());
|
||||
maxX = Math.max(maxX, it.x() + it.w());
|
||||
maxY = Math.max(maxY, it.y() + it.h());
|
||||
}
|
||||
double mw = Math.max(1e-6, maxX - minX);
|
||||
double mh = Math.max(1e-6, maxY - minY);
|
||||
// 0.80: drawing1.xml хранит ext-ы вплотную (gear6+gear6,
|
||||
// gear6+circularArrow с почти одним центром), при scale=0.96
|
||||
// они слипаются. 0.80 даёт зазор ~10% от ext — как в эталоне.
|
||||
double scale = Math.min(widthPt / mw, heightPt / mh) * 0.80;
|
||||
double offX = (widthPt - mw * scale) / 2.0 - minX * scale;
|
||||
double offY = (heightPt - mh * scale) / 2.0 - minY * scale;
|
||||
|
||||
Map<String, String> placeholders = placeholders(data);
|
||||
for (Item it : items) {
|
||||
drawShape(g, it, colors, scale, offX, offY, placeholders);
|
||||
}
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
/**
|
||||
* Подписи-заполнители. Форма в 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,
|
||||
double scale, double offX, double offY,
|
||||
Map<String, String> placeholders) {
|
||||
CTShape sp = it.shape();
|
||||
CTShapeProperties spPr = sp.getSpPr();
|
||||
double x = it.x() * scale + offX;
|
||||
double y = it.y() * scale + offY;
|
||||
double sw = it.w() * scale;
|
||||
double sh = it.h() * scale;
|
||||
|
||||
AffineTransform saved = g.getTransform();
|
||||
if (Math.abs(it.rotDeg()) > 0.01) {
|
||||
g.rotate(Math.toRadians(it.rotDeg()), x + sw / 2.0, y + sh / 2.0);
|
||||
}
|
||||
|
||||
String prst = null;
|
||||
int[] adj = new int[0];
|
||||
if (spPr != null && spPr.getPrstGeom() != null) {
|
||||
CTPresetGeometry2D pg = spPr.getPrstGeom();
|
||||
prst = pg.getPrst() == null ? null : pg.getPrst().value();
|
||||
if (pg.getAvLst() != null) {
|
||||
List<CTGeomGuide> gd = pg.getAvLst().getGd();
|
||||
adj = new int[gd.size()];
|
||||
for (int i = 0; i < gd.size(); i++) {
|
||||
adj[i] = parseGuide(gd.get(i).getFmla());
|
||||
}
|
||||
}
|
||||
}
|
||||
PrstGeomShapes.Shape shape = PrstGeomShapes.build(prst, adj, x, y, sw, sh);
|
||||
Area area = shape.filled();
|
||||
|
||||
Color fill = resolveFill(spPr, colors);
|
||||
if (fill != null) {
|
||||
g.setColor(fill);
|
||||
g.fill(area);
|
||||
}
|
||||
Color lineColor = null;
|
||||
double lineWidth = 1.0;
|
||||
if (spPr != null && spPr.getLn() != null) {
|
||||
if (spPr.getLn().getNoFill() == null) {
|
||||
lineColor = spPr.getLn().getSolidFill() != null
|
||||
? colors.resolveFill(spPr.getLn().getSolidFill())
|
||||
: colors.schemeColor("lt1");
|
||||
}
|
||||
if (spPr.getLn().getW() != null) {
|
||||
lineWidth = spPr.getLn().getW() / 12700.0;
|
||||
}
|
||||
} else if (sp.getStyle() != null && sp.getStyle().getLnRef() != null
|
||||
&& sp.getStyle().getLnRef().getIdx() > 0) {
|
||||
// стиль-матрица: тонкая светлая обводка
|
||||
lineColor = colors.schemeColor("lt1");
|
||||
lineWidth = 1.0;
|
||||
}
|
||||
if (lineColor != null) {
|
||||
g.setColor(lineColor);
|
||||
g.setStroke(new BasicStroke((float) Math.max(0.4, lineWidth * scale)));
|
||||
g.draw(area);
|
||||
}
|
||||
g.setTransform(saved);
|
||||
|
||||
// Текст: собственный прямоугольник (dsp:txXfrm) или границы фигуры
|
||||
double tx = x;
|
||||
double ty = y;
|
||||
double tw = sw;
|
||||
double th = sh;
|
||||
CTTransform2D txXfrm = sp.getTxXfrm();
|
||||
if (txXfrm != null && txXfrm.getExt() != null) {
|
||||
CTPoint2D o = txXfrm.getOff();
|
||||
tx = (o == null ? 0 : o.getX()) / 12700.0 * scale + offX;
|
||||
ty = (o == null ? 0 : o.getY()) / 12700.0 * scale + offY;
|
||||
tw = txXfrm.getExt().getCx() / 12700.0 * scale;
|
||||
th = txXfrm.getExt().getCy() / 12700.0 * scale;
|
||||
}
|
||||
|
||||
Color textColor = textColor(sp, colors);
|
||||
List<DrawMlText.Paragraph> paragraphs = new ArrayList<>();
|
||||
if (sp.getTxBody() != null) {
|
||||
paragraphs = DrawMlText.paragraphs(sp.getTxBody(), colors,
|
||||
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()) {
|
||||
return;
|
||||
}
|
||||
// Шрифт из XML (sz=2600 → 26pt) слишком крупный для маленьких
|
||||
// шестерёнок SmartArt: "123" лезет поверх зубьев. Ограничиваем
|
||||
// начальный кегль ~25% меньшей стороны текстового прямоугольника.
|
||||
double capPt = Math.max(4.0, Math.min(tw, th) * 0.25);
|
||||
if (p0(paragraphs) > capPt) {
|
||||
List<DrawMlText.Paragraph> shrunk = new ArrayList<>();
|
||||
for (DrawMlText.Paragraph p : paragraphs) {
|
||||
shrunk.add(new DrawMlText.Paragraph(p.text(),
|
||||
p.style().derive(capPt, null, null, null, null), p.align()));
|
||||
}
|
||||
paragraphs = shrunk;
|
||||
}
|
||||
// autosize: уменьшаем кегль, пока текст не влезет в прямоугольник
|
||||
for (int attempt = 0; attempt < 4; attempt++) {
|
||||
double needed = 0;
|
||||
for (DrawMlText.Paragraph p : paragraphs) {
|
||||
needed += DrawMlText.textHeight(p.style(), g.getFontRenderContext());
|
||||
}
|
||||
if (needed <= th || p0(paragraphs) <= 4) {
|
||||
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),
|
||||
"ctr", "ctr", 1.0);
|
||||
}
|
||||
|
||||
private static double p0(List<DrawMlText.Paragraph> ps) {
|
||||
return ps.isEmpty() ? 0 : ps.get(0).style().sizePt();
|
||||
}
|
||||
|
||||
private static Color resolveFill(CTShapeProperties spPr, DrawMlColor colors) {
|
||||
if (spPr == null) {
|
||||
return null;
|
||||
}
|
||||
if (spPr.getNoFill() != null) {
|
||||
return null;
|
||||
}
|
||||
if (spPr.getSolidFill() != null) {
|
||||
return colors.resolveFill(spPr.getSolidFill());
|
||||
}
|
||||
CTGradientFillProperties grad = spPr.getGradFill();
|
||||
if (grad != null && grad.getGsLst() != null && !grad.getGsLst().getGs().isEmpty()) {
|
||||
List<CTGradientStop> stops = grad.getGsLst().getGs();
|
||||
Color mid = colors.resolveStop(stops.get(stops.size() / 2));
|
||||
return mid != null ? mid : colors.resolveStop(stops.get(0));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Color textColor(CTShape sp, DrawMlColor colors) {
|
||||
CTShapeStyle style = sp.getStyle();
|
||||
if (style != null && style.getFontRef() != null) {
|
||||
Color resolved = colors.resolveFontRef(style.getFontRef());
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return new Color(0x59, 0x59, 0x59);
|
||||
}
|
||||
|
||||
/** a:gd/@fmla = "val 4687" -> 4687. */
|
||||
private static int parseGuide(String fmla) {
|
||||
if (fmla == null) {
|
||||
return 0;
|
||||
}
|
||||
String s = fmla.trim();
|
||||
if (s.startsWith("val")) {
|
||||
s = s.substring(3).trim();
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(s);
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Объёмная поверхностная диаграмма (c:surface3D).
|
||||
*
|
||||
* Модель: u — категория (ширина), v — ряд (глубина), w — значение (высота),
|
||||
* всё в [-0.5, 0.5]. Порядок преобразований: поворот сцены вокруг вертикали
|
||||
* на c:view3D/rotY, наклон камеры на rotX, затем перспектива по
|
||||
* c:view3D/perspective (по умолчанию 30°) с глубиной c:view3D/depth.
|
||||
*
|
||||
* Грани — ровно ячейки исходной сетки (без передискретизации): каждая
|
||||
* разбивается на два треугольника, цвет берётся из полосы высот
|
||||
* (c:bandFmts) и затемняется по нормали грани — именно это даёт объём,
|
||||
* как в Word. Порядок отрисовки — painter's algorithm по глубине
|
||||
* центроида треугольника.
|
||||
*/
|
||||
final class Surface3dPainter {
|
||||
|
||||
/**
|
||||
* Расстояние камеры сцены (в долях ширины коробки построения).
|
||||
* `c:view3D/perspective` (по умолчанию 30) — это НЕ угол обзора, а
|
||||
* коэффициент глубины: он масштабирует расстояние относительно
|
||||
* эталонных 30. Значение откалибровано по эталону Word
|
||||
* (см. Surface3dPainterTest.cameraMatchesWordReference).
|
||||
*/
|
||||
static final double CAMERA_DISTANCE = 2.36;
|
||||
|
||||
/**
|
||||
* Глубина коробки построения относительно ширины (при c:view3D/depth = 100).
|
||||
* Заметно больше «наивной» четверти ширины: Word уходит в глубину почти
|
||||
* на две трети, иначе лента выглядит плоской, а шаг оси рядов
|
||||
* (Ряд 1 → Ряд 2) выходит на треть меньше эталона.
|
||||
*/
|
||||
static final double DEPTH_RATIO = 0.705;
|
||||
|
||||
/** Высота значений относительно аспекта области построения. */
|
||||
static final double HEIGHT_RATIO = 0.664;
|
||||
|
||||
/**
|
||||
* Поля вокруг коробки построения — доли области построения (box без
|
||||
* заголовка и легенды): слева/справа под подписи осей значений и рядов,
|
||||
* сверху/снизу — отступы Word. Коробка занимает ~73% ширины области:
|
||||
* при полях «на глаз» (30/44 pt) поверхность растягивалась на 82%
|
||||
* ширины и лезла на подписи оси значений.
|
||||
*/
|
||||
static final double GUTTER_LEFT = 0.1485;
|
||||
static final double GUTTER_RIGHT = 0.1485;
|
||||
static final double GUTTER_TOP = 0.116;
|
||||
static final double GUTTER_BOTTOM = 0.146;
|
||||
|
||||
/**
|
||||
* Направление света в экранных координатах: x вправо, y «в экран»,
|
||||
* z «на зрителя». Подобрано по квантилям множителей яркости граней
|
||||
* эталона Word (см. Surface3dPainterTest.shadingMatchesWordReference).
|
||||
*/
|
||||
private static final double LIGHT_X = 0.83;
|
||||
private static final double LIGHT_Y = 0.48;
|
||||
private static final double LIGHT_Z = 0.28;
|
||||
|
||||
private Surface3dPainter() {
|
||||
}
|
||||
|
||||
/** Проекция узла: экранные координаты модельного пространства + глубина. */
|
||||
record Node(double x, double y, double depth) {
|
||||
}
|
||||
|
||||
private record Tri(Path2D path, Color color, double depth) {
|
||||
}
|
||||
|
||||
/** Вписывание модельно-экранных координат в box. */
|
||||
private record Fit(double scaleX, double scaleY, double offX, double offY) {
|
||||
}
|
||||
|
||||
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
|
||||
int nSer = spec.series.size();
|
||||
int nCat = 0;
|
||||
for (ChartSpec.Series s : spec.series) {
|
||||
nCat = Math.max(nCat, s.values.size());
|
||||
}
|
||||
if (nSer < 2 || nCat < 2) {
|
||||
return;
|
||||
}
|
||||
double[][] z = new double[nSer][nCat];
|
||||
double min = Double.MAX_VALUE;
|
||||
double max = -Double.MAX_VALUE;
|
||||
for (int r = 0; r < nSer; r++) {
|
||||
for (int c = 0; c < nCat; c++) {
|
||||
List<Double> vals = spec.series.get(r).values;
|
||||
double v = c < vals.size() && vals.get(c) != null ? vals.get(c) : 0;
|
||||
z[r][c] = v;
|
||||
min = Math.min(min, v);
|
||||
max = Math.max(max, v);
|
||||
}
|
||||
}
|
||||
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
|
||||
double[] bounds = ChartRenderer.axisBounds(valAxis, min, max);
|
||||
double lo = bounds[0];
|
||||
double hi = bounds[1];
|
||||
double unit = bounds[2];
|
||||
double span = Math.max(1e-9, hi - lo);
|
||||
|
||||
double rotX = Math.toRadians(spec.rotX);
|
||||
// Знак rotY в DrawingML обратный правому правилу вокруг вертикали:
|
||||
// положительный поворот приближает к зрителю правый край, поэтому
|
||||
// передняя кромка («Категория 1 → Категория 4») идёт вниз вправо.
|
||||
double rotY = -Math.toRadians(spec.rotY);
|
||||
double persp = spec.perspective;
|
||||
|
||||
// Пропорции «коробки» построения, снятые с эталона Word: глубина —
|
||||
// DEPTH_RATIO ширины (c:view3D/depth от неё), высота значений —
|
||||
// HEIGHT_RATIO·availH/availW. Оба коэффициента откалиброваны
|
||||
// Surface3dPainterTest.cameraMatchesWordReference по замерам
|
||||
// стр. 3 word-export.pdf (уклон передней кромки, аспект силуэта, шаг оси
|
||||
// значений и шаг оси рядов). Подменять их Math.max с множителем
|
||||
// availH/availW·1.0 нельзя: это даёт +56% к высоте и превращает
|
||||
// ленту в гору.
|
||||
double leftGutter = GUTTER_LEFT * box.getWidth();
|
||||
double rightGutter = GUTTER_RIGHT * box.getWidth();
|
||||
double bottomGutter = GUTTER_BOTTOM * box.getHeight();
|
||||
double topGutter = GUTTER_TOP * box.getHeight();
|
||||
double availW = Math.max(10, box.getWidth() - leftGutter - rightGutter);
|
||||
double availH = Math.max(10, box.getHeight() - bottomGutter - topGutter);
|
||||
double depthScale = DEPTH_RATIO * Math.max(0.05, spec.depthPercent / 100.0);
|
||||
double heightScale = HEIGHT_RATIO * availH / availW;
|
||||
|
||||
// 1. Узлы сетки и пол — в модельно-экранные координаты
|
||||
Node[][] node = new Node[nSer][nCat];
|
||||
double minX = Double.MAX_VALUE;
|
||||
double maxX = -Double.MAX_VALUE;
|
||||
double minY = Double.MAX_VALUE;
|
||||
double maxY = -Double.MAX_VALUE;
|
||||
for (int r = 0; r < nSer; r++) {
|
||||
for (int c = 0; c < nCat; c++) {
|
||||
node[r][c] = project(uOf(c, nCat), vOf(r, nSer),
|
||||
((z[r][c] - lo) / span - 0.5) * heightScale, rotX, rotY, depthScale, persp);
|
||||
minX = Math.min(minX, node[r][c].x());
|
||||
maxX = Math.max(maxX, node[r][c].x());
|
||||
minY = Math.min(minY, node[r][c].y());
|
||||
maxY = Math.max(maxY, node[r][c].y());
|
||||
}
|
||||
}
|
||||
double floorW = -0.5 * heightScale;
|
||||
Node[] floor = {
|
||||
project(-0.5, -0.5, floorW, rotX, rotY, depthScale, persp),
|
||||
project(0.5, -0.5, floorW, rotX, rotY, depthScale, persp),
|
||||
project(0.5, 0.5, floorW, rotX, rotY, depthScale, persp),
|
||||
project(-0.5, 0.5, floorW, rotX, rotY, depthScale, persp),
|
||||
};
|
||||
// Ось значений привязана к переднему левому ребру левой стенки
|
||||
// (v = -0.5), а не к дальней стенке: у дальней стенки ребро дальше
|
||||
// от камеры, и подписи уезжают внутрь поверхности.
|
||||
List<Node> valueAnchors = new ArrayList<>();
|
||||
for (double v = lo; v <= hi + unit / 2; v += unit) {
|
||||
Node n = project(-0.5, -0.5, ((v - lo) / span - 0.5) * heightScale,
|
||||
rotX, rotY, depthScale, persp);
|
||||
valueAnchors.add(n);
|
||||
minX = Math.min(minX, n.x());
|
||||
maxX = Math.max(maxX, n.x());
|
||||
minY = Math.min(minY, n.y());
|
||||
maxY = Math.max(maxY, n.y());
|
||||
}
|
||||
for (Node n : floor) {
|
||||
minX = Math.min(minX, n.x());
|
||||
maxX = Math.max(maxX, n.x());
|
||||
minY = Math.min(minY, n.y());
|
||||
maxY = Math.max(maxY, n.y());
|
||||
}
|
||||
|
||||
// 2. Вписывание в box равномерным масштабом: коробка уже задана
|
||||
// в пропорциях области построения, поэтому растягивать x и y
|
||||
// раздельно нельзя — это ломает перспективу.
|
||||
double scale = Math.min(availW / Math.max(1e-6, maxX - minX),
|
||||
availH / Math.max(1e-6, maxY - minY));
|
||||
double offX = box.getX() + leftGutter
|
||||
+ (availW - (maxX - minX) * scale) / 2 - minX * scale;
|
||||
double offY = box.getY() + topGutter
|
||||
+ (availH - (maxY - minY) * scale) / 2 - minY * scale;
|
||||
Fit fit = new Fit(scale, scale, offX, offY);
|
||||
|
||||
// 3. Пол, дальняя стенка и их сетки — под поверхностью
|
||||
drawFloor(g, spec, floor, valueAnchors, nCat, nSer, lo, hi, unit, span,
|
||||
rotX, rotY, depthScale, heightScale, persp, fit);
|
||||
|
||||
// 4. Грани: два треугольника на ячейку, каждый разрезан по
|
||||
// горизонтальным плоскостям полос (c:bandFmts) — Word красит
|
||||
// полосу по высоте, а не весь треугольник по среднему значению.
|
||||
List<Tri> tris = new ArrayList<>();
|
||||
double spanUnit = unit / span;
|
||||
int bandCount = Math.max(1, (int) Math.ceil(span / unit - 1e-9));
|
||||
for (int r = 0; r + 1 < nSer; r++) {
|
||||
for (int c = 0; c + 1 < nCat; c++) {
|
||||
double u0 = uOf(c, nCat);
|
||||
double u1 = uOf(c + 1, nCat);
|
||||
double v0 = vOf(r, nSer);
|
||||
double v1 = vOf(r + 1, nSer);
|
||||
// u — категория, v — ряд: (u_c, v_r) <-> z[r][c].
|
||||
// Перепутать w01/w10 значит закрутить квад в «бабочку»:
|
||||
// в проекции появляются дыры и самопересечения граней.
|
||||
double w00 = ((z[r][c] - lo) / span - 0.5) * heightScale;
|
||||
double w01 = ((z[r + 1][c] - lo) / span - 0.5) * heightScale;
|
||||
double w11 = ((z[r + 1][c + 1] - lo) / span - 0.5) * heightScale;
|
||||
double w10 = ((z[r][c + 1] - lo) / span - 0.5) * heightScale;
|
||||
// Диагональ — та, чьи концы выше (сумма значений больше). Седловая
|
||||
// ячейка в проекции вогнутая, и фиксированная диагональ даёт то
|
||||
// грань не той полосы, то треугольник внутри треугольника. Word
|
||||
// всегда видит верхнюю огибающую седла: при w00+w11 < w01+w10 он
|
||||
// режет квад по w01–w10 (эталон word-export.pdf, стр. 3: ячейка
|
||||
// Ряд 1→2 / Категория 2→3 там полоса 3–4, а не 2–3).
|
||||
boolean mainDiagonal = z[r][c] + z[r + 1][c + 1] >= z[r + 1][c] + z[r][c + 1];
|
||||
if (mainDiagonal) {
|
||||
addTri(tris, spec, palette,
|
||||
new double[][]{{u0, v0, w00}, {u0, v1, w01}, {u1, v1, w11}},
|
||||
spanUnit * heightScale, heightScale, bandCount,
|
||||
rotX, rotY, depthScale, persp, fit);
|
||||
addTri(tris, spec, palette,
|
||||
new double[][]{{u0, v0, w00}, {u1, v1, w11}, {u1, v0, w10}},
|
||||
spanUnit * heightScale, heightScale, bandCount,
|
||||
rotX, rotY, depthScale, persp, fit);
|
||||
} else {
|
||||
addTri(tris, spec, palette,
|
||||
new double[][]{{u0, v0, w00}, {u0, v1, w01}, {u1, v0, w10}},
|
||||
spanUnit * heightScale, heightScale, bandCount,
|
||||
rotX, rotY, depthScale, persp, fit);
|
||||
addTri(tris, spec, palette,
|
||||
new double[][]{{u0, v1, w01}, {u1, v1, w11}, {u1, v0, w10}},
|
||||
spanUnit * heightScale, heightScale, bandCount,
|
||||
rotX, rotY, depthScale, persp, fit);
|
||||
}
|
||||
}
|
||||
}
|
||||
tris.sort(Comparator.comparingDouble(Tri::depth).reversed());
|
||||
BasicStroke seam = new BasicStroke(0.4f);
|
||||
for (Tri t : tris) {
|
||||
g.setColor(t.color());
|
||||
g.fill(t.path());
|
||||
g.setStroke(seam);
|
||||
g.draw(t.path());
|
||||
}
|
||||
if (spec.wireframe) {
|
||||
g.setColor(new Color(0x80, 0x80, 0x80));
|
||||
g.setStroke(new BasicStroke(0.5f));
|
||||
for (Tri t : tris) {
|
||||
g.draw(t.path());
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Подписи осей
|
||||
drawLabels(g, spec, valueAnchors, lo, hi, unit, nCat, nSer,
|
||||
rotX, rotY, depthScale, heightScale, persp, fit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Один треугольник ячейки: нормаль (и, как следствие, затемнение) считается
|
||||
* по исходному треугольнику, а сам он режется плоскостями полос высот —
|
||||
* поэтому одна грань может быть окрашена в два цвета, как в Word.
|
||||
*
|
||||
* @param pts три вершины в модельных координатах {u, v, w}
|
||||
* @param wUnit ширина полосы в нормализованных координатах высоты
|
||||
*/
|
||||
private static void addTri(List<Tri> tris, ChartSpec spec, List<Color> palette,
|
||||
double[][] pts, double wUnit, double hScale, int bandCount,
|
||||
double rotX, double rotY, double depthScale, double persp,
|
||||
Fit fit) {
|
||||
// v здесь ещё не умножен на depthScale (это делает project), а w уже
|
||||
// умножен на hScale. Без того же масштаба в нормали поверхность кажется
|
||||
// положе, чем она есть, и все грани попадают в светлую часть Lambert.
|
||||
double e1x = pts[1][0] - pts[0][0];
|
||||
double e1y = (pts[1][1] - pts[0][1]) * depthScale;
|
||||
double e1z = pts[1][2] - pts[0][2];
|
||||
double e2x = pts[2][0] - pts[0][0];
|
||||
double e2y = (pts[2][1] - pts[0][1]) * depthScale;
|
||||
double e2z = pts[2][2] - pts[0][2];
|
||||
double nx = e1y * e2z - e1z * e2y;
|
||||
double ny = e1z * e2x - e1x * e2z;
|
||||
double nz = e1x * e2y - e1y * e2x;
|
||||
double len = Math.hypot(Math.hypot(nx, ny), nz);
|
||||
if (len < 1e-12) {
|
||||
return;
|
||||
}
|
||||
nx /= len;
|
||||
ny /= len;
|
||||
nz /= len;
|
||||
if (nz < 0) {
|
||||
nx = -nx;
|
||||
ny = -ny;
|
||||
nz = -nz;
|
||||
}
|
||||
// та же ориентация, что и у точек (перспектива на нормаль не влияет)
|
||||
double ca = Math.cos(rotY);
|
||||
double sa = Math.sin(rotY);
|
||||
double nx1 = nx * ca - ny * sa;
|
||||
double ny1 = nx * sa + ny * ca;
|
||||
double cb = Math.cos(rotX);
|
||||
double sb = Math.sin(rotX);
|
||||
double ny2 = ny1 * cb - nz * sb;
|
||||
double nz2 = ny1 * sb + nz * cb;
|
||||
double dot = nx1 * LIGHT_X + ny2 * LIGHT_Y + nz2 * LIGHT_Z;
|
||||
// Word красит грани дискретными множителями цвета полосы; в эталоне
|
||||
// (word-export.pdf, 300 dpi, гистограмма цветов граней) это 0,40 / 0,75 / 0,85 /
|
||||
// 1,04 / 1,06 / 1,10. Тёмная группа 0,40 — узкая полоска underside под
|
||||
// передним краем ленты; разгон Lambert до неё (отрицательные dot,
|
||||
// 0,69 + 1,23·dot) затемняет слишком большие площади и ухудшает
|
||||
// совпадение с эталоном (17,2 → 17,6 средних расхождений на пиксель),
|
||||
// поэтому нижний кламп 0,80. Направление света перебрано по 120
|
||||
// направлениям — текущее лучшее.
|
||||
double brightness = Math.min(1.25, Math.max(0.80, 0.92 + 0.88 * dot));
|
||||
|
||||
List<Color> bands = spec.bandColors.isEmpty() ? palette : spec.bandColors;
|
||||
double wLo = Math.min(Math.min(pts[0][2], pts[1][2]), pts[2][2]);
|
||||
double wHi = Math.max(Math.max(pts[0][2], pts[1][2]), pts[2][2]);
|
||||
double wBase = -0.5 * hScale;
|
||||
int kLo = Math.max(0, (int) Math.floor((wLo - wBase) / wUnit));
|
||||
int kHi = Math.min(bandCount - 1, (int) Math.floor((wHi - wBase) / wUnit));
|
||||
for (int k = kLo; k <= kHi; k++) {
|
||||
double a = wBase + k * wUnit;
|
||||
double b = wBase + (k + 1) * wUnit;
|
||||
List<double[]> piece = clipW(List.of(pts[0], pts[1], pts[2]), a, b);
|
||||
if (piece.size() < 3) {
|
||||
continue;
|
||||
}
|
||||
Path2D path = new Path2D.Double();
|
||||
double depth = 0;
|
||||
for (int i = 0; i < piece.size(); i++) {
|
||||
double[] p = piece.get(i);
|
||||
Node n = project(p[0], p[1], p[2], rotX, rotY, depthScale, persp);
|
||||
if (i == 0) {
|
||||
path.moveTo(n.x() * fit.scaleX() + fit.offX(), n.y() * fit.scaleY() + fit.offY());
|
||||
} else {
|
||||
path.lineTo(n.x() * fit.scaleX() + fit.offX(), n.y() * fit.scaleY() + fit.offY());
|
||||
}
|
||||
depth += n.depth();
|
||||
}
|
||||
path.closePath();
|
||||
Color base = bands.get(k % bands.size());
|
||||
Color shaded = new Color(
|
||||
Math.min(255, (int) Math.round(base.getRed() * brightness)),
|
||||
Math.min(255, (int) Math.round(base.getGreen() * brightness)),
|
||||
Math.min(255, (int) Math.round(base.getBlue() * brightness)));
|
||||
tris.add(new Tri(path, shaded, depth / piece.size()));
|
||||
}
|
||||
}
|
||||
|
||||
/** Отсечение многоугольника полосой w в [lo, hi] (Сазерленд-Ходжман). */
|
||||
private static List<double[]> clipW(List<double[]> poly, double lo, double hi) {
|
||||
List<double[]> out = clipHalf(poly, lo, true);
|
||||
if (out.size() < 3) {
|
||||
return out;
|
||||
}
|
||||
return clipHalf(out, hi, false);
|
||||
}
|
||||
|
||||
private static List<double[]> clipHalf(List<double[]> poly, double bound, boolean keepAbove) {
|
||||
List<double[]> out = new ArrayList<>();
|
||||
for (int i = 0; i < poly.size(); i++) {
|
||||
double[] cur = poly.get(i);
|
||||
double[] nxt = poly.get((i + 1) % poly.size());
|
||||
boolean inCur = keepAbove ? cur[2] >= bound : cur[2] <= bound;
|
||||
boolean inNxt = keepAbove ? nxt[2] >= bound : nxt[2] <= bound;
|
||||
if (inCur) {
|
||||
out.add(cur);
|
||||
}
|
||||
if (inCur != inNxt && Math.abs(nxt[2] - cur[2]) > 1e-12) {
|
||||
double t = (bound - cur[2]) / (nxt[2] - cur[2]);
|
||||
out.add(new double[]{cur[0] + t * (nxt[0] - cur[0]),
|
||||
cur[1] + t * (nxt[1] - cur[1]), bound});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Сетка пола и дальней стенки; рисуется до поверхности. */
|
||||
private static void drawFloor(Graphics2D g, ChartSpec spec, Node[] floor,
|
||||
List<Node> valueAnchors, int nCat, int nSer,
|
||||
double lo, double hi, double unit, double span,
|
||||
double rotX, double rotY, double depthScale,
|
||||
double heightScale, double persp,
|
||||
Fit fit) {
|
||||
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
|
||||
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
|
||||
Color grid = valAxis.gridColor != null ? valAxis.gridColor : catAxis.gridColor;
|
||||
g.setColor(grid);
|
||||
g.setStroke(new BasicStroke(0.5f));
|
||||
double floorW = -0.5 * heightScale;
|
||||
|
||||
// контур пола
|
||||
Path2D outline = new Path2D.Double();
|
||||
for (int i = 0; i < floor.length; i++) {
|
||||
Node n = floor[i];
|
||||
if (i == 0) {
|
||||
outline.moveTo(n.x() * fit.scaleX() + fit.offX(), n.y() * fit.scaleY() + fit.offY());
|
||||
} else {
|
||||
outline.lineTo(n.x() * fit.scaleX() + fit.offX(), n.y() * fit.scaleY() + fit.offY());
|
||||
}
|
||||
}
|
||||
outline.closePath();
|
||||
g.draw(outline);
|
||||
|
||||
// линии пола по категориям (вдоль глубины) и по рядам (вдоль ширины):
|
||||
// у 3D-диаграммы пол размечен всегда, независимо от c:majorGridlines
|
||||
for (int c = 0; c < nCat; c++) {
|
||||
double u = uOf(c, nCat);
|
||||
line(g, project(u, -0.5, floorW, rotX, rotY, depthScale, persp),
|
||||
project(u, 0.5, floorW, rotX, rotY, depthScale, persp), fit);
|
||||
}
|
||||
for (int r = 0; r < nSer; r++) {
|
||||
double v = vOf(r, nSer);
|
||||
line(g, project(-0.5, v, floorW, rotX, rotY, depthScale, persp),
|
||||
project(0.5, v, floorW, rotX, rotY, depthScale, persp), fit);
|
||||
}
|
||||
// сетка значений: левая стенка (от переднего левого ребра в глубину)
|
||||
// и дальней стенка — обе рисует Word
|
||||
if (valAxis.gridlines) {
|
||||
for (double v = lo; v <= hi + unit / 2; v += unit) {
|
||||
double w = ((v - lo) / span - 0.5) * heightScale;
|
||||
line(g, project(-0.5, -0.5, w, rotX, rotY, depthScale, persp),
|
||||
project(-0.5, 0.5, w, rotX, rotY, depthScale, persp), fit);
|
||||
line(g, project(-0.5, 0.5, w, rotX, rotY, depthScale, persp),
|
||||
project(0.5, 0.5, w, rotX, rotY, depthScale, persp), fit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void line(Graphics2D g, Node a, Node b, Fit fit) {
|
||||
g.draw(new java.awt.geom.Line2D.Double(
|
||||
a.x() * fit.scaleX() + fit.offX(), a.y() * fit.scaleY() + fit.offY(),
|
||||
b.x() * fit.scaleX() + fit.offX(), b.y() * fit.scaleY() + fit.offY()));
|
||||
}
|
||||
|
||||
private static void drawLabels(Graphics2D g, ChartSpec spec, List<Node> valueAnchors,
|
||||
double lo, double hi, double unit, int nCat, int nSer,
|
||||
double rotX, double rotY, double depthScale,
|
||||
double heightScale, double persp, Fit fit) {
|
||||
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
|
||||
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
|
||||
ChartSpec.AxisSpec serAxis = spec.serAxis != null ? spec.serAxis : new ChartSpec.AxisSpec();
|
||||
double floorW = -0.5 * heightScale;
|
||||
|
||||
// Ось значений: левый край дальней стенки
|
||||
DrawMlText.Style vs = valAxis.labelStyle;
|
||||
if (vs != null) {
|
||||
double h = DrawMlText.textHeight(vs, g.getFontRenderContext()) + 2;
|
||||
int i = 0;
|
||||
for (double v = lo; v <= hi + unit / 2; v += unit) {
|
||||
if (i >= valueAnchors.size()) {
|
||||
break;
|
||||
}
|
||||
Node n = valueAnchors.get(i++);
|
||||
double x = n.x() * fit.scaleX() + fit.offX();
|
||||
double y = n.y() * fit.scaleY() + fit.offY();
|
||||
String label = ChartRenderer.formatValue(v, valAxis.numFmt);
|
||||
double w = DrawMlText.textWidth(label, vs, g.getFontRenderContext());
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, vs, "r")),
|
||||
new Rectangle2D.Double(x - w - 4, y - h / 2, w, h), "r", "ctr", 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Категории: переднее нижнее ребро пола
|
||||
DrawMlText.Style cs = catAxis.labelStyle;
|
||||
if (cs != null) {
|
||||
double h = DrawMlText.textHeight(cs, g.getFontRenderContext()) + 2;
|
||||
for (int c = 0; c < nCat; c++) {
|
||||
String label = c < spec.categories.size() ? spec.categories.get(c) : "";
|
||||
if (label.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Node n = project(uOf(c, nCat), -0.5, floorW, rotX, rotY, depthScale, persp);
|
||||
double x = n.x() * fit.scaleX() + fit.offX();
|
||||
// в Word подписи категорий опущены на 15,1 pt ниже линии пола
|
||||
// (замер по эталону word-export.pdf, 300 dpi: центры подписей 669/714/
|
||||
// 764/820 px при линии пола 606/651/700/757 px)
|
||||
double y = n.y() * fit.scaleY() + fit.offY() + 8;
|
||||
double w = DrawMlText.textWidth(label, cs, g.getFontRenderContext());
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, cs, "ctr")),
|
||||
new Rectangle2D.Double(x - w / 2, y, w, h), "ctr", "t", 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Ряды: правое нижнее ребро пола
|
||||
DrawMlText.Style ss = serAxis.labelStyle;
|
||||
if (ss != null) {
|
||||
double h = DrawMlText.textHeight(ss, g.getFontRenderContext()) + 2;
|
||||
for (int r = 0; r < nSer; r++) {
|
||||
String label = spec.series.get(r).name;
|
||||
if (label == null || label.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Node n = project(0.5, vOf(r, nSer), floorW, rotX, rotY, depthScale, persp);
|
||||
double x = n.x() * fit.scaleX() + fit.offX() + 4;
|
||||
double y = n.y() * fit.scaleY() + fit.offY();
|
||||
double w = DrawMlText.textWidth(label, ss, g.getFontRenderContext());
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, ss, "l")),
|
||||
new Rectangle2D.Double(x, y - h / 2, w, h), "l", "ctr", 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проекция модельной точки. u — категория, v — ряд (умножается на
|
||||
* c:view3D/depth), w — значение; все в [-0.5, 0.5]. Возвращает
|
||||
* экранные координаты в модельном масштабе и глубину (больше = дальше).
|
||||
*/
|
||||
static Node project(double u, double v, double w, double rotX, double rotY,
|
||||
double depthScale, double perspective) {
|
||||
double vd = v * depthScale;
|
||||
double ca = Math.cos(rotY);
|
||||
double sa = Math.sin(rotY);
|
||||
double x1 = u * ca - vd * sa;
|
||||
double y1 = u * sa + vd * ca;
|
||||
double cb = Math.cos(rotX);
|
||||
double sb = Math.sin(rotX);
|
||||
double depth = y1 * cb - w * sb;
|
||||
double height = y1 * sb + w * cb;
|
||||
double k = 1.0;
|
||||
if (perspective > 0.01) {
|
||||
double d = CAMERA_DISTANCE * (30.0 / Math.max(1.0, perspective));
|
||||
k = d / Math.max(0.05, d + depth);
|
||||
}
|
||||
return new Node(x1 * k, -height * k, depth);
|
||||
}
|
||||
|
||||
private static double uOf(int c, int nCat) {
|
||||
return nCat > 1 ? (double) c / (nCat - 1) - 0.5 : 0;
|
||||
}
|
||||
|
||||
private static double vOf(int r, int nSer) {
|
||||
return nSer > 1 ? (double) r / (nSer - 1) - 0.5 : 0;
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,38 @@ class WordPdfConverterTest {
|
||||
return names;
|
||||
}
|
||||
|
||||
/** Количество Image XObject на всех страницах PDF. */
|
||||
private static int imageCount(Path pdf) throws IOException {
|
||||
int count = 0;
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources res = page.getResources();
|
||||
for (COSName name : res.getXObjectNames()) {
|
||||
if (res.isImageXObject(name)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Диаграммы (c:chart) и SmartArt (dgm:relIds) до экспорта в FO
|
||||
* рендерятся в PNG: без этого docx2fo.xslt выбрасывает весь w:drawing
|
||||
* как notImplemented, и в PDF не остаётся ни одной картинки.
|
||||
*/
|
||||
@Test
|
||||
void chartsSmartArt_drawingsBecomeImages() throws Exception {
|
||||
Path in = extractSample("charts-smartart.docx");
|
||||
Path pdf = convert(in);
|
||||
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("Диаграммы"), "пропал текст вокруг диаграмм: " + text);
|
||||
assertTrue(imageCount(pdf) >= 4,
|
||||
"ожидались 4 растра (SmartArt + 3 графика), найдено: " + imageCount(pdf));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruPlain_cyrillicAndStyles() throws Exception {
|
||||
Path in = extractSample("ru-plain.docx");
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import org.docx4j.dml.chart.CTBoolean;
|
||||
import org.docx4j.dml.chart.CTChart;
|
||||
import org.docx4j.dml.chart.CTTitle;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Пустой c:title при autoTitleDeleted=0 — это автозаголовок Word, которого
|
||||
* нет в XML: для круговых диаграмм он равен имени ряда, для остальных
|
||||
* типов это встроенный плейсхолдер.
|
||||
*/
|
||||
class ChartSpecTest {
|
||||
|
||||
@Test
|
||||
void emptyTitleFallsBackToAutoTitle() {
|
||||
ChartSpec spec = new ChartSpec();
|
||||
spec.type = ChartSpec.Type.SURFACE3D;
|
||||
ChartSpec.readTitle(emptyTitleChart(), spec, new DrawMlColor(null));
|
||||
assertEquals(ChartSpec.AUTO_TITLE, spec.title);
|
||||
assertNotNull(spec.titleStyle, "у автозаголовка должно быть начертание из c:txPr");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyTitleOfCircularChartUsesSeriesName() {
|
||||
ChartSpec spec = new ChartSpec();
|
||||
spec.type = ChartSpec.Type.PIE3D;
|
||||
ChartSpec.Series s = new ChartSpec.Series();
|
||||
s.name = "Продажи";
|
||||
spec.series.add(s);
|
||||
ChartSpec.readTitle(emptyTitleChart(), spec, new DrawMlColor(null));
|
||||
assertEquals("Продажи", spec.title);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedAutoTitleLeavesChartWithoutTitle() {
|
||||
ChartSpec spec = new ChartSpec();
|
||||
spec.type = ChartSpec.Type.LINE;
|
||||
CTChart chart = emptyTitleChart();
|
||||
CTBoolean deleted = new CTBoolean();
|
||||
deleted.setVal(Boolean.TRUE);
|
||||
chart.setAutoTitleDeleted(deleted);
|
||||
ChartSpec.readTitle(chart, spec, new DrawMlColor(null));
|
||||
assertNull(spec.title);
|
||||
}
|
||||
|
||||
private static CTChart emptyTitleChart() {
|
||||
CTChart chart = new CTChart();
|
||||
chart.setTitle(new CTTitle());
|
||||
CTBoolean keep = new CTBoolean();
|
||||
keep.setVal(Boolean.FALSE);
|
||||
chart.setAutoTitleDeleted(keep);
|
||||
return chart;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Геометрия pie3D: наклон «торта», глубина экструзии и видимость торцов.
|
||||
* Цели замерены по эталону Word — стр. 3 `word-export.pdf` (300 dpi), область
|
||||
* графика 219,23×149,08 pt (wp:extent 2784231×1893277 EMU).
|
||||
*/
|
||||
class PiePainterTest {
|
||||
|
||||
/**
|
||||
* Форма торта (не масштаб — он зависит от заголовка и легенды): в эталоне
|
||||
* Word силуэт 540×316 px, т.е. h/w = 0,585 при ry/rx = 0,475 и глубине
|
||||
* 0,22 от радиуса. До калибровки торт был на 8% выше эталона.
|
||||
*/
|
||||
@Test
|
||||
void pie3dSilhouetteMatchesWordReference() {
|
||||
DrawMlColor colors = new DrawMlColor(null);
|
||||
BufferedImage img = ChartRenderer.render(pie3dSpec(), 219.23, 149.08, colors);
|
||||
|
||||
int minX = Integer.MAX_VALUE;
|
||||
int maxX = -1;
|
||||
int minY = Integer.MAX_VALUE;
|
||||
int maxY = -1;
|
||||
int painted = 0;
|
||||
for (int y = 0; y < img.getHeight() * 0.82; y++) {
|
||||
for (int x = 0; x < img.getWidth(); x++) {
|
||||
int rgb = img.getRGB(x, y);
|
||||
int r = (rgb >> 16) & 0xFF;
|
||||
int g = (rgb >> 8) & 0xFF;
|
||||
int b = rgb & 0xFF;
|
||||
if (Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) <= 25) {
|
||||
continue;
|
||||
}
|
||||
painted++;
|
||||
minX = Math.min(minX, x);
|
||||
maxX = Math.max(maxX, x);
|
||||
minY = Math.min(minY, y);
|
||||
maxY = Math.max(maxY, y);
|
||||
}
|
||||
}
|
||||
assertTrue(painted > 60000, "слишком мало залитого торта: " + painted);
|
||||
assertRatio("аспект силуэта pie3D (h/w)", (maxY - minY) / (double) (maxX - minX), 0.585);
|
||||
}
|
||||
|
||||
/**
|
||||
* Торец общей границы двух соседних секторов должен быть один: у сектора,
|
||||
* чья грань отвернута от камеры, он не рисуется, иначе торец дальнего
|
||||
* сектора выползает наружу (в word-export.pdf на границе «Кв. 1»/«Кв. 2» видна
|
||||
* тёмно-синяя грань, а не оранжевая).
|
||||
*/
|
||||
@Test
|
||||
void pie3dSharedEdgeShowsOnlyCameraFacingEnd() {
|
||||
DrawMlColor colors = new DrawMlColor(null);
|
||||
BufferedImage img = ChartRenderer.render(pie3dSpec(), 219.23, 149.08, colors);
|
||||
int blue = 0;
|
||||
int orange = 0;
|
||||
for (int y = 0; y < img.getHeight(); y++) {
|
||||
for (int x = 0; x < img.getWidth(); x++) {
|
||||
int rgb = img.getRGB(x, y);
|
||||
int r = (rgb >> 16) & 0xFF;
|
||||
int g = (rgb >> 8) & 0xFF;
|
||||
int b = rgb & 0xFF;
|
||||
// тёмно-синий торец: accent1, затемнённый до 0,55..0,85
|
||||
if (b > r + 40 && b > 90 && b < 180 && r < 90) {
|
||||
blue++;
|
||||
}
|
||||
// тёмно-оранжевый торец: accent2, затемнённый до 0,55..0,85
|
||||
if (r > g + 40 && g > b + 20 && r > 120 && r < 210) {
|
||||
orange++;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(blue > orange,
|
||||
"на границе секторов должен быть виден торец переднего (синего) сектора: "
|
||||
+ "синего " + blue + " px, оранжевого " + orange + " px");
|
||||
}
|
||||
|
||||
private static ChartSpec pie3dSpec() {
|
||||
ChartSpec spec = new ChartSpec();
|
||||
spec.type = ChartSpec.Type.PIE3D;
|
||||
spec.title = "Продажи";
|
||||
spec.legendPos = "b";
|
||||
ChartSpec.Series s = new ChartSpec.Series();
|
||||
s.name = "Продажи";
|
||||
for (double v : new double[]{8.2, 3.2, 1.4, 1.2}) {
|
||||
s.values.add(v);
|
||||
}
|
||||
s.categories.addAll(List.of("Кв. 1", "Кв. 2", "Кв. 3", "Кв. 4"));
|
||||
spec.series.add(s);
|
||||
return spec;
|
||||
}
|
||||
|
||||
private static void assertRatio(String what, double actual, double expected) {
|
||||
double deviation = Math.abs(actual - expected) / Math.abs(expected);
|
||||
assertTrue(deviation < 0.06,
|
||||
what + ": получено " + String.format("%.0f", actual)
|
||||
+ " px, в эталоне Word " + String.format("%.0f", expected)
|
||||
+ " px (отклонение " + String.format("%.1f", deviation * 100) + "%)");
|
||||
}
|
||||
}
|
||||
+440
@@ -0,0 +1,440 @@
|
||||
package ru.pjandro.wordpdf.internal.chart;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Геометрия surface3D: перспектива, нулевая база оси значений и сам факт,
|
||||
* что грани заливаются (а не рисуются в субпиксельный ноль).
|
||||
*/
|
||||
class Surface3dPainterTest {
|
||||
|
||||
@Test
|
||||
void project_perspectiveMakesFrontEdgeWider() {
|
||||
double rotX = Math.toRadians(15);
|
||||
Surface3dPainter.Node front = Surface3dPainter.project(0.5, -0.5, 0, rotX, 0, 1.0, 30);
|
||||
Surface3dPainter.Node back = Surface3dPainter.project(0.5, 0.5, 0, rotX, 0, 1.0, 30);
|
||||
assertTrue(front.depth() < back.depth(),
|
||||
"передний план должен быть ближе: " + front.depth() + " vs " + back.depth());
|
||||
assertTrue(Math.abs(front.x()) > Math.abs(back.x()) * 1.05,
|
||||
"перспектива не расширяет передний план: " + front.x() + " vs " + back.x());
|
||||
|
||||
Surface3dPainter.Node flatFront = Surface3dPainter.project(0.5, -0.5, 0, rotX, 0, 1.0, 0);
|
||||
Surface3dPainter.Node flatBack = Surface3dPainter.project(0.5, 0.5, 0, rotX, 0, 1.0, 0);
|
||||
assertEquals(flatFront.x(), flatBack.x(), 1e-9,
|
||||
"без перспективы масштаб не должен различаться");
|
||||
}
|
||||
|
||||
@Test
|
||||
void axisBounds_linearValueAxisIncludesZero() {
|
||||
double[] b = ChartRenderer.axisBounds(new ChartSpec.AxisSpec(), 1.8, 5);
|
||||
assertEquals(0, b[0], 1e-9, "ось значений должна начинаться с нуля (как в Word)");
|
||||
assertEquals(5, b[1], 1e-9);
|
||||
assertEquals(1, b[2], 1e-9);
|
||||
|
||||
double[] negative = ChartRenderer.axisBounds(new ChartSpec.AxisSpec(), -5, -1.2);
|
||||
assertTrue(negative[0] < 0 && negative[1] < 0,
|
||||
"отрицательные данные не должны тянуть ось к нулю: "
|
||||
+ negative[0] + ".." + negative[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void paint_drawsShadedFacets() {
|
||||
ChartSpec spec = surfaceSpec();
|
||||
|
||||
DrawMlColor colors = new DrawMlColor(null);
|
||||
BufferedImage img = new BufferedImage(700, 400, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
try {
|
||||
Surface3dPainter.paint(g, spec,
|
||||
new Rectangle2D.Double(10, 10, 680, 380), ChartSpec.palette(colors));
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
Set<Integer> distinct = new HashSet<>();
|
||||
int painted = 0;
|
||||
for (int y = 0; y < img.getHeight(); y++) {
|
||||
for (int x = 0; x < img.getWidth(); x++) {
|
||||
int argb = img.getRGB(x, y);
|
||||
if (((argb >>> 24) & 0xFF) < 200) {
|
||||
continue;
|
||||
}
|
||||
Color c = new Color(argb);
|
||||
if (c.getRed() > 245 && c.getGreen() > 245 && c.getBlue() > 245) {
|
||||
continue;
|
||||
}
|
||||
painted++;
|
||||
distinct.add(c.getRGB());
|
||||
}
|
||||
}
|
||||
assertTrue(painted > 3000,
|
||||
"грани почти не залиты (похоже, геометрия ушла за пределы холста): " + painted);
|
||||
assertTrue(distinct.size() >= 6,
|
||||
"ождались разные оттенки граней (затемнение по нормали), найдено цветов: "
|
||||
+ distinct.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Калибровка камеры и «коробки» по эталону Word: стр. 3 `word-export.pdf`
|
||||
* (экспорт Word), растеризованная в 300 dpi. Цели — безразмерные
|
||||
* отношения, замеренные по подписям осей и по силуэту поверхности
|
||||
* (пиксели граней, 1897×962 px области графика 448,15×230,31 pt):
|
||||
* уклон передней кромки пола 0,1282 (подписи «Категория 1…4»:
|
||||
* x 311/658/1048/1489, y 669/714/764/820), аспект силуэта поверхности
|
||||
* 0,207 (1312×272 px — силуэт по связным областям граней, серые грани
|
||||
* входят в него), шаг оси значений 0,0504 (66 px на деление,
|
||||
* подписи 5…0 по переднему левому ребру) и шаг оси рядов 0,1176
|
||||
* (154 px между «Ряд 1» и «Ряд 2»). Все четыре — относительно
|
||||
* ширины силуэта, поэтому не зависят от размера области построения.
|
||||
*/
|
||||
@Test
|
||||
void cameraMatchesWordReference() {
|
||||
double rotX = Math.toRadians(15);
|
||||
double rotY = -Math.toRadians(20);
|
||||
double ds = Surface3dPainter.DEPTH_RATIO;
|
||||
// аспект области построения эталонного графика: box за вычетом
|
||||
// заголовка (~21 pt) и легенды (~14,5 pt) и полей painter'а
|
||||
double boxW = 448.15385826771654 - 8;
|
||||
double boxH = 230.30771653543306 - 8 - 21 - 14.5;
|
||||
double availW = boxW * (1 - Surface3dPainter.GUTTER_LEFT - Surface3dPainter.GUTTER_RIGHT);
|
||||
double availH = boxH * (1 - Surface3dPainter.GUTTER_TOP - Surface3dPainter.GUTTER_BOTTOM);
|
||||
double hs = Surface3dPainter.HEIGHT_RATIO * availH / availW;
|
||||
double[][] z = {{4.3, 2.5, 3.5, 4.5}, {2.4, 4.4, 1.8, 2.8}, {2.0, 2.0, 3.0, 5.0}};
|
||||
|
||||
double minX = Double.MAX_VALUE;
|
||||
double maxX = -Double.MAX_VALUE;
|
||||
double minY = Double.MAX_VALUE;
|
||||
double maxY = -Double.MAX_VALUE;
|
||||
for (int r = 0; r < 3; r++) {
|
||||
for (int c = 0; c < 4; c++) {
|
||||
Surface3dPainter.Node n = Surface3dPainter.project(
|
||||
c / 3.0 - 0.5, r / 2.0 - 0.5,
|
||||
(z[r][c] / 5.0 - 0.5) * hs, rotX, rotY, ds, 30);
|
||||
minX = Math.min(minX, n.x());
|
||||
maxX = Math.max(maxX, n.x());
|
||||
minY = Math.min(minY, n.y());
|
||||
maxY = Math.max(maxY, n.y());
|
||||
}
|
||||
}
|
||||
double width = maxX - minX;
|
||||
|
||||
Surface3dPainter.Node k1 = Surface3dPainter.project(-0.5, -0.5, -hs / 2, rotX, rotY, ds, 30);
|
||||
Surface3dPainter.Node k4 = Surface3dPainter.project(0.5, -0.5, -hs / 2, rotX, rotY, ds, 30);
|
||||
Surface3dPainter.Node v0 = Surface3dPainter.project(-0.5, -0.5, -hs / 2, rotX, rotY, ds, 30);
|
||||
Surface3dPainter.Node v1 = Surface3dPainter.project(-0.5, -0.5, -hs / 2 + hs / 5, rotX, rotY, ds, 30);
|
||||
Surface3dPainter.Node r0 = Surface3dPainter.project(0.5, -0.5, -hs / 2, rotX, rotY, ds, 30);
|
||||
Surface3dPainter.Node r1 = Surface3dPainter.project(0.5, 0.0, -hs / 2, rotX, rotY, ds, 30);
|
||||
|
||||
assertRatio("уклон передней кромки пола", (k4.y() - k1.y()) / (k4.x() - k1.x()), 0.1282);
|
||||
assertRatio("аспект силуэта поверхности", (maxY - minY) / width, 0.207);
|
||||
assertRatio("шаг оси значений", (v1.y() - v0.y()) / width, -0.0504);
|
||||
assertRatio("шаг оси рядов", (r1.y() - r0.y()) / width, -0.1176);
|
||||
}
|
||||
|
||||
/**
|
||||
* Размер и место самой поверхности в области графика: в эталоне Word
|
||||
* (стр. 3 word-export.pdf, 300 dpi, область 448,15×230,31 pt) связный блок
|
||||
* граней занимает x 291…1603 px и y 207…479 px, т.е. 314,9×65,3 pt
|
||||
* с центром в (227,3; 82,3) pt. Раньше коробка вписывалась в область
|
||||
* построения целиком (82% ширины) и поверхность наползала на подписи
|
||||
* оси значений.
|
||||
*/
|
||||
@Test
|
||||
void surfaceSilhouetteMatchesWordPlacement() {
|
||||
ChartSpec spec = surfaceSpec();
|
||||
DrawMlColor colors = new DrawMlColor(null);
|
||||
double widthPt = 448.15385826771654;
|
||||
double heightPt = 230.30771653543306;
|
||||
BufferedImage img = new BufferedImage(
|
||||
(int) Math.round(widthPt * 300 / 72.0),
|
||||
(int) Math.round(heightPt * 300 / 72.0), BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
try {
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, img.getWidth(), img.getHeight());
|
||||
g.scale(300 / 72.0, 300 / 72.0);
|
||||
Surface3dPainter.paint(g, spec,
|
||||
new Rectangle2D.Double(4, 25, widthPt - 8, heightPt - 8 - 21 - 14.5),
|
||||
ChartSpec.palette(colors));
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
double minX = Double.MAX_VALUE;
|
||||
double maxX = -Double.MAX_VALUE;
|
||||
double minY = Double.MAX_VALUE;
|
||||
double maxY = -Double.MAX_VALUE;
|
||||
int painted = 0;
|
||||
boolean[][] facet = facetMask(img);
|
||||
for (int y = 0; y < img.getHeight(); y++) {
|
||||
for (int x = 0; x < img.getWidth(); x++) {
|
||||
if (!facet[y][x]) {
|
||||
continue;
|
||||
}
|
||||
painted++;
|
||||
double px = x * 72.0 / 300;
|
||||
double py = y * 72.0 / 300;
|
||||
minX = Math.min(minX, px);
|
||||
maxX = Math.max(maxX, px);
|
||||
minY = Math.min(minY, py);
|
||||
maxY = Math.max(maxY, py);
|
||||
}
|
||||
}
|
||||
assertTrue(painted > 60000, "слишком мало граней: " + painted);
|
||||
// Word: силуэт 314,9×65,3 pt с центром в (227,3; 82,3) области 448×230 pt
|
||||
assertRatio("ширина силуэта поверхности", maxX - minX, 314.9);
|
||||
assertRatio("высота силуэта поверхности", maxY - minY, 65.3);
|
||||
assertRange("центр силуэта по X", (minX + maxX) / 2, 227.3, 6);
|
||||
assertRange("центр силуэта по Y", (minY + maxY) / 2, 82.3, 6);
|
||||
}
|
||||
|
||||
/**
|
||||
* Седловая ячейка «Ряд 1 → Ряд 2, Категория 2 → Категория 3»
|
||||
* (значения 2,5 и 4,4 спереди, 3,5 и 1,8 сзади) в проекции вогнутая:
|
||||
* один из её углов попадает внутрь треугольника остальных трёх, и то,
|
||||
* какой диагональю разрезан квад, меняют полосу видимой грани.
|
||||
* В эталоне Word (стр. 3 `word-export.pdf`, 300 dpi) нижняя кромка силуэта на
|
||||
* протяжении 0,40…0,59 его ширины — жёлтая, полоса 3–4 (accent4),
|
||||
* а не серая 2–3: Word берёт верхнюю огибающую седла, то есть диагональ
|
||||
* w01–w10. С фиксированной w00–w11 там выходит серая полоса 2–3.
|
||||
*/
|
||||
@Test
|
||||
void saddleCellUsesHigherDiagonal() {
|
||||
ChartSpec spec = surfaceSpec();
|
||||
List<Color> palette = ChartSpec.palette(new DrawMlColor(null));
|
||||
BufferedImage img = new BufferedImage(700, 400, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
try {
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, img.getWidth(), img.getHeight());
|
||||
Surface3dPainter.paint(g, spec,
|
||||
new Rectangle2D.Double(10, 10, 680, 380), palette);
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
boolean[][] facet = facetMask(img);
|
||||
int minX = img.getWidth();
|
||||
int maxX = -1;
|
||||
int minY = img.getHeight();
|
||||
int maxY = -1;
|
||||
for (int y = 0; y < img.getHeight(); y++) {
|
||||
for (int x = 0; x < img.getWidth(); x++) {
|
||||
if (!facet[y][x]) {
|
||||
continue;
|
||||
}
|
||||
minX = Math.min(minX, x);
|
||||
maxX = Math.max(maxX, x);
|
||||
minY = Math.min(minY, y);
|
||||
maxY = Math.max(maxY, y);
|
||||
}
|
||||
}
|
||||
assertTrue(maxX > minX && maxY > minY, "силуэт поверхности не найден");
|
||||
double width = maxX - minX;
|
||||
|
||||
int checked = 0;
|
||||
int yellow = 0;
|
||||
StringBuilder seen = new StringBuilder();
|
||||
for (int x = (int) Math.ceil(minX + 0.42 * width); x <= minX + 0.55 * width; x++) {
|
||||
for (int y = maxY; y >= minY; y--) {
|
||||
if (!facet[y][x]) {
|
||||
continue;
|
||||
}
|
||||
checked++;
|
||||
int band = bandOf(new Color(img.getRGB(x, y)), palette);
|
||||
if (band == 3) {
|
||||
yellow++;
|
||||
} else if (seen.length() < 40) {
|
||||
seen.append("x=").append(x).append(" полоса ").append(band).append("; ");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(checked > 40, "окно по нижней кромке силуэта почти пустое: " + checked);
|
||||
assertEquals(checked, yellow,
|
||||
"передняя грань седловой ячейки должна быть полосы 3–4 (Word), "
|
||||
+ "а не 2–3; первые расхождения: " + seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Полоса цвета с произвольным затемнением: грань Word красит цветом
|
||||
* полосы и умножает его на 0,8…1,25, поэтому искать ближайший цвет
|
||||
* палитры «как есть» — значит не найти ничего (жёлтый 0,8 — уже не
|
||||
* похож на accent4).
|
||||
*/
|
||||
private static int bandOf(Color c, List<Color> palette) {
|
||||
int best = -1;
|
||||
double bestDist = Double.MAX_VALUE;
|
||||
for (int i = 0; i < Math.min(5, palette.size()); i++) {
|
||||
Color b = palette.get(i);
|
||||
for (int f = 60; f <= 135; f++) {
|
||||
double k = f / 100.0;
|
||||
double d = Math.pow(c.getRed() - b.getRed() * k, 2)
|
||||
+ Math.pow(c.getGreen() - b.getGreen() * k, 2)
|
||||
+ Math.pow(c.getBlue() - b.getBlue() * k, 2);
|
||||
if (d < bestDist) {
|
||||
bestDist = d;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return bestDist < 3600 ? best : -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Пиксели граней поверхности: не белые и не тонкие (сетка, подписи и
|
||||
* рамки осей — линии толщиной в несколько пикселей, грань — пятно).
|
||||
* Серые грани по цвету близки к фону, поэтому «насыщенность» их не
|
||||
* ловит: нужен признак «крупное связное пятно».
|
||||
*/
|
||||
private static boolean[][] facetMask(BufferedImage img) {
|
||||
int w = img.getWidth();
|
||||
int h = img.getHeight();
|
||||
boolean[][] nonWhite = new boolean[h][w];
|
||||
for (int y = 0; y < h; y++) {
|
||||
for (int x = 0; x < w; x++) {
|
||||
Color c = new Color(img.getRGB(x, y));
|
||||
nonWhite[y][x] = Math.min(c.getRed(), Math.min(c.getGreen(), c.getBlue())) < 205;
|
||||
}
|
||||
}
|
||||
boolean[][] out = new boolean[h][w];
|
||||
for (int y = 4; y + 4 < h; y++) {
|
||||
for (int x = 4; x + 4 < w; x++) {
|
||||
int cnt = 0;
|
||||
for (int dy = -4; dy <= 4 && cnt < 45; dy++) {
|
||||
for (int dx = -4; dx <= 4; dx++) {
|
||||
if (nonWhite[y + dy][x + dx]) {
|
||||
cnt++;
|
||||
}
|
||||
}
|
||||
}
|
||||
out[y][x] = cnt >= 45 && nonWhite[y][x];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void assertRange(String what, double actual, double expected, double tolPt) {
|
||||
assertTrue(Math.abs(actual - expected) <= tolPt,
|
||||
what + ": получено " + String.format("%.1f", actual)
|
||||
+ " pt, в эталоне Word " + String.format("%.1f", expected) + " pt");
|
||||
}
|
||||
|
||||
/**
|
||||
* Затенение граней: множители яркости грани относительно цвета полосы
|
||||
* в эталоне Word (стр. 3 `word-export.pdf`, 300 dpi, гистограмма цветов граней)
|
||||
* — 0,40 / 0,75 / 0,85 / 1,04 / 1,06 / 1,10, причём 0,40 — это малая
|
||||
* зона (тонкая полоска под передним краем ленты). Свободный Lambert
|
||||
* с отрицательными dot даёт слишком много тёмных граней и хуже
|
||||
* сходится с эталоном, поэтому нижняя граница множителя — 0,80.
|
||||
*/
|
||||
@Test
|
||||
void shadingMatchesWordRange() {
|
||||
ChartSpec spec = surfaceSpec();
|
||||
DrawMlColor colors = new DrawMlColor(null);
|
||||
List<Color> palette = ChartSpec.palette(colors);
|
||||
BufferedImage img = new BufferedImage(700, 400, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
try {
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, img.getWidth(), img.getHeight());
|
||||
Surface3dPainter.paint(g, spec,
|
||||
new Rectangle2D.Double(10, 10, 680, 380), palette);
|
||||
} finally {
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
List<Double> ratios = new ArrayList<>();
|
||||
for (int y = 0; y < img.getHeight(); y++) {
|
||||
for (int x = 0; x < img.getWidth(); x++) {
|
||||
Color c = new Color(img.getRGB(x, y));
|
||||
if (c.getRed() > 245 && c.getGreen() > 245 && c.getBlue() > 245) {
|
||||
continue;
|
||||
}
|
||||
Color base = nearestBand(c, palette);
|
||||
if (base == null) {
|
||||
continue;
|
||||
}
|
||||
double lum = 0.299 * c.getRed() + 0.587 * c.getGreen() + 0.114 * c.getBlue();
|
||||
double baseLum = 0.299 * base.getRed() + 0.587 * base.getGreen()
|
||||
+ 0.114 * base.getBlue();
|
||||
ratios.add(lum / baseLum);
|
||||
}
|
||||
}
|
||||
assertTrue(ratios.size() > 3000, "слишком мало залитых граней: " + ratios.size());
|
||||
Collections.sort(ratios);
|
||||
double p5 = ratios.get((int) (ratios.size() * 0.05));
|
||||
double median = ratios.get(ratios.size() / 2);
|
||||
double p95 = ratios.get((int) (ratios.size() * 0.95));
|
||||
assertTrue(p5 >= 0.74 && p5 <= 0.90,
|
||||
"тёмные грани вне эталонного диапазона (0,75..0,85): p5=" + p5);
|
||||
assertTrue(median >= 0.90 && median <= 1.10,
|
||||
"медианная яркость граней вне эталонной (1,04): median=" + median);
|
||||
assertTrue(p95 >= 1.02 && p95 <= 1.20,
|
||||
"светлые грани вне эталонного диапазона (1,06..1,10): p95=" + p95);
|
||||
}
|
||||
|
||||
private static Color nearestBand(Color c, List<Color> palette) {
|
||||
Color best = null;
|
||||
double bestDist = Double.MAX_VALUE;
|
||||
for (int i = 0; i < Math.min(5, palette.size()); i++) {
|
||||
Color b = palette.get(i);
|
||||
double d = Math.pow(c.getRed() - b.getRed(), 2)
|
||||
+ Math.pow(c.getGreen() - b.getGreen(), 2)
|
||||
+ Math.pow(c.getBlue() - b.getBlue(), 2);
|
||||
if (d < bestDist) {
|
||||
bestDist = d;
|
||||
best = b;
|
||||
}
|
||||
}
|
||||
return bestDist < 3600 ? best : null;
|
||||
}
|
||||
|
||||
private static ChartSpec surfaceSpec() {
|
||||
ChartSpec spec = new ChartSpec();
|
||||
spec.type = ChartSpec.Type.SURFACE3D;
|
||||
spec.rotX = 15;
|
||||
spec.rotY = 20;
|
||||
spec.perspective = 30;
|
||||
spec.depthPercent = 100;
|
||||
addSeries(spec, "Ряд 1", 4.3, 2.5, 3.5, 4.5);
|
||||
addSeries(spec, "Ряд 2", 2.4, 4.4, 1.8, 2.8);
|
||||
addSeries(spec, "Ряд 3", 2.0, 2.0, 3.0, 5.0);
|
||||
spec.categories.addAll(List.of(
|
||||
"Категория 1", "Категория 2", "Категория 3", "Категория 4"));
|
||||
spec.valAxis = new ChartSpec.AxisSpec();
|
||||
spec.valAxis.gridlines = true;
|
||||
spec.catAxis = new ChartSpec.AxisSpec();
|
||||
spec.catAxis.gridlines = true;
|
||||
spec.serAxis = new ChartSpec.AxisSpec();
|
||||
spec.serAxis.gridlines = true;
|
||||
return spec;
|
||||
}
|
||||
|
||||
private static void assertRatio(String what, double actual, double expected) {
|
||||
double deviation = Math.abs(actual - expected) / Math.abs(expected);
|
||||
assertTrue(deviation < 0.10,
|
||||
what + ": получено " + String.format("%.4f", actual)
|
||||
+ ", в эталоне Word " + String.format("%.4f", expected)
|
||||
+ " (отклонение " + String.format("%.1f", deviation * 100) + "%)");
|
||||
}
|
||||
|
||||
private static void addSeries(ChartSpec spec, String name, double... values) {
|
||||
ChartSpec.Series s = new ChartSpec.Series();
|
||||
s.name = name;
|
||||
for (double v : values) {
|
||||
s.values.add(v);
|
||||
}
|
||||
spec.series.add(s);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Reference in New Issue
Block a user