docx→PDF конвертер на docx4j + FOP (без LibreOffice/Aspose)

- wordpdf-core: WordPdfConverter, встроенные TTF-шрифты (Carlito/Caladea/
  Arimo/Tinos/Cousine/DejaVu), BundledFontMapper с фолбэком в DejaVu
- нормализация w:val on/off (regular-раны не рендерятся жирным курсивом)
- символы U+2000–U+2EFF (em-dash) встраиваются через DejaVu, а не
  системным неembedded-шрифтом
- wordpdf-cli: fat-jar CLI (один/несколько docx, явный выходной файл)
- тесты (docx4j/FOP/PDFBox/POI), README
This commit is contained in:
Pjandro
2026-09-23 17:54:39 +00:00
commit 76c251ddd9
53 changed files with 2163 additions and 0 deletions
@@ -0,0 +1,20 @@
package ru.pjandro.wordpdf;
/**
* Ошибка конвертации docx в PDF.
*
* Наследуется от {@link RuntimeException}: конвертер не бросает
* checked-исключения на уровне публичного API, чтобы не засорять
* вызывающий код. Ошибка означает, что PDF не создан (или создан
* частично, в случае потока).
*/
public class ConversionException extends RuntimeException {
public ConversionException(String message) {
super(message);
}
public ConversionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,149 @@
package ru.pjandro.wordpdf;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.FopFactoryBuilder;
import org.docx4j.Docx4J;
import org.docx4j.convert.out.FOSettings;
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.DocxOnOffNormalizer;
import ru.pjandro.wordpdf.internal.FopFallbackFonts;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
/**
* Конвертер docx -> PDF на базе docx4j + Apache FOP
* (без LibreOffice/Aspose).
*
* Пайплайн: docx -> XSL-FO -> Apache FOP -> PDF.
*
* Шрифты берутся из jar (см. {@link BundledFonts}): конвертация
* не зависит от шрифтов, установленных в системе. Частые MS-шрифты
* подменяются метрически совместимыми open-source аналогами
* (см. {@link BundledFontMapper}).
*
* Класс stateless, все методы статические.
*/
public final class WordPdfConverter {
private WordPdfConverter() {
}
/**
* Конвертирует файл в PDF рядом с исходным: {@code doc.docx -> doc.pdf}.
*
* @param docxIn входной .docx
* @return путь к созданному PDF
* @throws ConversionException при ошибке (не .docx, файл не найден и т.п.)
*/
public static Path convert(Path docxIn) throws ConversionException {
validateInput(docxIn);
String name = docxIn.getFileName().toString();
int dot = name.lastIndexOf('.');
String base = dot > 0 ? name.substring(0, dot) : name;
Path pdfOut = docxIn.resolveSibling(base + ".pdf");
convert(docxIn, pdfOut);
return pdfOut;
}
/**
* Конвертирует {@code docxIn} в {@code pdfOut}.
* Родительские каталоги {@code pdfOut} при необходимости создаются.
*
* @throws ConversionException при ошибке
*/
public static void convert(Path docxIn, Path pdfOut) throws ConversionException {
validateInput(docxIn);
try {
Path parent = pdfOut.toAbsolutePath().getParent();
if (parent != null) {
Files.createDirectories(parent);
}
try (OutputStream os = Files.newOutputStream(pdfOut)) {
convertToStream(docxIn, os);
}
} catch (ConversionException e) {
throw e;
} catch (Exception e) {
throw new ConversionException("Не удалось конвертировать "
+ docxIn + " -> " + pdfOut, e);
}
}
/**
* Ядро конвертации: docx -> XSL-FO -> FOP -> PDF в поток.
*/
private static void convertToStream(Path docxIn, OutputStream os) throws Exception {
// 1. Маппер шрифтов. Порядок важен: конструктор запускает
// обнаружение системных шрифтов, затем бандл-шрифты из jar
// регистрируются поверх них (имеют приоритет).
BundledFontMapper mapper = new BundledFontMapper();
BundledFonts.init();
// 2. Загрузка документа. Предварительно нормализуем w:val="off"/"on"
// в "false"/"true": docx4j 11.x теряет атрибуты "off"/"on"
// при JAXB-разборе (см. DocxOnOffNormalizer).
byte[] docxBytes = Files.readAllBytes(docxIn);
byte[] normalized = DocxOnOffNormalizer.normalize(docxBytes);
WordprocessingMLPackage pkg = WordprocessingMLPackage.load(
new ByteArrayInputStream(normalized));
try {
// 3. Привязка маппера: docx4j сопоставляет шрифты документа
// с физическими TTF (учитывая и шрифты, встроенные в docx)
pkg.setFontMapper(mapper);
// 4. Настройки экспорта (FOP-конфиг с embed-шрифтами)
FOSettings foSettings = new FOSettings(pkg);
// FOP-конфиг знает только шрифты из fontsInUse, а символы
// U+2000–U+2EFF (em-dash и т.п.) в FO маппятся на fallback
// семейство — декларируем его, чтобы FOP встроил подмножество
FopFallbackFonts.declare(foSettings);
// 5. Метаданные PDF: заголовок — из имени файла
FopFactoryBuilder builder = FORendererApacheFOP.getFopFactoryBuilder(foSettings);
FopFactory fopFactory = builder.build();
FOUserAgent foUserAgent = FORendererApacheFOP.getFOUserAgent(foSettings, fopFactory);
foUserAgent.setTitle(baseName(docxIn));
// 6. Проход XSLT (медленнее, но полнее), вывод в поток
Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
} finally {
// 7. Уборка временных файлов встроенных в docx шрифтов
if (pkg.getMainDocumentPart() != null
&& pkg.getMainDocumentPart().getFontTablePart() != null) {
pkg.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
}
// Примечание: в docx4j 11.x OpcPackage.close() отсутствует —
// пакет загружается в память и ничего не закрывает.
}
}
/** Проверяет входной файл: существует, это .docx (не .doc). */
private static void validateInput(Path docxIn) throws ConversionException {
if (docxIn == null) {
throw new ConversionException("Не указан входной файл");
}
if (!Files.isRegularFile(docxIn)) {
throw new ConversionException("Файл не найден: " + docxIn);
}
String name = docxIn.getFileName().toString().toLowerCase(Locale.ROOT);
if (!name.endsWith(".docx")) {
throw new ConversionException(
"Поддерживается только .docx (без .doc): " + docxIn);
}
}
/** Имя файла без расширения (для PDF-заголовка). */
private static String baseName(Path p) {
String name = p.getFileName().toString();
int dot = name.lastIndexOf('.');
return dot > 0 ? name.substring(0, dot) : name;
}
}
@@ -0,0 +1,136 @@
package ru.pjandro.wordpdf.fonts;
import org.docx4j.fonts.BestMatchingMapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.wml.Fonts;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Маппинг имён шрифтов из docx на TTF-шрифты, встроенные в jar.
*
* Стратегия (см. {@link #populateFontMappings}):
* 1. Частые MS-шрифты заменяются метрически совместимыми open-source
* аналогами (таблица алиасов) — они есть в jar и содержат кириллицу.
* 2. Нераспознанные шрифты передаются родительскому
* {@link BestMatchingMapper} (совпадение по Panose-кодам среди
* доступных шрифтов).
* 3. Всё, что так и осталось без маппинга, падает в финальный
* fallback — DejaVu Sans (обязательно с кириллицей).
*
* Для каждого маппированного шрифта дополнительно регистрируются
* варианты Bold/Italic/BoldItalic: экспорт в PDF (FOP) требует отдельный
* файл для каждого начертания. Ключи register*Form — точное имя из
* документа: docx4j ищет варианты именно по нему.
*
* ВАЖНО (порядок инициализации): конструктор BestMatchingMapper
* запускает обнаружение системных шрифтов, которые могут занять те же
* имена в реестре docx4j. Поэтому {@code BundledFonts.init()} нужно
* вызывать ПОСЛЕ создания маппера, чтобы бандл-шрифты оказались в
* реестре поверх системных.
*/
public class BundledFontMapper extends BestMatchingMapper {
/**
* Алиасы: имя шрифта из документа (lowercase) -> бандл-семейство (lowercase).
* Croscore (Arimo/Tinos/Cousine) и crosextra (Carlito/Caladea) шрифты
* метрически совместимы с соответствующими MS-шрифтами и содержат
* кириллицу.
*/
private static final Map<String, String> ALIASES;
/** Финальный fallback: шрифт с гарантированной кириллицей. */
private static final String FALLBACK_FAMILY = BundledFonts.FALLBACK_FAMILY;
/**
* Имя, которое docx4j {@code RunFontSelector} запрашивает у маппера для
* символов диапазона U+2000–U+2EFF (em-dash «—», кавычки «„», многоточие
* «…»), если шрифт ранa не содержит глифа. Это виртуальное имя (в
* документе его нет), поэтому маппим его на {@link #FALLBACK_FAMILY}:
* без записи символ остаётся без font-family в FO и рендерится системным
* неembedded-шрифтом (Helvetica).
*/
static final String SYMBOL_FONT = "Segoe UI Symbol";
static {
Map<String, String> m = new HashMap<>();
// Частые MS-шрифты -> open-source аналоги
m.put("calibri", "carlito");
m.put("calibri light", "carlito");
m.put("cambria", "caladea");
m.put("arial", "arimo");
m.put("times new roman", "tinos");
m.put("courier new", "cousine");
// Бандл-шрифты сами по себе (на случай, если документ прямо
// указывает одно из них)
m.put("carlito", "carlito");
m.put("caladea", "caladea");
m.put("arimo", "arimo");
m.put("tinos", "tinos");
m.put("cousine", "cousine");
m.put("dejavu sans", "dejavu sans");
m.put("dejavu serif", "dejavu serif");
ALIASES = Map.copyOf(m);
}
/**
* Вызывается docx4j при {@code package.setFontMapper(...)}: для каждого
* имени шрифта, использованного в документе, нужно определить, каким
* физическим TTF оно заменяется.
*
* @param documentFontNames имена шрифтов из fontTablePart + run-ов документа
* @param wmlFonts w:fonts из fontTablePart (используются в super)
*/
@Override
public void populateFontMappings(Set<String> documentFontNames, Fonts wmlFonts) throws Exception {
// Виртуальное имя для символов U+2000–U+2EFF (см. SYMBOL_FONT):
// маппим сразу, чтобы оно не попало в remaining и родительский
// BestMatchingMapper не пытался искать его в fontTable (и не логировал
// "Font Segoe UI Symbol not found in font table!").
if (BundledFonts.regular(FALLBACK_FAMILY) != null) {
mapFamily(SYMBOL_FONT, FALLBACK_FAMILY);
}
Set<String> remaining = new LinkedHashSet<>();
for (String docFontName : documentFontNames) {
if (SYMBOL_FONT.equalsIgnoreCase(docFontName)) {
// уже маппировано выше
continue;
}
String family = ALIASES.get(docFontName.toLowerCase(Locale.ROOT));
if (family == null || BundledFonts.regular(family) == null) {
// Нет алиаса (или init() не вызван) — доверимся родителю
remaining.add(docFontName);
continue;
}
mapFamily(docFontName, family);
}
// Нераспознанные: Panose-совпадение (логика родителя)
super.populateFontMappings(remaining, wmlFonts);
// Финальный fallback: всё, что так и не маппилось -> DejaVu Sans
PhysicalFont fallback = BundledFonts.regular(FALLBACK_FAMILY);
if (fallback != null) {
for (String docFontName : documentFontNames) {
if (get(docFontName) == null) {
mapFamily(docFontName, FALLBACK_FAMILY);
}
}
}
}
/**
* Привязывает все начертания семейства к имени шрифта из документа.
*/
private void mapFamily(String docFontName, String family) {
put(docFontName, BundledFonts.regular(family));
registerBoldForm(docFontName, BundledFonts.bold(family));
registerItalicForm(docFontName, BundledFonts.italic(family));
registerBoldItalicForm(docFontName, BundledFonts.boldItalic(family));
}
}
@@ -0,0 +1,198 @@
package ru.pjandro.wordpdf.fonts;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Регистрация TTF-шрифтов, встроенных в jar (classpath: fonts/).
*
* Экспорт в PDF (Apache FOP) требует файлы шрифтов на диске, поэтому
* шрифты выгружаются из jar в временный каталог и регистрируются в
* реестре docx4j ({@link PhysicalFonts}). Это делает jar самодостаточным:
* конвертация работает на системах без каких-либо установленных шрифтов.
*
* ВАЖНО (порядок инициализации): конструктор {@link org.docx4j.fonts.Mapper}
* (в частности {@link BundledFontMapper}) запускает обнаружение системных
* шрифтов, которые могут занять те же имена в реестре. Поэтому
* {@link #init()} нужно вызывать ПОСЛЕ создания маппера: бандл-шрифты
* регистрируются поверх системных и имеют приоритет.
*
* Имена шрифтов в реестре docx4j берутся из name-таблицы TTF (полное имя),
* а не из имени файла — например, у DejaVu курсив называется «Oblique»,
* а не «Italic». Поэтому зарегистрированный объект ищется по URI файла,
* а не по предпологаемому имени.
*/
public final class BundledFonts {
/** Начертание: обычное. */
public static final String V_REGULAR = "regular";
/** Начертание: полужирное. */
public static final String V_BOLD = "bold";
/** Начертание: курсивное. */
public static final String V_ITALIC = "italic";
/** Начертание: полужирный курсив. */
public static final String V_BOLD_ITALIC = "bolditalic";
/**
* Fallback-семейство: используется для символов, не найденных в
* шрифте ранa (em-dash, кавычки, U+2000–U+2EFF), и для нераспознанных
* шрифтов (см. {@link BundledFontMapper}). Гарантированная кириллица.
*/
public static final String FALLBACK_FAMILY = "dejavu sans";
/** Каталог с TTF внутри jar (classpath). */
private static final String CLASSPATH_DIR = "fonts";
/** Описание одного файла: имя в jar, ключ семейства, начертание.
* Package-private: доступ для теста. */
static record Entry(String file, String family, String variant) {
}
/**
* Все TTF из resources/fonts/. Список нужно поддерживать в sync с
* фактическими файлами (это проверяет BundledFontsTest).
* Package-private: доступ для теста.
*/
static final List<Entry> ENTRIES = List.of(
// Carlito — open-source аналог Calibri (SIL OFL)
new Entry("Carlito-Regular.ttf", "carlito", V_REGULAR),
new Entry("Carlito-Bold.ttf", "carlito", V_BOLD),
new Entry("Carlito-Italic.ttf", "carlito", V_ITALIC),
new Entry("Carlito-BoldItalic.ttf", "carlito", V_BOLD_ITALIC),
// Caladea — open-source аналог Cambria (SIL OFL)
new Entry("Caladea-Regular.ttf", "caladea", V_REGULAR),
new Entry("Caladea-Bold.ttf", "caladea", V_BOLD),
new Entry("Caladea-Italic.ttf", "caladea", V_ITALIC),
new Entry("Caladea-BoldItalic.ttf", "caladea", V_BOLD_ITALIC),
// Arimo — open-source аналог Arial (SIL OFL)
new Entry("Arimo-Regular.ttf", "arimo", V_REGULAR),
new Entry("Arimo-Bold.ttf", "arimo", V_BOLD),
new Entry("Arimo-Italic.ttf", "arimo", V_ITALIC),
new Entry("Arimo-BoldItalic.ttf", "arimo", V_BOLD_ITALIC),
// Tinos — open-source аналог Times New Roman (SIL OFL)
new Entry("Tinos-Regular.ttf", "tinos", V_REGULAR),
new Entry("Tinos-Bold.ttf", "tinos", V_BOLD),
new Entry("Tinos-Italic.ttf", "tinos", V_ITALIC),
new Entry("Tinos-BoldItalic.ttf", "tinos", V_BOLD_ITALIC),
// Cousine — open-source аналог Courier New (SIL OFL)
new Entry("Cousine-Regular.ttf", "cousine", V_REGULAR),
new Entry("Cousine-Bold.ttf", "cousine", V_BOLD),
new Entry("Cousine-Italic.ttf", "cousine", V_ITALIC),
new Entry("Cousine-BoldItalic.ttf", "cousine", V_BOLD_ITALIC),
// DejaVu — fallback для нераспознанных шрифтов (SIL OFL),
// гарантированная кириллица
new Entry("DejaVuSans-Regular.ttf", "dejavu sans", V_REGULAR),
new Entry("DejaVuSans-Bold.ttf", "dejavu sans", V_BOLD),
new Entry("DejaVuSans-Italic.ttf", "dejavu sans", V_ITALIC),
new Entry("DejaVuSans-BoldItalic.ttf", "dejavu sans", V_BOLD_ITALIC),
new Entry("DejaVuSerif-Regular.ttf", "dejavu serif", V_REGULAR),
new Entry("DejaVuSerif-Bold.ttf", "dejavu serif", V_BOLD),
new Entry("DejaVuSerif-Italic.ttf", "dejavu serif", V_ITALIC),
new Entry("DejaVuSerif-BoldItalic.ttf", "dejavu serif", V_BOLD_ITALIC)
);
/** Ключ семейства (lowercase) -> начертание -> зарегистрированный PhysicalFont. */
private static final Map<String, Map<String, PhysicalFont>> VARIANTS = new HashMap<>();
/** Каталог, куда выгружены TTF (после init()). */
private static Path extractDir;
private static boolean inited = false;
private BundledFonts() {
}
/**
* Выгружает шрифты из jar и регистрирует их в docx4j.
* Повторные вызовы игнорируются (idempotентно).
*/
public static synchronized void init() {
if (inited) {
return;
}
try {
extractDir = Files.createTempDirectory("wordpdf-fonts-");
} catch (IOException e) {
throw new IllegalStateException("Не удалось создать временный каталог для шрифтов", e);
}
for (Entry entry : ENTRIES) {
// 1. Выгружаем файл из jar
Path target = extractDir.resolve(entry.file());
try (InputStream in = BundledFonts.class.getClassLoader()
.getResourceAsStream(CLASSPATH_DIR + "/" + entry.file())) {
if (in == null) {
throw new IllegalStateException(
"Шрифт не найден в jar: " + CLASSPATH_DIR + "/" + entry.file());
}
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Не удалось выгрузить шрифт " + entry.file(), e);
}
// 2. Регистрируем в docx4j: имя в реестре docx4j берёт из
// name-таблицы TTF, поэтому ищем результат по URI файла
PhysicalFonts.addPhysicalFont(target.toUri());
PhysicalFont pf = findByFile(target.getFileName().toString());
if (pf == null) {
throw new IllegalStateException(
"docx4j не зарегистрировал шрифт: " + entry.file()
+ " (файл повреждён или не embeddable?)");
}
// 3. Учимся: семейство -> начертание -> PhysicalFont
VARIANTS
.computeIfAbsent(entry.family(), k -> new HashMap<>())
.put(entry.variant(), pf);
}
// Удаление временного каталога при завершении JVM
extractDir.toFile().deleteOnExit();
inited = true;
}
/** Находит в реестре docx4j шрифт по имени файла (embeddedURI). */
private static PhysicalFont findByFile(String filename) {
for (PhysicalFont pf : PhysicalFonts.getPhysicalFonts().values()) {
java.net.URI uri = pf.getEmbeddedURI();
if (uri != null && uri.toString().endsWith(filename)) {
return pf;
}
}
return null;
}
/**
* Зарегистрированный шрифт: семейство (lowercase) + начертание.
*
* @return PhysicalFont или null (если init() не вызван или шрифта нет)
*/
public static PhysicalFont font(String family, String variant) {
Map<String, PhysicalFont> m = VARIANTS.get(family);
return m == null ? null : m.get(variant);
}
public static PhysicalFont regular(String family) {
return font(family, V_REGULAR);
}
public static PhysicalFont bold(String family) {
return font(family, V_BOLD);
}
public static PhysicalFont italic(String family) {
return font(family, V_ITALIC);
}
public static PhysicalFont boldItalic(String family) {
return font(family, V_BOLD_ITALIC);
}
}
@@ -0,0 +1,89 @@
package ru.pjandro.wordpdf.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Нормализация ST_OnOff-значений в docx перед загрузкой docx4j.
*
* docx4j 11.x теряет атрибуты {@code w:val="off"} / {@code w:val="on"}
* при JAXB-разборе (тип поля {@code Boolean} не принимает "on"/"off",
* поле остаётся null и {@code BooleanDefaultTrue.isVal()} считается
* true). Из-за этого явные {@code <w:b w:val="off"/>} и
* {@code <w:i w:val="off"/>} (так записывают, например, POI)
* превращаются в bold+italic в PDF. Значения true/false/1/0
* docx4j разбирает корректно, поэтому заменяем "off"->"false",
* "on"->"true" в XML-частях word/*.xml.
*
* Если совпадений нет, возвращает исходный массив без переупаковки zip.
*/
public final class DocxOnOffNormalizer {
private static final Pattern ON_OFF = Pattern.compile(
"w:val=([\"'])(on|off)\\1", Pattern.CASE_INSENSITIVE);
private DocxOnOffNormalizer() {
}
/**
* Заменяет в XML-частях docx (word/*.xml) w:val="off"/"on"
* на "false"/"true".
*
* @param docx байты .docx (zip)
* @return те же или переупакованные байты
*/
public static byte[] normalize(byte[] docx) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(docx.length);
boolean changed = false;
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(docx));
ZipOutputStream zos = new ZipOutputStream(out)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
byte[] data = zis.readAllBytes();
String name = entry.getName();
if (name.startsWith("word/") && name.endsWith(".xml")) {
String fixed = rewrite(new String(data, StandardCharsets.UTF_8));
if (fixed != null) {
changed = true;
data = fixed.getBytes(StandardCharsets.UTF_8);
}
}
zos.putNextEntry(new ZipEntry(name));
zos.write(data);
zos.closeEntry();
}
}
return changed ? out.toByteArray() : docx;
}
/**
* Заменяет в XML-строке w:val="off"/"on" на "false"/"true".
*
* @return новая строка либо null, если совпадений не было
*/
static String rewrite(String xml) {
if (xml.indexOf("w:val=") < 0) {
return null;
}
Matcher m = ON_OFF.matcher(xml);
if (!m.find()) {
return null;
}
m.reset();
StringBuilder sb = new StringBuilder(xml.length());
while (m.find()) {
String value = m.group(2).equalsIgnoreCase("on") ? "true" : "false";
m.appendReplacement(sb, Matcher.quoteReplacement(
"w:val=" + m.group(1) + value + m.group(1)));
}
m.appendTail(sb);
return sb.toString();
}
}
@@ -0,0 +1,88 @@
package ru.pjandro.wordpdf.internal;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.convert.out.fopconf.Fonts;
import org.docx4j.convert.out.fopconf.ObjectFactory;
import org.docx4j.fonts.PhysicalFont;
import ru.pjandro.wordpdf.fonts.BundledFonts;
/**
* Декларирует fallback-семейство (DejaVu Sans) в FOP-конфиге.
*
* FOP-конфиг, который docx4j строит в {@code FOSettings}, содержит
* только шрифты, реально использованные в документе ({@code fontsInUse}).
* Но docx4j {@code RunFontSelector} для символов диапазона U+2000–U+2EFF
* (em-dash «—», кавычки, многоточие) выставляет в FO
* {@code font-family}, маппированный с "Segoe UI Symbol" на DejaVu Sans
* (см. {@link ru.pjandro.wordpdf.fonts.BundledFontMapper}). Если семейство
* не задекларировано в FOP-конфиге, FOP не может его встроить и падает
* на базовый неembedded-шрифт (Helvetica) — символ рендерится шрифтом
* просмотрщика, а не встраиваемым подмножеством.
*
* Метод идемпотентен: если семейство уже задекларировано (например,
* документ прямо использует DejaVu), ничего не добавляет.
*/
public final class FopFallbackFonts {
private FopFallbackFonts() {
}
/**
* Добавляет все начертания fallback-семейства в FOP-конфиг
* {@code foSettings}. Вызывать после {@code new FOSettings(pkg)}
* и до передачи настроек в {@code FORendererApacheFOP}.
*/
public static void declare(FOSettings foSettings) {
Fonts rendererFonts = foSettings.getFopConfig()
.getRenderers()
.getRenderer()
.getFonts();
if (rendererFonts == null) {
return;
}
PhysicalFont regular = BundledFonts.regular(BundledFonts.FALLBACK_FAMILY);
if (regular == null) {
return;
}
// Имя семейства — из name-таблицы TTF regular-варианта
// (например, "DejaVu Sans"): по нему FO запрашивает шрифт,
// и под это же имя декларируются все начертания (так делает
// docx4j FopConfigUtil.createVariant).
String familyName = regular.getName();
for (Fonts.Font existing : rendererFonts.getFont()) {
for (Fonts.Font.FontTriplet triplet : existing.getFontTriplet()) {
if (familyName.equals(triplet.getName())) {
return;
}
}
}
ObjectFactory factory = new ObjectFactory();
addFont(rendererFonts, factory, familyName, regular, "normal", "normal");
addFont(rendererFonts, factory, familyName,
BundledFonts.bold(BundledFonts.FALLBACK_FAMILY), "normal", "bold");
addFont(rendererFonts, factory, familyName,
BundledFonts.italic(BundledFonts.FALLBACK_FAMILY), "italic", "normal");
addFont(rendererFonts, factory, familyName,
BundledFonts.boldItalic(BundledFonts.FALLBACK_FAMILY), "italic", "bold");
}
private static void addFont(Fonts rendererFonts, ObjectFactory factory,
String familyName, PhysicalFont pf,
String style, String weight) {
if (pf == null) {
return;
}
Fonts.Font font = factory.createFontsFont();
font.setSimulateStyle(false);
font.setEmbedUrl(pf.getEmbeddedURI().toString());
// Имя tripleta — имя regular-варианта (как в docx4j
// FopConfigUtil.createVariant): по нему FO запрашивает семейство
Fonts.Font.FontTriplet triplet = factory.createFontsFontFontTriplet();
triplet.setName(familyName);
triplet.setStyle(style);
triplet.setWeight(weight);
font.getFontTriplet().add(triplet);
rendererFonts.getFont().add(font);
}
}
Binary file not shown.
@@ -0,0 +1,187 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
TeX Gyre DJV Math
-----------------
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
(on behalf of TeX users groups) are in public domain.
Letters imported from Euler Fraktur from AMSfonts are (c) American
Mathematical Society (see below).
Bitstream Vera Fonts Copyright
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license (“Fonts”) and associated
documentation
files (the “Font Software”), to reproduce and distribute the Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute,
and/or sell copies of the Font Software, and to permit persons to whom
the Font Software is furnished to do so, subject to the following
conditions:
The above copyright and trademark notices and this permission notice
shall be
included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional
glyphs or characters may be added to the Fonts, only if the fonts are
renamed
to names not containing either the words “Bitstream” or the word “Vera”.
This License becomes null and void to the extent applicable to Fonts or
Font Software
that has been modified and is distributed under the “Bitstream Vera”
names.
The Font Software may be sold as part of a larger software package but
no copy
of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of GNOME, the GNOME
Foundation,
and Bitstream Inc., shall not be used in advertising or otherwise to promote
the sale, use or other dealings in this Font Software without prior written
authorization from the GNOME Foundation or Bitstream Inc., respectively.
For further information, contact: fonts at gnome dot org.
AMSFonts (v. 2.2) copyright
The PostScript Type 1 implementation of the AMSFonts produced by and
previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
available for general use. This has been accomplished through the
cooperation
of a consortium of scientific publishers with Blue Sky Research and Y&Y.
Members of this consortium include:
Elsevier Science IBM Corporation Society for Industrial and Applied
Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
In order to assure the authenticity of these fonts, copyright will be
held by
the American Mathematical Society. This is not meant to restrict in any way
the legitimate use of the fonts, such as (but not limited to) electronic
distribution of documents containing these fonts, inclusion of these fonts
into other public domain or commercial font collections or computer
applications, use of the outline data to create derivative fonts and/or
faces, etc. However, the AMS does require that the AMS copyright notice be
removed from any derivative versions of the fonts which have been altered in
any way. In addition, to ensure the fidelity of TeX documents using Computer
Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
has requested that any alterations which yield different font metrics be
given a different name.
$Id$
@@ -0,0 +1,18 @@
Лицензии на шрифты, упакованные в этот каталог:
- Arimo, Cousine, Tinos (метрически совместимы с Arial, Courier New, Times New Roman)
SIL Open Font License 1.1 (SIL OFL 1.1).
Источник: пакет fonts-croscore (Debian/Ubuntu), upstream: noto-fonts (Google).
- Carlito (метрически совместим с Calibri), Caladea (метрически совместима с Cambria)
SIL Open Font License 1.1 (SIL OFL 1.1).
Carlito: (c) 2010-2013 tyPoland Lukasz Dziedzic (upstream: googlefonts/carlito).
Caladea: (c) 2011-2016 tyPoland (upstream: googlefonts/caladea).
Источник: пакеты fonts-crosextra-carlito / fonts-crosextra-caladea (Debian/Ubuntu).
- DejaVu Sans, DejaVu Serif
SIL Open Font License 1.1 + публичные домены (Bitstream Vera).
Источник: официальный tarball dejavu-fonts-ttf-2.37 (https://dejavu-fonts.github.io),
LICENSE см. DejaVu-LICENSE.txt.
Все шрифты свободно распространяемы и поддерживают кириллицу.
Binary file not shown.
@@ -0,0 +1,7 @@
# slf4j-simple: уровень по умолчанию.
# Важно: без настроенного slf4j docx4j печатает предупреждение
# "TO HIDE THESE MESSAGES" прямо в выходной PDF.
org.slf4j.simpleLogger.defaultLogLevel=info
# Спам docx4j (warn "No entry in MicrosoftFontsRegistry..." и т.п.)
# не информативен для пользователя CLI
org.slf4j.simpleLogger.log.org.docx4j=info