commit 76c251ddd983965804591ff502ce3a994eb60224 Author: Pjandro Date: Wed Sep 23 17:54:39 2026 +0000 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b328c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +# Maven +target/ +dependency-reduced-pom.xml + +# IDE +.idea/ +*.iml +.vscode/ +.classpath +.project +.settings/ + +# OS +.DS_Store +Thumbs.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..f6a5e09 --- /dev/null +++ b/README.md @@ -0,0 +1,125 @@ +# java-word-pdf + +Конвертация **docx → PDF** на чистом Java: `docx4j` + `Apache FOP`, без +LibreOffice/Aspose. Шрифты упакованы в jar — конвертация не зависит от +шрифтов, установленных в системе (работает «из коробки» на голом сервере). + +## Возможности + +- Поддержка RU/EN: кириллица и латиница встраиваются в PDF (embedded-подмножества). +- Самодостаточность: TTF выгружаются из jar в временный каталог и регистрируются + в docx4j/FOP. +- Частые MS-шрифты подменяются метрически совместимыми open-source аналогами + (см. «Шрифты» ниже). +- Клиентская библиотека (`wordpdf-core`) и CLI (`wordpdf-cli`, fat-jar). + +## Структура + +``` +java-word-pdf/ +├── wordpdf-core/ библиотека: конвертер, шрифты, маппинг +└── wordpdf-cli/ командная строка (fat-jar через maven-shade) +``` + +Ключевые классы (`wordpdf-core`): + +| Класс | Назначение | +|---|---| +| `ru.pjandro.wordpdf.WordPdfConverter` | публичный API: `convert(Path)` / `convert(Path, Path)` | +| `ru.pjandro.wordpdf.ConversionException` | исключение конвертации | +| `ru.pjandro.wordpdf.fonts.BundledFonts` | выгрузка TTF из jar и регистрация в docx4j | +| `ru.pjandro.wordpdf.fonts.BundledFontMapper` | маппинг имён шрифтов документа → TTF | +| `ru.pjandro.wordpdf.internal.DocxOnOffNormalizer` | нормализация `w:val="off"/"on"` перед загрузкой | +| `ru.pjandro.wordpdf.internal.FopFallbackFonts` | декларация fallback-семейства в FOP-конфиге | + +## Сборка + +Требуется **Java 17** и **Maven**. + +```bash +mvn clean verify # сборка всех модулей + тесты +mvn -pl wordpdf-cli package # только fat-jar CLI +``` + +Результат: `wordpdf-cli/target/wordpdf-cli-<версия>.jar` (fat-jar, все +зависимости внутри). + +## Использование + +### CLI + +```bash +java -jar wordpdf-cli-1.0.0.jar in.docx # рядом создаётся in.pdf +java -jar wordpdf-cli-1.0.0.jar in.docx out.pdf # в указанный файл +java -jar wordpdf-cli-1.0.0.jar a.docx b.docx # пакетно: каждый -> свой .pdf +``` + +Коды возврата: `0` — успех, `1` — ошибка использования, `2` — не удалось +конвертировать хотя бы один файл. + +### Библиотека + +```java +import ru.pjandro.wordpdf.WordPdfConverter; +import java.nio.file.Path; + +Path pdf = WordPdfConverter.convert(Path.of("doc.docx")); // doc.pdf рядом +WordPdfConverter.convert(Path.of("doc.docx"), Path.of("out.pdf")); // явный выход +``` + +Ошибки валидации (не `.docx`, файл не найден) бросают `ConversionException`. + +## Шрифты + +В `wordpdf-core/src/main/resources/fonts/` упакованы 28 TTF (по 4 начертания +на семейство): + +| Семейство | Аналог MS-шрифта | +|---|---| +| Carlito | Calibri | +| Caladea | Cambria | +| Arimo | Arial | +| Tinos | Times New Roman | +| Cousine | Courier New | +| DejaVu Sans / DejaVu Serif | fallback | + +`BundledFontMapper` подставляет метрически совместимые аналоги при конвертации +(`Calibri → Carlito` и т.д.). Нераспознанные шрифты и символы, не найденные в +шрифте ранa (em-dash «—», кавычки, U+2000–U+2EFF), падают в **DejaVu Sans** +(гарантированная кириллица). Все шрифты встраиваются в PDF как подмножества. + +### Лицензии шрифтов + +- Arimo, Cousine, Tinos, Carlito, Caladea — **SIL OFL 1.1** + (см. `fonts/FONT-LICENSE.txt`). +- DejaVu Sans / DejaVu Serif — **SIL OFL 1.1 / Bitstream Vera** + (см. `fonts/DejaVu-LICENSE.txt`). + +## Как это работает + +``` +docx ──> (нормализация w:val on/off) ──> docx4j (WordprocessingMLPackage) + ──> XSL-FO (XSLT) ──> Apache FOP ──> PDF (embedded-шрифты) +``` + +1. Байты `.docx` нормализуются (`DocxOnOffNormalizer`): docx4j 11.x теряет + атрибуты `w:val="off"/"on"` при JAXB-разборе, из-за чего regular-раны + могли рендериться жирным курсивом. +2. Документ загружается в `WordprocessingMLPackage`, привязывается + `BundledFontMapper`. +3. Экспорт в XSL-FO (XSLT-проход), затем `Apache FOP` рендерит PDF, встраивая + используемые подмножества шрифтов. + +## Ограничения + +- Это **не** pixel-perfect рендер Word: раскладка, поля и некоторые эффекты + приближённые (ограничения FOP/docx4j, а не «мы что-то упустили»). +- Символы U+2000–U+2EFF (em-dash и т.п.) рендерятся fallback-шрифтом DejaVu, + а не шрифтом самого ранa. +- Поддержка таблиц/изображений — базовая (через docx4j/FOP). + +## Тесты + +Тесты используют готовые `.docx` из `wordpdf-core/src/test/resources/samples/` +(генерируются POI) и проверяют извлечённый PDFBox'ом текст и встраивание +шрифтов. Запуск: `mvn test`. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..7a42f97 --- /dev/null +++ b/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + ru.pjandro + java-word-pdf + 1.0.0 + pom + + java-word-pdf + Конвертация docx в PDF (docx4j + Apache FOP, без LibreOffice/Aspose), шрифты в jar + + + wordpdf-core + wordpdf-cli + + + + 17 + 17 + UTF-8 + + + 11.5.3 + 2.0.17 + + + 5.12.2 + 3.0.7 + 5.5.1 + + + + + + org.docx4j + docx4j-core + ${docx4j.version} + + + + org.docx4j + docx4j-JAXB-ReferenceImpl + ${docx4j.version} + + + + org.docx4j + docx4j-export-fo + ${docx4j.version} + + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + + org.junit.jupiter + junit-jupiter + ${junit.version} + + + org.apache.pdfbox + pdfbox + ${pdfbox.version} + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.15.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.6 + + + -Djava.awt.headless=true + + + + org.apache.maven.plugins + maven-jar-plugin + 3.4.2 + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.2 + + + + + diff --git a/wordpdf-cli/pom.xml b/wordpdf-cli/pom.xml new file mode 100644 index 0000000..cd46cc2 --- /dev/null +++ b/wordpdf-cli/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + + ru.pjandro + java-word-pdf + 1.0.0 + + + wordpdf-cli + wordpdf-cli + CLI: конвертация docx в PDF (fat-jar) + + + + ru.pjandro + wordpdf-core + ${project.version} + + + + + org.junit.jupiter + junit-jupiter + test + + + + ru.pjandro + wordpdf-core + ${project.version} + tests + test-jar + test + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + ru.pjandro.wordpdf.cli.WordPdfCli + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + diff --git a/wordpdf-cli/src/main/java/ru/pjandro/wordpdf/cli/WordPdfCli.java b/wordpdf-cli/src/main/java/ru/pjandro/wordpdf/cli/WordPdfCli.java new file mode 100644 index 0000000..b9b3334 --- /dev/null +++ b/wordpdf-cli/src/main/java/ru/pjandro/wordpdf/cli/WordPdfCli.java @@ -0,0 +1,91 @@ +package ru.pjandro.wordpdf.cli; + +import ru.pjandro.wordpdf.ConversionException; +import ru.pjandro.wordpdf.WordPdfConverter; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Locale; + +/** + * Командная строка: конвертация docx в PDF. + * + * Использование: + *
+ *   java -jar wordpdf-cli-1.0.0.jar in.docx [in2.docx]
+ *   java -jar wordpdf-cli-1.0.0.jar in.docx out.pdf
+ * 
+ * + * + * + * Коды возврата: 0 — всё успешно, 1 — ошибка использования, + * 2 — не удалось конвертировать хотя бы один файл. + */ +public final class WordPdfCli { + + private WordPdfCli() { + } + + public static void main(String[] args) { + System.exit(run(args)); + } + + /** Точка входа без System.exit (удобно для тестов). + * + * @return код возврата (см. javadoc класса) + */ + public static int run(String[] args) { + if (args.length < 1 || args.length > 2) { + System.err.println(usage()); + return 1; + } + + boolean failed = false; + if (args.length == 2 && args[1].toLowerCase(Locale.ROOT).endsWith(".pdf")) { + // Два аргумента, второй — .pdf: явный выходной файл + failed |= !convertOne(Paths.get(args[0]), Paths.get(args[1])); + } else { + // Один входной, либо два .docx: каждый -> <имя>.pdf рядом с исходником + for (String in : args) { + failed |= !convertOne(Paths.get(in), null); + } + } + return failed ? 2 : 0; + } + + /** Конвертирует один файл и печатает результат. + * + * @param in входной .docx + * @param out выходной .pdf, или null (рядом с исходником) + * @return успех? + */ + private static boolean convertOne(Path in, Path out) { + try { + Path result; + if (out == null) { + result = WordPdfConverter.convert(in); + } else { + WordPdfConverter.convert(in, out); + result = out; + } + System.out.println(result + " — готово"); + return true; + } catch (ConversionException e) { + System.err.println(in + ": " + e.getMessage()); + return false; + } catch (Exception e) { + System.err.println(in + ": неожиданная ошибка: " + e); + return false; + } + } + + private static String usage() { + return "Использование: java -jar wordpdf-cli.jar \n" + + " java -jar wordpdf-cli.jar "; + } +} diff --git a/wordpdf-cli/src/test/java/ru/pjandro/wordpdf/cli/WordPdfCliTest.java b/wordpdf-cli/src/test/java/ru/pjandro/wordpdf/cli/WordPdfCliTest.java new file mode 100644 index 0000000..c2545a6 --- /dev/null +++ b/wordpdf-cli/src/test/java/ru/pjandro/wordpdf/cli/WordPdfCliTest.java @@ -0,0 +1,93 @@ +package ru.pjandro.wordpdf.cli; + +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Smoke-тест CLI. Готовый .docx берётся из test-jar wordpdf-core + * (classpath: samples/ru-plain.docx). + */ +class WordPdfCliTest { + + @Test + void usageErrors() { + assertEquals(1, WordPdfCli.run(new String[]{}), "нет аргументов"); + assertEquals(1, WordPdfCli.run(new String[]{"a.docx", "b.docx", "c.docx"}), + "слишком много аргументов"); + } + + @Test + void missingFileReturnsError() { + assertEquals(2, WordPdfCli.run(new String[]{"/tmp/no-such-file-xyz.docx"})); + } + + @Test + void convertsSampleWithExplicitOutput() throws Exception { + // Сэмпл из test-jar wordpdf-core + Path in = extractToTemp("samples/ru-plain.docx", "cli-in-"); + Path out = in.resolveSibling("cli-out.pdf"); + + int code = WordPdfCli.run(new String[]{in.toString(), out.toString()}); + + assertEquals(0, code, "CLI вернул ошибку"); + assertTrue(Files.isRegularFile(out), "PDF не создан"); + // Магический заголовок PDF + byte[] header = new byte[4]; + try (InputStream is = Files.newInputStream(out)) { + int read = is.readNBytes(header, 0, 4); + assertEquals(4, read); + } + assertEquals("%PDF", new String(header, StandardCharsets.US_ASCII)); + } + + @Test + void convertsSampleWithoutExplicitOutput() throws Exception { + // Выход = <имя без .docx>.pdf рядом с исходником + Path in = extractToTemp("samples/en-plain.docx", "cli-in2-"); + String name = in.getFileName().toString(); + int dot = name.lastIndexOf('.'); + Path expected = in.resolveSibling(name.substring(0, dot) + ".pdf"); + + int code = WordPdfCli.run(new String[]{in.toString()}); + + assertEquals(0, code, "CLI вернул ошибку"); + assertTrue(Files.isRegularFile(expected), "PDF не создан: " + expected); + } + + @Test + void batchConvertsBothInputs() throws Exception { + // Два .docx-аргумента = пакетная конвертация (не «вход/выход»): + // каждый исходник -> свой .pdf рядом + Path in1 = extractToTemp("samples/ru-plain.docx", "cli-b1-"); + Path in2 = extractToTemp("samples/en-plain.docx", "cli-b2-"); + + int code = WordPdfCli.run(new String[]{in1.toString(), in2.toString()}); + + assertEquals(0, code, "CLI вернул ошибку"); + for (Path in : List.of(in1, in2)) { + String name = in.getFileName().toString(); + int dot = name.lastIndexOf('.'); + Path expected = in.resolveSibling(name.substring(0, dot) + ".pdf"); + assertTrue(Files.isRegularFile(expected), "PDF не создан: " + expected); + } + } + + /** Выгружает ресурс (сэмпл) из classpath во временный файл. */ + private static Path extractToTemp(String resource, String prefix) throws Exception { + try (InputStream in = WordPdfCliTest.class.getClassLoader() + .getResourceAsStream(resource)) { + assertNotNull(in, "Нет ресурса: " + resource); + Path tmp = Files.createTempFile(prefix, ".docx"); + Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING); + return tmp; + } + } +} diff --git a/wordpdf-core/pom.xml b/wordpdf-core/pom.xml new file mode 100644 index 0000000..b097504 --- /dev/null +++ b/wordpdf-core/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + + ru.pjandro + java-word-pdf + 1.0.0 + + + wordpdf-core + wordpdf-core + Библиотека: конвертация docx в PDF (docx4j + FOP, шрифты внутри jar) + + + + + org.docx4j + docx4j-core + + + + org.docx4j + docx4j-JAXB-ReferenceImpl + + + + org.docx4j + docx4j-export-fo + + + + org.slf4j + slf4j-simple + + + + + org.junit.jupiter + junit-jupiter + test + + + + org.apache.pdfbox + pdfbox + test + + + + org.apache.poi + poi-ooxml + test + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + test-jar + + test-jar + + + + + + + diff --git a/wordpdf-core/src/main/java/ru/pjandro/wordpdf/ConversionException.java b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/ConversionException.java new file mode 100644 index 0000000..df32a8c --- /dev/null +++ b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/ConversionException.java @@ -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); + } +} diff --git a/wordpdf-core/src/main/java/ru/pjandro/wordpdf/WordPdfConverter.java b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/WordPdfConverter.java new file mode 100644 index 0000000..1dc3023 --- /dev/null +++ b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/WordPdfConverter.java @@ -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; + } +} diff --git a/wordpdf-core/src/main/java/ru/pjandro/wordpdf/fonts/BundledFontMapper.java b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/fonts/BundledFontMapper.java new file mode 100644 index 0000000..719101a --- /dev/null +++ b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/fonts/BundledFontMapper.java @@ -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 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 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 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 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)); + } +} diff --git a/wordpdf-core/src/main/java/ru/pjandro/wordpdf/fonts/BundledFonts.java b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/fonts/BundledFonts.java new file mode 100644 index 0000000..1a562c6 --- /dev/null +++ b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/fonts/BundledFonts.java @@ -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 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> 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 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); + } +} diff --git a/wordpdf-core/src/main/java/ru/pjandro/wordpdf/internal/DocxOnOffNormalizer.java b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/internal/DocxOnOffNormalizer.java new file mode 100644 index 0000000..7415dfc --- /dev/null +++ b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/internal/DocxOnOffNormalizer.java @@ -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 } и + * {@code } (так записывают, например, 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(); + } +} diff --git a/wordpdf-core/src/main/java/ru/pjandro/wordpdf/internal/FopFallbackFonts.java b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/internal/FopFallbackFonts.java new file mode 100644 index 0000000..132cc73 --- /dev/null +++ b/wordpdf-core/src/main/java/ru/pjandro/wordpdf/internal/FopFallbackFonts.java @@ -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); + } +} diff --git a/wordpdf-core/src/main/resources/fonts/Arimo-Bold.ttf b/wordpdf-core/src/main/resources/fonts/Arimo-Bold.ttf new file mode 100644 index 0000000..d901b99 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Arimo-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Arimo-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/Arimo-BoldItalic.ttf new file mode 100644 index 0000000..0e076d6 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Arimo-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Arimo-Italic.ttf b/wordpdf-core/src/main/resources/fonts/Arimo-Italic.ttf new file mode 100644 index 0000000..4c117b1 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Arimo-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Arimo-Regular.ttf b/wordpdf-core/src/main/resources/fonts/Arimo-Regular.ttf new file mode 100644 index 0000000..42ad964 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Arimo-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Caladea-Bold.ttf b/wordpdf-core/src/main/resources/fonts/Caladea-Bold.ttf new file mode 100644 index 0000000..a4a9703 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Caladea-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Caladea-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/Caladea-BoldItalic.ttf new file mode 100644 index 0000000..a9bb487 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Caladea-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Caladea-Italic.ttf b/wordpdf-core/src/main/resources/fonts/Caladea-Italic.ttf new file mode 100644 index 0000000..2c910c6 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Caladea-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Caladea-Regular.ttf b/wordpdf-core/src/main/resources/fonts/Caladea-Regular.ttf new file mode 100644 index 0000000..a490e8f Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Caladea-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Carlito-Bold.ttf b/wordpdf-core/src/main/resources/fonts/Carlito-Bold.ttf new file mode 100644 index 0000000..67543b5 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Carlito-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Carlito-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/Carlito-BoldItalic.ttf new file mode 100644 index 0000000..e2c5d88 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Carlito-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Carlito-Italic.ttf b/wordpdf-core/src/main/resources/fonts/Carlito-Italic.ttf new file mode 100644 index 0000000..8dc3c84 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Carlito-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Carlito-Regular.ttf b/wordpdf-core/src/main/resources/fonts/Carlito-Regular.ttf new file mode 100644 index 0000000..427b959 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Carlito-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Cousine-Bold.ttf b/wordpdf-core/src/main/resources/fonts/Cousine-Bold.ttf new file mode 100644 index 0000000..2a67f91 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Cousine-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Cousine-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/Cousine-BoldItalic.ttf new file mode 100644 index 0000000..3216410 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Cousine-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Cousine-Italic.ttf b/wordpdf-core/src/main/resources/fonts/Cousine-Italic.ttf new file mode 100644 index 0000000..d998492 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Cousine-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Cousine-Regular.ttf b/wordpdf-core/src/main/resources/fonts/Cousine-Regular.ttf new file mode 100644 index 0000000..644bc1c Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Cousine-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVu-LICENSE.txt b/wordpdf-core/src/main/resources/fonts/DejaVu-LICENSE.txt new file mode 100644 index 0000000..df52c17 --- /dev/null +++ b/wordpdf-core/src/main/resources/fonts/DejaVu-LICENSE.txt @@ -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$ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSans-Bold.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSans-Bold.ttf new file mode 100644 index 0000000..6d65fa7 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSans-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSans-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSans-BoldItalic.ttf new file mode 100644 index 0000000..753f2d8 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSans-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSans-Italic.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSans-Italic.ttf new file mode 100644 index 0000000..999bac7 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSans-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSans-Regular.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSans-Regular.ttf new file mode 100644 index 0000000..e5f7eec Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSans-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Bold.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Bold.ttf new file mode 100644 index 0000000..3bb755f Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSerif-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-BoldItalic.ttf new file mode 100644 index 0000000..a36dd4b Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Italic.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Italic.ttf new file mode 100644 index 0000000..805daf2 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Regular.ttf b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Regular.ttf new file mode 100644 index 0000000..0b803d2 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/DejaVuSerif-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/FONT-LICENSE.txt b/wordpdf-core/src/main/resources/fonts/FONT-LICENSE.txt new file mode 100644 index 0000000..4e48755 --- /dev/null +++ b/wordpdf-core/src/main/resources/fonts/FONT-LICENSE.txt @@ -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. + +Все шрифты свободно распространяемы и поддерживают кириллицу. diff --git a/wordpdf-core/src/main/resources/fonts/Tinos-Bold.ttf b/wordpdf-core/src/main/resources/fonts/Tinos-Bold.ttf new file mode 100644 index 0000000..1dee731 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Tinos-Bold.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Tinos-BoldItalic.ttf b/wordpdf-core/src/main/resources/fonts/Tinos-BoldItalic.ttf new file mode 100644 index 0000000..6073bad Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Tinos-BoldItalic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Tinos-Italic.ttf b/wordpdf-core/src/main/resources/fonts/Tinos-Italic.ttf new file mode 100644 index 0000000..a914356 Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Tinos-Italic.ttf differ diff --git a/wordpdf-core/src/main/resources/fonts/Tinos-Regular.ttf b/wordpdf-core/src/main/resources/fonts/Tinos-Regular.ttf new file mode 100644 index 0000000..0cdaaca Binary files /dev/null and b/wordpdf-core/src/main/resources/fonts/Tinos-Regular.ttf differ diff --git a/wordpdf-core/src/main/resources/slf4j-simple.properties b/wordpdf-core/src/main/resources/slf4j-simple.properties new file mode 100644 index 0000000..19edd25 --- /dev/null +++ b/wordpdf-core/src/main/resources/slf4j-simple.properties @@ -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 diff --git a/wordpdf-core/src/test/java/ru/pjandro/wordpdf/SampleDocxGenerator.java b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/SampleDocxGenerator.java new file mode 100644 index 0000000..5e5e7a4 --- /dev/null +++ b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/SampleDocxGenerator.java @@ -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 не генерируют. + * + * Пересоздать (если нужно): + *
+ *   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
+ * 
+ */ +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() + " байт)"); + } +} diff --git a/wordpdf-core/src/test/java/ru/pjandro/wordpdf/WordPdfConverterTest.java b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/WordPdfConverterTest.java new file mode 100644 index 0000000..aa9f123 --- /dev/null +++ b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/WordPdfConverterTest.java @@ -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 embeddedFontNames(Path pdf) throws IOException { + Set 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 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 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); + } +} diff --git a/wordpdf-core/src/test/java/ru/pjandro/wordpdf/fonts/BundledFontsTest.java b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/fonts/BundledFontsTest.java new file mode 100644 index 0000000..5acb68e --- /dev/null +++ b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/fonts/BundledFontsTest.java @@ -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 actual = Files.list(Path.of(dir.toURI())) + .map(p -> p.getFileName().toString()) + .filter(n -> n.toLowerCase().endsWith(".ttf")) + .collect(Collectors.toSet()); + Set 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 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"), + "неизвестный шрифт без маппинга"); + } +} diff --git a/wordpdf-core/src/test/java/ru/pjandro/wordpdf/internal/DocxOnOffNormalizerTest.java b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/internal/DocxOnOffNormalizerTest.java new file mode 100644 index 0000000..8f68162 --- /dev/null +++ b/wordpdf-core/src/test/java/ru/pjandro/wordpdf/internal/DocxOnOffNormalizerTest.java @@ -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 = + "" + + "" + + "" + + "" + + "текст" + + "" + + "жирный"; + + 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("".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(""), "b не стал false: " + document); + assertTrue(document.contains(""), "i не стал false: " + document); + assertTrue(document.contains(""), "strike не стал false: " + document); + // -> "true"; (без val) не трогается + assertTrue(document.contains(""), "b не стал true: " + document); + assertTrue(document.contains(""), "w:i без val изменён: " + document); + } + + @Test + void nonWordPartsNotTouched() throws Exception { + byte[] result = DocxOnOffNormalizer.normalize(makeDocx(DOCUMENT_XML)); + + // Часть вне word/*.xml остаётся как была (политика — трогать + // только word/*.xml) + assertEquals("", readEntry(result, "[Content_Types].xml")); + } + + @Test + void noMatchesReturnsOriginalArray() throws Exception { + byte[] docx = makeDocx(""); + + assertSame(docx, DocxOnOffNormalizer.normalize(docx)); + } + + @Test + void singleQuotesSupported() throws Exception { + byte[] docx = makeDocx(""); + + String document = readEntry(DocxOnOffNormalizer.normalize(docx), "word/document.xml"); + assertTrue(document.contains(""), "single-quote off: " + document); + assertTrue(document.contains(""), "single-quote on: " + document); + } + + @Test + void rewriteWithoutMatchesIsNull() { + assertNull(DocxOnOffNormalizer.rewrite("")); + assertNull(DocxOnOffNormalizer.rewrite("")); + assertNull(DocxOnOffNormalizer.rewrite("без атрибутов")); + } +} diff --git a/wordpdf-core/src/test/resources/samples/en-plain.docx b/wordpdf-core/src/test/resources/samples/en-plain.docx new file mode 100644 index 0000000..c0a7fbd Binary files /dev/null and b/wordpdf-core/src/test/resources/samples/en-plain.docx differ diff --git a/wordpdf-core/src/test/resources/samples/ru-en-mixed.docx b/wordpdf-core/src/test/resources/samples/ru-en-mixed.docx new file mode 100644 index 0000000..3a2a864 Binary files /dev/null and b/wordpdf-core/src/test/resources/samples/ru-en-mixed.docx differ diff --git a/wordpdf-core/src/test/resources/samples/ru-plain.docx b/wordpdf-core/src/test/resources/samples/ru-plain.docx new file mode 100644 index 0000000..2261b21 Binary files /dev/null and b/wordpdf-core/src/test/resources/samples/ru-plain.docx differ diff --git a/wordpdf-core/src/test/resources/samples/ru-table-image.docx b/wordpdf-core/src/test/resources/samples/ru-table-image.docx new file mode 100644 index 0000000..07e0ffa Binary files /dev/null and b/wordpdf-core/src/test/resources/samples/ru-table-image.docx differ diff --git a/wordpdf-core/src/test/resources/samples/ru-times.docx b/wordpdf-core/src/test/resources/samples/ru-times.docx new file mode 100644 index 0000000..7465284 Binary files /dev/null and b/wordpdf-core/src/test/resources/samples/ru-times.docx differ