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,77 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>ru.pjandro</groupId>
|
||||
<artifactId>java-word-pdf</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>wordpdf-cli</artifactId>
|
||||
<name>wordpdf-cli</name>
|
||||
<description>CLI: конвертация docx в PDF (fat-jar)</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>ru.pjandro</groupId>
|
||||
<artifactId>wordpdf-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- ============ Тесты ============ -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Готовые .docx для smoke-теста берутся из test-jar wordpdf-core -->
|
||||
<dependency>
|
||||
<groupId>ru.pjandro</groupId>
|
||||
<artifactId>wordpdf-core</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<classifier>tests</classifier>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- Fat-jar: все зависимости внутри, Main-Class в манифесте.
|
||||
Запуск: java -jar wordpdf-cli-1.0.0.jar file.docx [out.pdf] -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>ru.pjandro.wordpdf.cli.WordPdfCli</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
<!-- Подписанные jar-файлы ломает shade -->
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes>
|
||||
<exclude>META-INF/*.SF</exclude>
|
||||
<exclude>META-INF/*.DSA</exclude>
|
||||
<exclude>META-INF/*.RSA</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -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.
|
||||
*
|
||||
* Использование:
|
||||
* <pre>
|
||||
* java -jar wordpdf-cli-1.0.0.jar in.docx [in2.docx]
|
||||
* java -jar wordpdf-cli-1.0.0.jar in.docx out.pdf
|
||||
* </pre>
|
||||
*
|
||||
* <ul>
|
||||
* <li>один аргумент: рядом с файлом создаётся {@code <имя>.pdf};</li>
|
||||
* <li>два аргумента, второй — {@code .pdf}: конвертация в указанный файл;</li>
|
||||
* <li>два аргумента, второй — {@code .docx}: пакетная конвертация,
|
||||
* каждый исходник -> свой .pdf рядом с ним.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Коды возврата: 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 <file1.docx [file2.docx ...]>\n"
|
||||
+ " java -jar wordpdf-cli.jar <in.docx out.pdf>";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user