Собственный рендер OMML→PNG, полный FOP-конфиг шрифтов, удаление JEuclid #113
@@ -26,7 +26,16 @@ import ru.pjandro.wordpdf.fonts.BundledFonts;
|
|||||||
* рендерится шрифтом просмотрщика либо .notdef («#»). Поэтому в конфиг
|
* рендерится шрифтом просмотрщика либо .notdef («#»). Поэтому в конфиг
|
||||||
* добавляются ВСЕ шрифты бандла: стоит они в документе или нет, решает FO.
|
* добавляются ВСЕ шрифты бандла: стоит они в документе или нет, решает FO.
|
||||||
*
|
*
|
||||||
* Метод идемпотентен: уже задекларированное семейство не дублируется.
|
* Конфиг обязан быть полным при каждом {@code declare}: общая FopFactory
|
||||||
|
* ({@code WordPdfConverter.sharedFopFactory}) строится из fopconf первого
|
||||||
|
* документа JVM, а docx4j декларирует из {@code fontsInUse} только
|
||||||
|
* использованные начертания — {@code declareFamily} дополняет семейство
|
||||||
|
* недостающими реальными начертаниями, а не пропускает его целиком.
|
||||||
|
* Идемпотентность: начертание, уже имеющее в конфиге запись на реальном
|
||||||
|
* TTF, не дублируется.
|
||||||
|
*
|
||||||
|
* <p>Регрессия — FopFallbackFontsTest#declareWhenDocx4jDeclaredRegularOnly_addsMissingVariants,
|
||||||
|
* WordPdfConverterTest#fopFactoryFrozenFromFirstDoc_fontsComplete.
|
||||||
*/
|
*/
|
||||||
public final class FopFallbackFonts {
|
public final class FopFallbackFonts {
|
||||||
|
|
||||||
@@ -49,7 +58,15 @@ public final class FopFallbackFonts {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Одно семейство: regular + существующие начертания (Noto — только regular). */
|
/**
|
||||||
|
* Одно семейство: каждое начертание, для которого в конфиге нет
|
||||||
|
* записи с реальным TTF этого начертания (Noto — только regular,
|
||||||
|
* отсутствующие варианты пропускаются). Family-level «уже есть —
|
||||||
|
* пропускаем всё» запрещён: docx4j декларирует только использованные
|
||||||
|
* начертания (или simulate-style на одном файле), а общая FopFactory
|
||||||
|
* замораживает конфиг первого документа на всю JVM — пропущенное
|
||||||
|
* семейство остаётся неполным для всех последующих конвертаций.
|
||||||
|
*/
|
||||||
private static void declareFamily(Fonts rendererFonts, ObjectFactory factory,
|
private static void declareFamily(Fonts rendererFonts, ObjectFactory factory,
|
||||||
String family) {
|
String family) {
|
||||||
PhysicalFont regular = BundledFonts.regular(family);
|
PhysicalFont regular = BundledFonts.regular(family);
|
||||||
@@ -61,21 +78,43 @@ public final class FopFallbackFonts {
|
|||||||
// и под это же имя декларируются все начертания (так делает
|
// и под это же имя декларируются все начертания (так делает
|
||||||
// docx4j FopConfigUtil.createVariant).
|
// docx4j FopConfigUtil.createVariant).
|
||||||
String familyName = regular.getName();
|
String familyName = regular.getName();
|
||||||
for (Fonts.Font existing : rendererFonts.getFont()) {
|
String[][] variants = {
|
||||||
for (Fonts.Font.FontTriplet triplet : existing.getFontTriplet()) {
|
{BundledFonts.V_REGULAR, "normal", "normal"},
|
||||||
if (familyName.equals(triplet.getName())) {
|
{BundledFonts.V_BOLD, "normal", "bold"},
|
||||||
return;
|
{BundledFonts.V_ITALIC, "italic", "normal"},
|
||||||
|
{BundledFonts.V_BOLD_ITALIC, "italic", "bold"},
|
||||||
|
};
|
||||||
|
for (String[] v : variants) {
|
||||||
|
PhysicalFont variant = BundledFonts.font(family, v[0]);
|
||||||
|
if (variant == null
|
||||||
|
|| hasRealFace(rendererFonts, familyName, v[1], v[2], variant)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
addFont(rendererFonts, factory, familyName, variant, v[1], v[2]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Есть ли в конфиге запись триплета (familyName, style, weight) именно
|
||||||
|
* на реальном TTF {@code variant}. Триплет без этого embed-url
|
||||||
|
* (simulate-style docx4j — все начертания на regular-файле) реальным
|
||||||
|
* лицом не считается: FOP встроит из него не то начертание.
|
||||||
|
*/
|
||||||
|
private static boolean hasRealFace(Fonts rendererFonts, String familyName,
|
||||||
|
String style, String weight, PhysicalFont variant) {
|
||||||
|
String url = variant.getEmbeddedURI().toString();
|
||||||
|
for (Fonts.Font font : rendererFonts.getFont()) {
|
||||||
|
if (!url.equals(font.getEmbedUrl())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (Fonts.Font.FontTriplet triplet : font.getFontTriplet()) {
|
||||||
|
if (familyName.equals(triplet.getName()) && style.equals(triplet.getStyle())
|
||||||
|
&& weight.equals(triplet.getWeight())) {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return false;
|
||||||
addFont(rendererFonts, factory, familyName, regular, "normal", "normal");
|
|
||||||
addFont(rendererFonts, factory, familyName,
|
|
||||||
BundledFonts.bold(family), "normal", "bold");
|
|
||||||
addFont(rendererFonts, factory, familyName,
|
|
||||||
BundledFonts.italic(family), "italic", "normal");
|
|
||||||
addFont(rendererFonts, factory, familyName,
|
|
||||||
BundledFonts.boldItalic(family), "italic", "bold");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -491,6 +491,62 @@ class WordPdfConverterTest {
|
|||||||
"Carlito-BoldItalic не встроен (ран с w:b+w:i должен быть): " + fonts);
|
"Carlito-BoldItalic не встроен (ран с w:b+w:i должен быть): " + fonts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Общая FopFactory строится из fopconf первого документа JVM, а docx4j
|
||||||
|
* декларирует в него только использованные начертания (частично или
|
||||||
|
* simulate-style) — FopFallbackFonts обязан дополнять семейства реальными
|
||||||
|
* начертаниями при каждом declare. Регрессия —
|
||||||
|
* FopFallbackFonts.declareFamily/hasRealFace (macOS-падения
|
||||||
|
* ruPlain_regularRunsUseRegularFont и strictOoxml_convertsNotRejected
|
||||||
|
* зависели от порядка документов в JVM). Здесь порядок задаётся явно:
|
||||||
|
* «ядовитый» doc (один regular-ран Carlito) замороживает фабрику с
|
||||||
|
* частичной декларацией семейства, четырёхначертательный Calibri-doc
|
||||||
|
* обязан получить все четыре Carlito-*; финальный doc без rFonts —
|
||||||
|
* кириллицу вшитым бандл-шрифтом, а не base-14 (симптом «СТРО*ИЙ» на
|
||||||
|
* macOS). Какое семейство выберет док без rFonts — решает docx4j
|
||||||
|
* (дефолт Aptos → Carlito), поэтому ассерт — «вшитый, не Helvetica»,
|
||||||
|
* а не конкретное имя. На Linux ни одна ядовитая комбинация (bold-only
|
||||||
|
* Calibri, regular-only Carlito, italic-only Calibri) этот тест не
|
||||||
|
* краснит: docx4j 17.3.2 здесь декларирует в fopconf полное семейство;
|
||||||
|
* на macOS та же последовательность была красной. Авторитетная
|
||||||
|
* регрессия полноты — FopFallbackFontsTest#declareWhenDocx4jDeclared*,
|
||||||
|
* здесь — smoke независимости вывода от порядка документов в JVM.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void fopFactoryFrozenFromFirstDoc_fontsComplete() throws Exception {
|
||||||
|
resetSharedFopFactory();
|
||||||
|
String rPoison = "<w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/><w:i/></w:rPr>";
|
||||||
|
convertPdf(minimalDocx("<w:p><w:r>" + rPoison
|
||||||
|
+ "<w:t>ЯДОВИТЫЙКУРСИВ</w:t></w:r></w:p>"), "poison");
|
||||||
|
|
||||||
|
String rBold = "<w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/><w:b/></w:rPr>";
|
||||||
|
String rPlain = "<w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/></w:rPr>";
|
||||||
|
String rItal = "<w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/><w:i/></w:rPr>";
|
||||||
|
String rBoldItal =
|
||||||
|
"<w:rPr><w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\"/><w:b/><w:i/></w:rPr>";
|
||||||
|
Set<String> fonts = embeddedFontNames(convertPdf(minimalDocx("<w:p>"
|
||||||
|
+ "<w:r>" + rPlain + "<w:t>ОбычныйКАЛ</w:t></w:r>"
|
||||||
|
+ "<w:r>" + rBold + "<w:t>ЖирныйКАЛ</w:t></w:r>"
|
||||||
|
+ "<w:r>" + rItal + "<w:t>КурсивКАЛ</w:t></w:r>"
|
||||||
|
+ "<w:r>" + rBoldItal + "<w:t>ЖирКурсивКАЛ</w:t></w:r></w:p>"),
|
||||||
|
"four-faces"));
|
||||||
|
for (String face : List.of("Carlito-Regular", "Carlito-Bold",
|
||||||
|
"Carlito-Italic", "Carlito-BoldItalic")) {
|
||||||
|
assertTrue(fonts.stream().anyMatch(n -> n.endsWith("+" + face)),
|
||||||
|
face + " не встроен (фабрика заморожена неполным конфигом): " + fonts);
|
||||||
|
}
|
||||||
|
|
||||||
|
Path strict = convertPdf(minimalDocx(
|
||||||
|
"<w:p><w:r><w:t>СТРОГИЙМАРКЕР таблица</w:t></w:r></w:p>"), "strict-like");
|
||||||
|
String t = norm(pdfText(strict));
|
||||||
|
assertTrue(t.contains("СТРОГИЙМАРКЕР таблица"), "артефакты в тексте: " + t);
|
||||||
|
String cyrFont = fontNameOf(strict, 'Г');
|
||||||
|
assertFalse(cyrFont.startsWith("Helvetica"),
|
||||||
|
"кириллица упала на base-14 (неполный конфиг фабрики): " + cyrFont);
|
||||||
|
assertTrue(embeddedFontNames(strict).contains(cyrFont),
|
||||||
|
"кириллица нарисована не вшитым шрифтом: " + cyrFont);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Regression: символы U+2000–U+2EFF (em-dash «—») docx4j
|
* Regression: символы U+2000–U+2EFF (em-dash «—») docx4j
|
||||||
* {@code RunFontSelector} мапит на "Segoe UI Symbol", которого нет ни в
|
* {@code RunFontSelector} мапит на "Segoe UI Symbol", которого нет ни в
|
||||||
@@ -2835,6 +2891,13 @@ class WordPdfConverterTest {
|
|||||||
return (FopFactory) f.get(null);
|
return (FopFactory) f.get(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Обнуление общей FopFactory: следующий документ строит её заново (шов теста). */
|
||||||
|
private static void resetSharedFopFactory() throws Exception {
|
||||||
|
java.lang.reflect.Field f = WordPdfConverter.class.getDeclaredField("sharedFopFactory");
|
||||||
|
f.setAccessible(true);
|
||||||
|
f.set(null, null);
|
||||||
|
}
|
||||||
|
|
||||||
/** Размер внутренней {@code map} SoftMapCache (package-private поле). */
|
/** Размер внутренней {@code map} SoftMapCache (package-private поле). */
|
||||||
private static int softMapSize(Object cacheHolder, String field) throws Exception {
|
private static int softMapSize(Object cacheHolder, String field) throws Exception {
|
||||||
java.lang.reflect.Field f = cacheHolder.getClass().getDeclaredField(field);
|
java.lang.reflect.Field f = cacheHolder.getClass().getDeclaredField(field);
|
||||||
|
|||||||
@@ -126,4 +126,134 @@ class FopFallbackFontsTest {
|
|||||||
Map.class.getMethod("putAll", Map.class).invoke(variants, savedVariants);
|
Map.class.getMethod("putAll", Map.class).invoke(variants, savedVariants);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Запись fopconf «как docx4j»: один триплет + embed-url. */
|
||||||
|
private static void preRegister(Fonts fonts, String familyName, String style,
|
||||||
|
String weight, String embedUrl) {
|
||||||
|
ObjectFactory factory = new ObjectFactory();
|
||||||
|
Fonts.Font font = factory.createFontsFont();
|
||||||
|
font.setEmbedUrl(embedUrl);
|
||||||
|
Fonts.Font.FontTriplet triplet = factory.createFontsFontFontTriplet();
|
||||||
|
triplet.setName(familyName);
|
||||||
|
triplet.setStyle(style);
|
||||||
|
triplet.setWeight(weight);
|
||||||
|
font.getFontTriplet().add(triplet);
|
||||||
|
fonts.getFont().add(font);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Записи fopconf, несущие указанный триплет. */
|
||||||
|
private static List<Fonts.Font> fontsWithTriplet(Fonts fonts, String familyName,
|
||||||
|
String style, String weight) {
|
||||||
|
return fonts.getFont().stream()
|
||||||
|
.filter(f -> f.getFontTriplet().stream().anyMatch(t ->
|
||||||
|
familyName.equals(t.getName()) && style.equals(t.getStyle())
|
||||||
|
&& weight.equals(t.getWeight())))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Число записей fopconf, несущих хоть один триплет семейства. */
|
||||||
|
private static int familyEntryCount(Fonts fonts, String familyName) {
|
||||||
|
return (int) fonts.getFont().stream()
|
||||||
|
.filter(f -> f.getFontTriplet().stream()
|
||||||
|
.anyMatch(t -> familyName.equals(t.getName())))
|
||||||
|
.count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Embed-url реального TTF варианта fallback-семейства. */
|
||||||
|
private static String variantUrl(String variant) {
|
||||||
|
return BundledFonts.font(BundledFonts.FALLBACK_FAMILY, variant)
|
||||||
|
.getEmbeddedURI().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* docx4j задекларировал только использованное начертание (regular):
|
||||||
|
* declare обязан дополнить семейство недостающими реальными начертаниями,
|
||||||
|
* не дублируя уже вшитый regular. Регрессия частичной декларации
|
||||||
|
* fopconf, из-за которой общая FopFactory первого документа JVM
|
||||||
|
* замерзала без Carlito-Bold (macOS-падение ruPlain_regularRunsUseRegularFont).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void declareWhenDocx4jDeclaredRegularOnly_addsMissingVariants() {
|
||||||
|
BundledFonts.init();
|
||||||
|
String family = declaredFamilyName();
|
||||||
|
Fonts pdfFonts = new ObjectFactory().createFonts();
|
||||||
|
preRegister(pdfFonts, family, "normal", "normal",
|
||||||
|
variantUrl(BundledFonts.V_REGULAR));
|
||||||
|
|
||||||
|
FopFallbackFonts.declare(settingsWith(renderer(MIME_PDF, pdfFonts)));
|
||||||
|
|
||||||
|
assertEquals(1, fontsWithTriplet(pdfFonts, family, "normal", "normal").size(),
|
||||||
|
"regular-запись задублировалась");
|
||||||
|
assertEquals(List.of(variantUrl(BundledFonts.V_BOLD)),
|
||||||
|
fontsWithTriplet(pdfFonts, family, "normal", "bold").stream()
|
||||||
|
.map(Fonts.Font::getEmbedUrl).toList(),
|
||||||
|
"bold-начертание не дополнено реальным TTF");
|
||||||
|
assertEquals(List.of(variantUrl(BundledFonts.V_ITALIC)),
|
||||||
|
fontsWithTriplet(pdfFonts, family, "italic", "normal").stream()
|
||||||
|
.map(Fonts.Font::getEmbedUrl).toList(),
|
||||||
|
"italic-начертание не дополнено реальным TTF");
|
||||||
|
assertEquals(List.of(variantUrl(BundledFonts.V_BOLD_ITALIC)),
|
||||||
|
fontsWithTriplet(pdfFonts, family, "italic", "bold").stream()
|
||||||
|
.map(Fonts.Font::getEmbedUrl).toList(),
|
||||||
|
"bolditalic-начертание не дополнено реальным TTF");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* docx4j задекларировал все четыре триплета на одном regular-файле
|
||||||
|
* (simulate-style): триплет есть, но лицо ненастоящее — declare обязан
|
||||||
|
* добавить реальные TTF жирных/курсивных начертаний поверх.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void declareWhenDocx4jDeclaredSimulatedStyle_addsRealFaces() {
|
||||||
|
BundledFonts.init();
|
||||||
|
String family = declaredFamilyName();
|
||||||
|
Fonts pdfFonts = new ObjectFactory().createFonts();
|
||||||
|
ObjectFactory factory = new ObjectFactory();
|
||||||
|
Fonts.Font simulated = factory.createFontsFont();
|
||||||
|
simulated.setSimulateStyle(true);
|
||||||
|
simulated.setEmbedUrl(variantUrl(BundledFonts.V_REGULAR));
|
||||||
|
String[][] triplets = {
|
||||||
|
{"normal", "normal"}, {"normal", "bold"},
|
||||||
|
{"italic", "normal"}, {"italic", "bold"},
|
||||||
|
};
|
||||||
|
for (String[] t : triplets) {
|
||||||
|
Fonts.Font.FontTriplet triplet = factory.createFontsFontFontTriplet();
|
||||||
|
triplet.setName(family);
|
||||||
|
triplet.setStyle(t[0]);
|
||||||
|
triplet.setWeight(t[1]);
|
||||||
|
simulated.getFontTriplet().add(triplet);
|
||||||
|
}
|
||||||
|
pdfFonts.getFont().add(simulated);
|
||||||
|
|
||||||
|
FopFallbackFonts.declare(settingsWith(renderer(MIME_PDF, pdfFonts)));
|
||||||
|
|
||||||
|
String[][] expected = {
|
||||||
|
{"normal", "normal", variantUrl(BundledFonts.V_REGULAR)},
|
||||||
|
{"normal", "bold", variantUrl(BundledFonts.V_BOLD)},
|
||||||
|
{"italic", "normal", variantUrl(BundledFonts.V_ITALIC)},
|
||||||
|
{"italic", "bold", variantUrl(BundledFonts.V_BOLD_ITALIC)},
|
||||||
|
};
|
||||||
|
for (String[] e : expected) {
|
||||||
|
assertTrue(fontsWithTriplet(pdfFonts, family, e[0], e[1]).stream()
|
||||||
|
.anyMatch(f -> e[2].equals(f.getEmbedUrl())),
|
||||||
|
"нет реальной записи " + e[0] + "/" + e[1] + " на " + e[2]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Идемпотентность полноты: второй declare не плодит дублей семейства. */
|
||||||
|
@Test
|
||||||
|
void declareTwice_noDuplicates() {
|
||||||
|
BundledFonts.init();
|
||||||
|
String family = declaredFamilyName();
|
||||||
|
Fonts pdfFonts = new ObjectFactory().createFonts();
|
||||||
|
|
||||||
|
FopFallbackFonts.declare(settingsWith(renderer(MIME_PDF, pdfFonts)));
|
||||||
|
int afterFirst = familyEntryCount(pdfFonts, family);
|
||||||
|
FopFallbackFonts.declare(settingsWith(renderer(MIME_PDF, pdfFonts)));
|
||||||
|
int afterSecond = familyEntryCount(pdfFonts, family);
|
||||||
|
|
||||||
|
assertTrue(afterFirst >= 4, "после первого declare семейство неполное");
|
||||||
|
assertEquals(afterFirst, afterSecond,
|
||||||
|
"второй declare добавил дубли записей семейства");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user