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:
@@ -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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
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$
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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.
Binary file not shown.
Binary file not shown.
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
|
||||
@@ -0,0 +1,234 @@
|
||||
package ru.pjandro.wordpdf;
|
||||
|
||||
import org.apache.poi.common.usermodel.PictureType;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTable;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
|
||||
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
|
||||
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
|
||||
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ОДНОРАЗОВАЯ утилита: генерация готовых .docx для тестов (Apache POI).
|
||||
*
|
||||
* Готовые файлы лежат в {@code wordpdf-core/src/test/resources/samples/}
|
||||
* и коммитятся в репозиторий: сами тесты работают с ними как с
|
||||
* обычными входными файлами и docx не генерируют.
|
||||
*
|
||||
* Пересоздать (если нужно):
|
||||
* <pre>
|
||||
* mvn -pl wordpdf-core test-compile \
|
||||
* -Dmdep.outputFile=/tmp/cp.txt dependency:build-classpath -q
|
||||
* java -cp wordpdf-core/target/test-classes:$(cat /tmp/cp.txt) \
|
||||
* ru.pjandro.wordpdf.SampleDocxGenerator \
|
||||
* wordpdf-core/src/test/resources/samples
|
||||
* </pre>
|
||||
*/
|
||||
public final class SampleDocxGenerator {
|
||||
|
||||
private SampleDocxGenerator() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path dir = Paths.get(args.length > 0 ? args[0] : "samples");
|
||||
dir.toFile().mkdirs();
|
||||
|
||||
ruPlain(dir.resolve("ru-plain.docx"));
|
||||
enPlain(dir.resolve("en-plain.docx"));
|
||||
ruEnMixed(dir.resolve("ru-en-mixed.docx"));
|
||||
ruTimes(dir.resolve("ru-times.docx"));
|
||||
ruTableImage(dir.resolve("ru-table-image.docx"));
|
||||
|
||||
System.out.println("Готово: " + dir.toAbsolutePath());
|
||||
}
|
||||
|
||||
/** Русский текст, Calibri, заголовок + полужирный и курсивный run'ы. */
|
||||
private static void ruPlain(Path out) throws Exception {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
heading(doc, "Тестовый документ (русский)", "Calibri");
|
||||
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
run(p, "Привет, мир! ", "Calibri", false, false);
|
||||
run(p, "Это ", "Calibri", true, false);
|
||||
run(p, "курсивный", "Calibri", false, true);
|
||||
run(p, " и ", "Calibri", false, false);
|
||||
run(p, "жирный курсив", "Calibri", true, true);
|
||||
run(p, " текст.", "Calibri", false, false);
|
||||
|
||||
p = doc.createParagraph();
|
||||
run(p, "Быстрая рыжая лиса прыгает через ленивого пса — "
|
||||
+ "абвгдеёжзийклмнопрстуфхцчшщъыьэюя 0123456789.", "Calibri", false, false);
|
||||
|
||||
save(doc, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Английский текст, Times New Roman. */
|
||||
private static void enPlain(Path out) throws Exception {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
heading(doc, "Test document (English)", "Times New Roman");
|
||||
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
run(p, "Hello, world! The quick brown fox jumps over the lazy dog.",
|
||||
"Times New Roman", false, false);
|
||||
|
||||
p = doc.createParagraph();
|
||||
run(p, "Bold and italic styles: ", "Times New Roman", false, false);
|
||||
run(p, "bold", "Times New Roman", true, false);
|
||||
run(p, " and ", "Times New Roman", false, false);
|
||||
run(p, "italic", "Times New Roman", false, true);
|
||||
run(p, ".", "Times New Roman", false, false);
|
||||
|
||||
save(doc, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Смешанный RU/EN: заголовок уровня 2, «список», таблица. */
|
||||
private static void ruEnMixed(Path out) throws Exception {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
heading(doc, "Смешанный документ", "Calibri");
|
||||
|
||||
// «Заголовок уровня 2»: POI 5.5 не имеет createHeading —
|
||||
// имитируем жирным run'ом с меньшим размером
|
||||
XWPFParagraph h2 = doc.createParagraph();
|
||||
XWPFRun h2run = h2.createRun();
|
||||
h2run.setText("Section two / Раздел два");
|
||||
h2run.setBold(true);
|
||||
h2run.setFontSize(14);
|
||||
setFont(h2run, "Calibri");
|
||||
|
||||
// «Список» (в POI нативный numbering — отдельная история,
|
||||
// для тестового документа достаточно маркера)
|
||||
for (String item : List.of(
|
||||
"• Пункт один — first item",
|
||||
"• Пункт два — second item",
|
||||
"• Пункт три — third item")) {
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
run(p, item, "Calibri", false, false);
|
||||
}
|
||||
|
||||
// Таблица 2x2 с границами
|
||||
XWPFTable table = doc.createTable(2, 2);
|
||||
setCell(table, 0, 0, "Заголовок 1", "Calibri");
|
||||
setCell(table, 0, 1, "Header 1", "Calibri");
|
||||
setCell(table, 1, 0, "Ячейка А", "Calibri");
|
||||
setCell(table, 1, 1, "Cell B", "Calibri");
|
||||
|
||||
save(doc, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Русский текст, Times New Roman (алиас -> Tinos). */
|
||||
private static void ruTimes(Path out) throws Exception {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
heading(doc, "Русский, Times New Roman", "Times New Roman");
|
||||
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
run(p, "Съешь ещё этих мягких французских булок, да выпей чаю. "
|
||||
+ "Раз, два, три, четыре, пять — я пошёл гулять.",
|
||||
"Times New Roman", false, false);
|
||||
|
||||
save(doc, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** Таблица + встроенное изображение (PNG). */
|
||||
private static void ruTableImage(Path out) throws Exception {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
heading(doc, "Таблица и изображение", "Arial");
|
||||
|
||||
XWPFTable table = doc.createTable(3, 2);
|
||||
setCell(table, 0, 0, "Имя", "Arial");
|
||||
setCell(table, 0, 1, "Значение", "Arial");
|
||||
setCell(table, 1, 0, "Шрифт", "Arial");
|
||||
setCell(table, 1, 1, "Arial", "Arial");
|
||||
setCell(table, 2, 0, "Язык", "Arial");
|
||||
setCell(table, 2, 1, "Русский", "Arial");
|
||||
|
||||
// PNG 120x60: красная полоса
|
||||
BufferedImage img = new BufferedImage(120, 60, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, 120, 60);
|
||||
g.setColor(Color.RED);
|
||||
g.fillRect(10, 10, 100, 40);
|
||||
g.dispose();
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ImageIO.write(img, "png", bos);
|
||||
|
||||
// В POI 5.5 изображение добавляется через run.
|
||||
// Размеры в EMU (1 px @ 96 dpi = 9525 EMU)
|
||||
XWPFParagraph imgPara = doc.createParagraph();
|
||||
XWPFRun imgRun = imgPara.createRun();
|
||||
imgRun.addPicture(new java.io.ByteArrayInputStream(bos.toByteArray()),
|
||||
PictureType.PNG, "test-image.png",
|
||||
120 * 9525, 60 * 9525);
|
||||
|
||||
save(doc, out);
|
||||
}
|
||||
}
|
||||
|
||||
// ================== Вспомогательные ==================
|
||||
|
||||
/** Абзац-заголовок: POI 5.5 не имеет createHeading, поэтому
|
||||
* имитируем жирным run'ом увеличенного размера. */
|
||||
private static void heading(XWPFDocument doc, String text, String font) {
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
XWPFRun r = p.createRun();
|
||||
r.setText(text);
|
||||
r.setBold(true);
|
||||
r.setFontSize(18);
|
||||
setFont(r, font);
|
||||
}
|
||||
|
||||
/** Run с текстом, шрифтом, bold/italic. */
|
||||
private static void run(XWPFParagraph p, String text, String font,
|
||||
boolean bold, boolean italic) {
|
||||
XWPFRun r = p.createRun();
|
||||
r.setText(text);
|
||||
r.setBold(bold);
|
||||
r.setItalic(italic);
|
||||
setFont(r, font);
|
||||
}
|
||||
|
||||
/** Задаёт шрифт для латиницы (w:rFonts@w:ascii и @w:hAnsi) —
|
||||
* именно так docx4j определяет шрифт run'а. */
|
||||
private static void setFont(XWPFRun r, String font) {
|
||||
CTR ctr = r.getCTR();
|
||||
CTRPr rPr = ctr.isSetRPr() ? ctr.getRPr() : ctr.addNewRPr();
|
||||
CTFonts f = rPr.getRFontsArray().length > 0
|
||||
? rPr.getRFontsArray()[0]
|
||||
: rPr.addNewRFonts();
|
||||
f.setAscii(font);
|
||||
f.setHAnsi(font);
|
||||
}
|
||||
|
||||
private static void setCell(XWPFTable table, int row, int col,
|
||||
String text, String font) {
|
||||
XWPFTableCell cell = table.getRow(row).getCell(col);
|
||||
XWPFRun r = cell.getParagraphs().get(0).createRun();
|
||||
r.setText(text);
|
||||
setFont(r, font);
|
||||
}
|
||||
|
||||
private static void save(XWPFDocument doc, Path out) throws Exception {
|
||||
try (FileOutputStream fos = new FileOutputStream(out.toFile())) {
|
||||
doc.write(fos);
|
||||
}
|
||||
System.out.println(" создан: " + out.getFileName()
|
||||
+ " (" + new File(out.toString()).length() + " байт)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package ru.pjandro.wordpdf;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
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.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Конвертация готовых .docx (src/test/resources/samples) в PDF.
|
||||
* Текст PDF извлекается PDFBox и проверяется.
|
||||
*/
|
||||
class WordPdfConverterTest {
|
||||
|
||||
/** Готовый тестовый документ (коммитится, создан SampleDocxGenerator). */
|
||||
private static Path extractSample(String name) throws IOException {
|
||||
try (InputStream in = WordPdfConverterTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/" + name)) {
|
||||
assertNotNull(in, "Нет тестового документа: samples/" + name);
|
||||
Path tmp = Files.createTempFile("sample-" + name + "-", ".docx");
|
||||
Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
/** Извлекает весь текст из PDF (PDFBox, PDFTextStripper). */
|
||||
private static String pdfText(Path pdf) throws IOException {
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
return new PDFTextStripper().getText(doc);
|
||||
}
|
||||
}
|
||||
|
||||
/** Конвертирует docx в временный PDF и возвращает его путь. */
|
||||
private static Path convert(Path docx) throws IOException {
|
||||
Path out = Files.createTempFile("converted-", ".pdf");
|
||||
WordPdfConverter.convert(docx, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Нормализует пробельные (PDFTextExtractor вставляет переносы). */
|
||||
private static String norm(String s) {
|
||||
return s.replaceAll("\\s+", " ");
|
||||
}
|
||||
|
||||
/** BaseFont-имена вшитых шрифтов PDF (например "EAAAAA+Carlito-Bold"). */
|
||||
private static Set<String> embeddedFontNames(Path pdf) throws IOException {
|
||||
Set<String> names = new TreeSet<>();
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources res = page.getResources();
|
||||
for (COSName name : res.getFontNames()) {
|
||||
PDFont font = res.getFont(name);
|
||||
if (font != null) {
|
||||
names.add(font.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruPlain_cyrillicAndStyles() throws Exception {
|
||||
Path in = extractSample("ru-plain.docx");
|
||||
String text = norm(pdfText(convert(in)));
|
||||
|
||||
assertTrue(text.contains("Привет, мир!"), "нет «Привет, мир!»: " + text);
|
||||
// Полный кириллический алфавит — проверка, что все глифы встроились
|
||||
assertTrue(text.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"),
|
||||
"нет кириллического алфавита: " + text);
|
||||
assertTrue(text.contains("жирный курсив"), "нет «жирный курсив»: " + text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: docx4j теряет w:val="off" (см. DocxOnOffNormalizer),
|
||||
* из-за чего regular-раны рендерились Carlito-BoldItalic.
|
||||
* Документ содержит все четыре начертания: в PDF должны
|
||||
* встраиваться все четыре подмножества, в том числе regular
|
||||
* (FOP называет его по имени из TTF: "…+Carlito-Regular").
|
||||
*/
|
||||
@Test
|
||||
void ruPlain_regularRunsUseRegularFont() throws Exception {
|
||||
Path in = extractSample("ru-plain.docx");
|
||||
Set<String> fonts = embeddedFontNames(convert(in));
|
||||
|
||||
assertTrue(fonts.stream().anyMatch(n -> n.endsWith("+Carlito-Regular")),
|
||||
"regular-подмножество Carlito не встроено: " + fonts);
|
||||
assertTrue(fonts.stream().anyMatch(n -> n.endsWith("+Carlito-Bold")),
|
||||
"Carlito-Bold не встроен: " + fonts);
|
||||
assertTrue(fonts.stream().anyMatch(n -> n.endsWith("+Carlito-Italic")),
|
||||
"Carlito-Italic не встроен: " + fonts);
|
||||
assertTrue(fonts.stream().anyMatch(n -> n.endsWith("+Carlito-BoldItalic")),
|
||||
"Carlito-BoldItalic не встроен (ран с w:b+w:i должен быть): " + fonts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: символы U+2000–U+2EFF (em-dash «—») docx4j
|
||||
* {@code RunFontSelector} мапит на "Segoe UI Symbol", которого нет ни в
|
||||
* документе, ни в fontTable. Без маппинга (BundledFontMapper) и
|
||||
* декларации в FOP-конфиге (FopFallbackFonts) символ рендерился
|
||||
* системным неembedded-шрифтом (Helvetica). Теперь em-dash
|
||||
* встраивается подмножеством fallback-семейства (DejaVu).
|
||||
*/
|
||||
@Test
|
||||
void ruPlain_emDashEmbeddedNotHelvetica() throws Exception {
|
||||
Path in = extractSample("ru-plain.docx");
|
||||
Path pdf = convert(in);
|
||||
|
||||
// Текст извлекается (глиф на месте)
|
||||
assertTrue(norm(pdfText(pdf)).contains("—"), "em-dash не извлёкся");
|
||||
|
||||
Set<String> fonts = embeddedFontNames(pdf);
|
||||
// Em-dash в fallback-семействе (DejaVu), а не в системном Helvetica
|
||||
assertTrue(fonts.stream().anyMatch(n -> n.contains("DejaVu")),
|
||||
"fallback-подмножество (DejaVu) не встроено: " + fonts);
|
||||
assertFalse(fonts.stream().anyMatch(n -> n.startsWith("Helvetica")),
|
||||
"em-dash упал на системный неembedded-шрифт: " + fonts);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enPlain_englishText() throws Exception {
|
||||
Path in = extractSample("en-plain.docx");
|
||||
String text = norm(pdfText(convert(in)));
|
||||
|
||||
assertTrue(text.contains("Hello, world!"), "нет «Hello, world!»: " + text);
|
||||
assertTrue(text.contains("quick brown fox"), "нет «quick brown fox»: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixed_headingListTable() throws Exception {
|
||||
Path in = extractSample("ru-en-mixed.docx");
|
||||
String text = norm(pdfText(convert(in)));
|
||||
|
||||
assertTrue(text.contains("Смешанный документ"), "нет заголовка: " + text);
|
||||
assertTrue(text.contains("first item"), "нет пункта списка: " + text);
|
||||
assertTrue(text.contains("Ячейка А") && text.contains("Cell B"),
|
||||
"нет ячеек таблицы: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruTimes_russianInTimes() throws Exception {
|
||||
Path in = extractSample("ru-times.docx");
|
||||
String text = norm(pdfText(convert(in)));
|
||||
|
||||
assertTrue(text.contains("Съешь ещё этих мягких французских булок"),
|
||||
"нет русского текста: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableImage_tableAndImage() throws Exception {
|
||||
Path in = extractSample("ru-table-image.docx");
|
||||
String text = norm(pdfText(convert(in)));
|
||||
|
||||
assertTrue(text.contains("Значение"), "нет текста таблицы: " + text);
|
||||
assertTrue(text.contains("Русский"), "нет «Русский»: " + text);
|
||||
|
||||
// Изображение: ищем XObject'ы-изображения среди ресурсов страниц
|
||||
Path pdf = convert(in);
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
int images = 0;
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources res = page.getResources();
|
||||
for (COSName name : res.getXObjectNames()) {
|
||||
if (res.isImageXObject(name)) {
|
||||
images++;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(images >= 1, "в PDF нет изображения");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Без настроенного slf4j docx4j печатает предупреждение прямо в PDF.
|
||||
* Мы подключаем slf4j-simple, поэтому текста быть не должно.
|
||||
*/
|
||||
@Test
|
||||
void noLoggingWarningInPdf() throws Exception {
|
||||
Path in = extractSample("ru-plain.docx");
|
||||
String text = pdfText(convert(in));
|
||||
|
||||
assertFalse(text.contains("TO HIDE THESE MESSAGES"),
|
||||
"в PDF попало предупреждение docx4j о логировании");
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidInputsRejected() {
|
||||
// Файла нет
|
||||
assertThrows(ConversionException.class, () ->
|
||||
WordPdfConverter.convert(Path.of("/tmp/no-such-file-xyz.docx")));
|
||||
|
||||
// Не .docx: создаём временный .doc и проверяем проверку расширения
|
||||
try {
|
||||
Path tmpDoc = Files.createTempFile("not-docx-", ".doc");
|
||||
assertThrows(ConversionException.class, () ->
|
||||
WordPdfConverter.convert(tmpDoc));
|
||||
} catch (IOException e) {
|
||||
fail(e);
|
||||
}
|
||||
|
||||
// null
|
||||
assertThrows(ConversionException.class, () ->
|
||||
WordPdfConverter.convert(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCreatesPdfNextToSource() throws Exception {
|
||||
Path in = extractSample("en-plain.docx");
|
||||
Path out = WordPdfConverter.convert(in);
|
||||
|
||||
// Ожидание считаем так же, как в реализации: убираем последнее
|
||||
// расширение (.docx) и добавляем .pdf
|
||||
String name = in.getFileName().toString();
|
||||
int dot = name.lastIndexOf('.');
|
||||
Path expected = in.resolveSibling(name.substring(0, dot) + ".pdf");
|
||||
|
||||
assertEquals(expected, out);
|
||||
assertTrue(Files.isRegularFile(out), "PDF не создан: " + out);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package ru.pjandro.wordpdf.fonts;
|
||||
|
||||
import org.docx4j.fonts.PhysicalFont;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Проверка бандл-шрифтов: файлы в jar, регистрация в docx4j.
|
||||
*/
|
||||
class BundledFontsTest {
|
||||
|
||||
/** Все файлы из списка должны присутствовать в classpath (resources/fonts/).
|
||||
* Путь — абсолютный (через classloader), не относительный к пакету класса. */
|
||||
@Test
|
||||
void listedFilesAreInClasspath() {
|
||||
for (BundledFonts.Entry e : BundledFonts.ENTRIES) {
|
||||
try (InputStream in = BundledFonts.class.getClassLoader()
|
||||
.getResourceAsStream("fonts/" + e.file())) {
|
||||
assertNotNull(in, "Шрифт отсутствует в classpath: fonts/" + e.file());
|
||||
} catch (IOException ioe) {
|
||||
fail("Не удалось прочитать шрифт " + e.file() + ": " + ioe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** И наоборот: все .ttf в resources/fonts/ есть в списке (защита от рассинхрона).
|
||||
* Работает, когда classpath — директория (surefire); в fat-jar тест не запускается. */
|
||||
@Test
|
||||
void listedFilesCoverAllTtfInResources() throws Exception {
|
||||
URL dir = BundledFonts.class.getClassLoader().getResource("fonts");
|
||||
assertNotNull(dir, "Каталог fonts/ не найден в classpath");
|
||||
assertTrue("file".equals(dir.getProtocol()),
|
||||
"Тест ожидает classpath-директорию (surefire)");
|
||||
|
||||
Set<String> actual = Files.list(Path.of(dir.toURI()))
|
||||
.map(p -> p.getFileName().toString())
|
||||
.filter(n -> n.toLowerCase().endsWith(".ttf"))
|
||||
.collect(Collectors.toSet());
|
||||
Set<String> listed = BundledFonts.ENTRIES.stream()
|
||||
.map(BundledFonts.Entry::file)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertEquals(actual, listed,
|
||||
"Список BundledFonts.ENTRIES рассинхронизирован с resources/fonts/");
|
||||
}
|
||||
|
||||
/** Каждый семейство имеет все четыре начертания. */
|
||||
@Test
|
||||
void allFamiliesHaveAllVariants() {
|
||||
for (String family : List.of("carlito", "caladea", "arimo", "tinos",
|
||||
"cousine", "dejavu sans", "dejavu serif")) {
|
||||
assertNotNull(BundledFonts.regular(family), family + ": regular");
|
||||
assertNotNull(BundledFonts.bold(family), family + ": bold");
|
||||
assertNotNull(BundledFonts.italic(family), family + ": italic");
|
||||
assertNotNull(BundledFonts.boldItalic(family), family + ": bolditalic");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Зарегистрированные шрифты берутся из нашего временного каталога
|
||||
* (из jar), а не из системных — это требование «самодостаточности».
|
||||
*/
|
||||
@Test
|
||||
void registeredFontsComeFromBundledFiles() {
|
||||
for (String family : List.of("carlito", "dejavu sans")) {
|
||||
PhysicalFont pf = BundledFonts.regular(family);
|
||||
assertNotNull(pf);
|
||||
assertTrue(pf.getEmbeddedURI().toString().contains("wordpdf-fonts-"),
|
||||
family + ": шрифт не из бандл-каталога: " + pf.getEmbeddedURI());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Порядок инициализации: сначала маппер (его статический init
|
||||
* обнаруживает системные шрифты), затем бандл-шрифты поверх.
|
||||
* После этого маппер должен маппить «Calibri» на наш Carlito.
|
||||
*/
|
||||
@Test
|
||||
void mapperMapsCommonMsFontsToBundledOnes() throws Exception {
|
||||
BundledFontMapper mapper = new BundledFontMapper();
|
||||
BundledFonts.init();
|
||||
|
||||
// populateFontMappings вызывается при setFontMapper; проверяем
|
||||
// итоговое состояние через публичный get()
|
||||
java.util.Set<String> names = new java.util.HashSet<>(List.of(
|
||||
"Calibri", "Times New Roman", "Arial", "Cousine", "UnknownExoticFont"));
|
||||
// wmlFonts не может быть null (super обращается к getFont()),
|
||||
// поэтому — пустой объект (как у документа без fontTable)
|
||||
org.docx4j.wml.Fonts wmlFonts = new org.docx4j.wml.Fonts();
|
||||
mapper.populateFontMappings(names, wmlFonts);
|
||||
|
||||
assertEquals(BundledFonts.regular("carlito"), mapper.get("Calibri"),
|
||||
"Calibri -> Carlito");
|
||||
assertEquals(BundledFonts.regular("tinos"), mapper.get("Times New Roman"),
|
||||
"Times New Roman -> Tinos");
|
||||
assertEquals(BundledFonts.regular("arimo"), mapper.get("Arial"),
|
||||
"Arial -> Arimo");
|
||||
// Нераспознанный шрифт не остаётся без маппинга: либо Panose-
|
||||
// совпадение (super), либо fallback DejaVu Sans
|
||||
assertNotNull(mapper.get("UnknownExoticFont"),
|
||||
"неизвестный шрифт без маппинга");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
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 static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Нормализация w:val="off"/"on" в docx (docx4j теряет эти значения
|
||||
* при JAXB-разборе, см. DocxOnOffNormalizer).
|
||||
*/
|
||||
class DocxOnOffNormalizerTest {
|
||||
|
||||
private static final String DOCUMENT_XML =
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
+ "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
|
||||
+ "<w:body><w:p><w:r>"
|
||||
+ "<w:rPr><w:b w:val=\"off\"/><w:i w:val=\"off\"/><w:strike w:val=\"off\"/></w:rPr>"
|
||||
+ "<w:t>текст</w:t></w:r><w:r>"
|
||||
+ "<w:rPr><w:b w:val=\"on\"/><w:i/></w:rPr>"
|
||||
+ "<w:t>жирный</w:t></w:r></w:p></w:body></w:document>";
|
||||
|
||||
private static byte[] makeDocx(String documentXml) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
zos.putNextEntry(new ZipEntry("[Content_Types].xml"));
|
||||
zos.write("<Types w:val=\"off\"/>".getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
zos.putNextEntry(new ZipEntry("word/document.xml"));
|
||||
zos.write(documentXml.getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static String readEntry(byte[] zip, String name) throws IOException {
|
||||
try (ZipInputStream zis = new ZipInputStream(
|
||||
new java.io.ByteArrayInputStream(zip))) {
|
||||
ZipEntry e;
|
||||
while ((e = zis.getNextEntry()) != null) {
|
||||
if (e.getName().equals(name)) {
|
||||
return new String(zis.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AssertionError("нет записи " + name);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewritesOnOffInWordParts() throws Exception {
|
||||
byte[] result = DocxOnOffNormalizer.normalize(makeDocx(DOCUMENT_XML));
|
||||
|
||||
String document = readEntry(result, "word/document.xml");
|
||||
assertFalse(document.contains("w:val=\"off\""), "остался off: " + document);
|
||||
assertFalse(document.contains("w:val=\"on\""), "остался on: " + document);
|
||||
assertTrue(document.contains("<w:b w:val=\"false\"/>"), "b не стал false: " + document);
|
||||
assertTrue(document.contains("<w:i w:val=\"false\"/>"), "i не стал false: " + document);
|
||||
assertTrue(document.contains("<w:strike w:val=\"false\"/>"), "strike не стал false: " + document);
|
||||
// <w:b w:val="on"/> -> "true"; <w:i/> (без val) не трогается
|
||||
assertTrue(document.contains("<w:b w:val=\"true\"/>"), "b не стал true: " + document);
|
||||
assertTrue(document.contains("<w:i/>"), "w:i без val изменён: " + document);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonWordPartsNotTouched() throws Exception {
|
||||
byte[] result = DocxOnOffNormalizer.normalize(makeDocx(DOCUMENT_XML));
|
||||
|
||||
// Часть вне word/*.xml остаётся как была (политика — трогать
|
||||
// только word/*.xml)
|
||||
assertEquals("<Types w:val=\"off\"/>", readEntry(result, "[Content_Types].xml"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noMatchesReturnsOriginalArray() throws Exception {
|
||||
byte[] docx = makeDocx("<w:document><w:b w:val=\"false\"/></w:document>");
|
||||
|
||||
assertSame(docx, DocxOnOffNormalizer.normalize(docx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleQuotesSupported() throws Exception {
|
||||
byte[] docx = makeDocx("<w:document><w:b w:val='off'/><w:i w:val='on'/></w:document>");
|
||||
|
||||
String document = readEntry(DocxOnOffNormalizer.normalize(docx), "word/document.xml");
|
||||
assertTrue(document.contains("<w:b w:val='false'/>"), "single-quote off: " + document);
|
||||
assertTrue(document.contains("<w:i w:val='true'/>"), "single-quote on: " + document);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewriteWithoutMatchesIsNull() {
|
||||
assertNull(DocxOnOffNormalizer.rewrite("<w:document><w:b/></w:document>"));
|
||||
assertNull(DocxOnOffNormalizer.rewrite("<w:b w:val=\"false\"/>"));
|
||||
assertNull(DocxOnOffNormalizer.rewrite("без атрибутов"));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user