feat: конвертация бинарного .doc (Word 97-2003) в PDF (POI HWPF + FOP)
This commit is contained in:
@@ -16,6 +16,7 @@ import ru.pjandro.wordpdf.internal.FieldNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.GlyphCoverageNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.FopFallbackFonts;
|
||||
import ru.pjandro.wordpdf.internal.StrictOoxmlNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.DocToPdfRenderer;
|
||||
import ru.pjandro.wordpdf.internal.SymbolFontNormalizer;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
@@ -54,8 +55,9 @@ public final class WordPdfConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертирует байты .docx в PDF. Работа с файлами — забота вызывающего
|
||||
* (файловое API было здесь раньше; ядро пути не принимает).
|
||||
* Конвертирует байты .docx (или бинарного .doc Word 97-2003 — ветка
|
||||
* выбирается по магическому байту контейнера) в PDF. Работа с файлами — забота
|
||||
* вызывающего (файловое API было здесь раньше; ядро пути не принимает).
|
||||
*
|
||||
* <p>Вход проверяется валидатором до рендера: {@link WordPdfValidator#checkInput(byte[])}
|
||||
* (null / больше {@link WordPdfSettings#MAX_INPUT_BYTES}), затем число страниц
|
||||
@@ -108,6 +110,16 @@ public final class WordPdfConverter {
|
||||
*/
|
||||
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
||||
OutputStream os) throws Exception {
|
||||
// 0. Бинарный .doc (Word 97-2003, OLE2-контейнер) — отдельная
|
||||
// ветка: docx4j его не читает, нормализаторы (все — по zip-частям
|
||||
// docx) тут бессмысленны. Флаги renderCharts/renderSmartArt/
|
||||
// errorOn* для .doc — no-op: диаграмм как c:chart в .doc нет,
|
||||
// превью встраиваемых объектов приходят картинками через
|
||||
// PicturesManager (см. internal/DocToPdfRenderer).
|
||||
if (isOle2(rawDocxBytes)) {
|
||||
DocToPdfRenderer.render(rawDocxBytes, title, options, os);
|
||||
return;
|
||||
}
|
||||
// 1. Маппер шрифтов. Порядок важен: конструктор запускает
|
||||
// обнаружение системных шрифтов, затем бандл-шрифты из jar
|
||||
// регистрируются поверх них (имеют приоритет).
|
||||
@@ -181,4 +193,13 @@ public final class WordPdfConverter {
|
||||
// пакет загружается в память и ничего не закрывает.
|
||||
}
|
||||
}
|
||||
|
||||
/** Магик OLE2 (CFB): {@code D0 CF 11 E0 A1 B1 1A E1} — контейнер .doc. */
|
||||
private static boolean isOle2(byte[] bytes) {
|
||||
return bytes != null && bytes.length >= 8
|
||||
&& (bytes[0] & 0xFF) == 0xD0 && (bytes[1] & 0xFF) == 0xCF
|
||||
&& (bytes[2] & 0xFF) == 0x11 && (bytes[3] & 0xFF) == 0xE0
|
||||
&& (bytes[4] & 0xFF) == 0xA1 && (bytes[5] & 0xFF) == 0xB1
|
||||
&& (bytes[6] & 0xFF) == 0x1A && (bytes[7] & 0xFF) == 0xE1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package ru.pjandro.wordpdf;
|
||||
|
||||
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
|
||||
import org.apache.poi.hwpf.HWPFDocument;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.apache.poi.ddf.EscherRecordTypes;
|
||||
import org.docx4j.wml.Br;
|
||||
import org.docx4j.wml.ContentAccessor;
|
||||
import org.docx4j.wml.P;
|
||||
@@ -153,6 +156,44 @@ public final class WordPdfValidator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет число страниц бинарного .doc (Word 97-2003) по кэшу
|
||||
* {@code SummaryInformation.PageCount} — аналогу {@code docProps/app.xml}
|
||||
* в docx-пути: Word переписывает его при сохранении, пост-рендерной
|
||||
* проверки нет осознанно (как в docx-ветке — доверяем кэшу до рендера).
|
||||
* Кэш пуст или ноль — проверка пропускается (посчитать дёшево нельзя,
|
||||
* отвергать валидный документ по отсутствию кэша неправильно).
|
||||
*
|
||||
* @throws ConversionException при {@code null}, ошибке разбора OLE2 или превышении {@link WordPdfSettings#MAX_PAGES}
|
||||
*/
|
||||
public static void checkDocPageCountLightweight(byte[] docBytes) throws ConversionException {
|
||||
checkDocPageCountLightweight(docBytes, WordPdfSettings.MAX_PAGES);
|
||||
}
|
||||
|
||||
/**
|
||||
* То же, что {@link #checkDocPageCountLightweight(byte[])}, с явным
|
||||
* лимитом страниц (переопределение на вызов, см. {@link ConvertOptions#maxPages()}).
|
||||
*
|
||||
* @throws ConversionException при {@code null}, ошибке разбора OLE2 или превышении {@code maxPages}
|
||||
*/
|
||||
public static void checkDocPageCountLightweight(byte[] docBytes, int maxPages) throws ConversionException {
|
||||
if (docBytes == null) {
|
||||
throw new ConversionException("Не указаны байты входного .doc");
|
||||
}
|
||||
int pages;
|
||||
try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(docBytes));
|
||||
HWPFDocument hwpf = new HWPFDocument(fs)) {
|
||||
org.apache.poi.hpsf.SummaryInformation si = hwpf.getSummaryInformation();
|
||||
pages = si == null ? 0 : si.getPageCount();
|
||||
} catch (IOException | RuntimeException e) {
|
||||
throw new ConversionException("Не удалось разобрать байты .doc", e);
|
||||
}
|
||||
if (pages > maxPages) {
|
||||
throw new ConversionException("Документ длиннее " + maxPages
|
||||
+ " страниц: получено не менее " + pages);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Считает страницы .docx в байтах и проверяет лимит.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,759 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.apache.fop.apps.FOUserAgent;
|
||||
import org.apache.fop.apps.Fop;
|
||||
import org.apache.fop.apps.FopFactory;
|
||||
import org.apache.fop.apps.MimeConstants;
|
||||
import org.apache.poi.hwpf.HWPFDocument;
|
||||
import org.apache.poi.hwpf.converter.FontReplacer;
|
||||
import org.apache.poi.hwpf.converter.PicturesManager;
|
||||
import org.apache.poi.hwpf.converter.WordToFoConverter;
|
||||
import org.apache.poi.hwpf.usermodel.CharacterRun;
|
||||
import org.apache.poi.hwpf.usermodel.HeaderStories;
|
||||
import org.apache.poi.hwpf.usermodel.Paragraph;
|
||||
import org.apache.poi.hwpf.usermodel.PictureType;
|
||||
import org.apache.poi.hwpf.usermodel.Range;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import ru.pjandro.wordpdf.ConversionException;
|
||||
import ru.pjandro.wordpdf.ConvertOptions;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.sax.SAXResult;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Рендер бинарного .doc (Word 97-2003, OLE2) в PDF: POI HWPF -> XSL-FO ->
|
||||
* Apache FOP (тот же форк, что в docx-ветке).
|
||||
*
|
||||
* <p>docx4j бинарный формат не читает, HWPF->XWPF конвертера в POI нет —
|
||||
* поэтому для .doc отдельная ветка: {@link WordToFoConverter} строит FO
|
||||
* из HWPF-модели напрямую, а колонтитулы (которые POI в FO не пишет)
|
||||
* дописываются в FO-DOM по {@link HeaderStories}.
|
||||
*
|
||||
* <p>Известная деградация против Word (принята): дрейф вёрстки (FO POI
|
||||
* беднее docx4j-экспорта), шрифты — бандл-аналоги, колонтитулы — по
|
||||
* одной (odd) истории на секцию, first/even-варианты — эвристикой
|
||||
* «непустая история => вариант» (флаги titlePg/evenAndOdd POI не отдаёт).
|
||||
* Флаги {@code renderCharts}/{@code renderSmartArt} для .doc — no-op:
|
||||
* диаграмм как {@code c:chart} в .doc нет, превью встраиваемых объектов
|
||||
* приходят картинками через {@link PicturesManager}.
|
||||
*/
|
||||
public final class DocToPdfRenderer {
|
||||
|
||||
private DocToPdfRenderer() {
|
||||
}
|
||||
|
||||
private static final String FO_NS = "http://www.w3.org/1999/XSL/Format";
|
||||
|
||||
/** Маркеры полей Word в тексте HWPF-ранов. */
|
||||
private static final char FIELD_BEGIN = '\u0013';
|
||||
private static final char FIELD_SEPARATOR = '\u0014';
|
||||
private static final char FIELD_END = '\u0015';
|
||||
/** Маркер конца секции в историях колонтитулов. */
|
||||
private static final char SECTION_END = '\u000c';
|
||||
/** Конец абзаца / конец ячейки таблицы в тексте HWPF. */
|
||||
private static final char PARA_END = '\r';
|
||||
private static final char CELL_END = '\u0007';
|
||||
|
||||
/** Зазор между текстом колонтитула и областью контента. */
|
||||
private static final double REGION_GAP_IN = 0.15;
|
||||
|
||||
|
||||
/**
|
||||
* Полный путь .doc -> PDF в поток. Все ошибки — {@link ConversionException}.
|
||||
*
|
||||
* @param docBytes байты OLE2 (.doc)
|
||||
* @param title заголовок PDF (метаданные); {@code null}/пустая — не задаётся
|
||||
* @param options настройки вызова (для .doc флаги рисования — no-op)
|
||||
* @param out приёмник байтов PDF
|
||||
*/
|
||||
public static void render(byte[] docBytes, String title, ConvertOptions options,
|
||||
OutputStream out) throws ConversionException {
|
||||
Path workDir = null;
|
||||
try {
|
||||
// init() идемпотентен; restrictToBundled() не нужен — FOP-конфиг
|
||||
// строится явно (auto-detect="false"), системные шрифты в него не попадают.
|
||||
BundledFonts.init();
|
||||
workDir = Files.createTempDirectory("wordpdf-doc-");
|
||||
Path picsDir = Files.createDirectory(workDir.resolve("pics"));
|
||||
|
||||
Document foDoc;
|
||||
try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(docBytes));
|
||||
HWPFDocument hwpf = new HWPFDocument(fs)) {
|
||||
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
Document dom = dbf.newDocumentBuilder().newDocument();
|
||||
WordToFoConverter converter = new WordToFoConverter(dom);
|
||||
converter.setFontReplacer(DocToPdfRenderer::replaceFont);
|
||||
converter.setPicturesManager(new TempPictures(picsDir));
|
||||
converter.processDocument(hwpf);
|
||||
foDoc = converter.getDocument();
|
||||
applyDefaultFont(foDoc);
|
||||
|
||||
injectHeadersAndFooters(foDoc, hwpf);
|
||||
}
|
||||
|
||||
renderFo(foDoc, title, workDir, out);
|
||||
} catch (ConversionException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new ConversionException("Не удалось конвертировать документ .doc", e);
|
||||
} finally {
|
||||
if (workDir != null) {
|
||||
deleteRecursively(workDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Шрифты ====================
|
||||
|
||||
/**
|
||||
* Замена шрифта ранa на бандл-аналог: имя из name-таблицы TTF
|
||||
* regular-варианта (тот же механизм triplet-имён, что в
|
||||
* {@link FopFallbackFonts}) — FO запрашивает именно его.
|
||||
*/
|
||||
private static FontReplacer.Triplet replaceFont(FontReplacer.Triplet t) {
|
||||
String family = BundledFontMapper.bundledFamily(
|
||||
t.fontName == null ? "" : t.fontName);
|
||||
var regular = BundledFonts.regular(family);
|
||||
if (regular != null) {
|
||||
t.fontName = regular.getName();
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Картинки во временный каталог; FO ссылается на них file:-URI. */
|
||||
private static final class TempPictures implements PicturesManager {
|
||||
private final Path dir;
|
||||
|
||||
TempPictures(Path dir) {
|
||||
this.dir = dir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String savePicture(byte[] content, PictureType pictureType,
|
||||
String suggestedName, float widthInches, float heightInches) {
|
||||
try {
|
||||
if (content == null || content.length == 0) {
|
||||
// пустой объект (напр. превью удалённого рисунка) — FOP
|
||||
// падает на нём с EOFException, ссылка не нужна
|
||||
return null;
|
||||
}
|
||||
String name = suggestedName == null ? "" :
|
||||
suggestedName.replaceAll("[^A-Za-z0-9._-]", "_");
|
||||
if (name.isEmpty()) {
|
||||
String ext = pictureType == null
|
||||
? PictureType.UNKNOWN.getExtension()
|
||||
: pictureType.getExtension();
|
||||
name = "pic-" + java.util.Arrays.hashCode(content) + "." + ext;
|
||||
}
|
||||
Path file = dir.resolve(name);
|
||||
Files.write(file, content);
|
||||
return file.toUri().toString();
|
||||
} catch (IOException e) {
|
||||
// деградация вместо падения: картинка без ссылки просто исчезнет
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Колонтитулы ====================
|
||||
|
||||
/**
|
||||
* POI не пишет колонтитулы в FO. Достаём их из {@link HeaderStories},
|
||||
* разбиваем на чанки по секциям (маркер конца секции {@code \u000c}) и
|
||||
* вставляем в FO-DOM: {@code fo:region-before}/{@code fo:region-after}
|
||||
* в мастер + {@code fo:static-content} в page-sequence.
|
||||
*/
|
||||
private static void injectHeadersAndFooters(Document foDoc, HWPFDocument hwpf) {
|
||||
NodeList sequences = foDoc.getElementsByTagNameNS(FO_NS, "page-sequence");
|
||||
if (sequences.getLength() == 0) {
|
||||
return;
|
||||
}
|
||||
HeaderStories hs = new HeaderStories(hwpf);
|
||||
// Императивный список: javac 21 не выводит T для List.of/Arrays.asList
|
||||
// из вложенных дженерик-аргументов (varargs inference).
|
||||
List<List<List<Paragraph>>> stories = new ArrayList<>();
|
||||
stories.add(chunkBySection(hs.getOddHeaderSubrange(), sequences.getLength()));
|
||||
stories.add(chunkBySection(hs.getEvenHeaderSubrange(), sequences.getLength()));
|
||||
stories.add(chunkBySection(hs.getFirstHeaderSubrange(), sequences.getLength()));
|
||||
stories.add(chunkBySection(hs.getOddFooterSubrange(), sequences.getLength()));
|
||||
stories.add(chunkBySection(hs.getEvenFooterSubrange(), sequences.getLength()));
|
||||
stories.add(chunkBySection(hs.getFirstFooterSubrange(), sequences.getLength()));
|
||||
|
||||
// NUMPAGES/SECTIONPAGES -> citation-last по ПОСЛЕДНЕМУ мастеру
|
||||
// документа: нумерация FOP между page-sequence непрерывна.
|
||||
String lastMaster = ((Element) sequences.item(sequences.getLength() - 1))
|
||||
.getAttribute("master-reference");
|
||||
for (int i = 0; i < sequences.getLength(); i++) {
|
||||
Element seq = (Element) sequences.item(i);
|
||||
String masterName = seq.getAttribute("master-reference");
|
||||
Element master = findMaster(foDoc, masterName);
|
||||
if (master == null) {
|
||||
continue;
|
||||
}
|
||||
String[] margins = parseMarginShorthand(master);
|
||||
if (margins == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Форк FOP (docx4j-fo-renderer) вырезал PageMaster.setupRegions:
|
||||
// viewport region-body = page-area минус СОБСТВЕННЫЕ margin'ы
|
||||
// body, extent'ы region-before/after body не вычитаются. Поэтому
|
||||
// margin'ы region-body (шортхэнд POI = Word-поля) сохраняются —
|
||||
// единственная защита от наезда текста на колонтитулы; extent'ы
|
||||
// регионов только размещают сами колонтитулы.
|
||||
// Порядок детей simple-page-master: body -> before -> after
|
||||
// (требование валидации форка).
|
||||
if (hasText(stories.get(0).get(i))) {
|
||||
appendRegion(master, "region-before", margins[0], "after");
|
||||
insertStaticContent(seq, "xsl-region-before",
|
||||
blocks(foDoc, stories.get(0).get(i), lastMaster), "margin-bottom");
|
||||
}
|
||||
if (hasText(stories.get(3).get(i))) {
|
||||
appendRegion(master, "region-after", margins[2], "before");
|
||||
insertStaticContent(seq, "xsl-region-after",
|
||||
blocks(foDoc, stories.get(3).get(i), lastMaster), "margin-top");
|
||||
}
|
||||
|
||||
// first/even — эвристика: непустая история => вариант существует.
|
||||
boolean hasFirst = hasText(stories.get(2).get(i)) || hasText(stories.get(5).get(i));
|
||||
boolean hasEven = hasText(stories.get(1).get(i)) || hasText(stories.get(4).get(i));
|
||||
if (!hasFirst && !hasEven) {
|
||||
continue;
|
||||
}
|
||||
List<Element> variants = new ArrayList<>();
|
||||
if (hasFirst) {
|
||||
Element clone = (Element) master.cloneNode(true);
|
||||
String name = masterName + "-first";
|
||||
clone.setAttribute("master-name", name);
|
||||
renameRegionFlows(clone, "-first");
|
||||
foDoc.getDocumentElement().insertBefore(clone, master.getNextSibling());
|
||||
if (hasText(stories.get(2).get(i))) {
|
||||
insertStaticContent(seq, "xsl-region-before-first",
|
||||
blocks(foDoc, stories.get(2).get(i), lastMaster), "margin-bottom");
|
||||
}
|
||||
if (hasText(stories.get(5).get(i))) {
|
||||
insertStaticContent(seq, "xsl-region-after-first",
|
||||
blocks(foDoc, stories.get(5).get(i), lastMaster), "margin-top");
|
||||
}
|
||||
variants.add(clone);
|
||||
}
|
||||
if (hasEven) {
|
||||
Element clone = (Element) master.cloneNode(true);
|
||||
String name = masterName + "-even";
|
||||
clone.setAttribute("master-name", name);
|
||||
renameRegionFlows(clone, "-even");
|
||||
foDoc.getDocumentElement().insertBefore(clone, master.getNextSibling());
|
||||
if (hasText(stories.get(1).get(i))) {
|
||||
insertStaticContent(seq, "xsl-region-before-even",
|
||||
blocks(foDoc, stories.get(1).get(i), lastMaster), "margin-bottom");
|
||||
}
|
||||
if (hasText(stories.get(4).get(i))) {
|
||||
insertStaticContent(seq, "xsl-region-after-even",
|
||||
blocks(foDoc, stories.get(4).get(i), lastMaster), "margin-top");
|
||||
}
|
||||
variants.add(clone);
|
||||
}
|
||||
wrapInPageSequenceMaster(foDoc, master, variants);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* История колонтитулов — конкатенация одноимённых историй всех секций;
|
||||
* конец секции помечен {@code \u000c} в последнем параграфе. Чанков не
|
||||
* столько, сколько секций — деградация: один чанк раздаётся всем.
|
||||
*/
|
||||
private static List<List<Paragraph>> chunkBySection(Range story, int sectionCount) {
|
||||
List<List<Paragraph>> chunks = new ArrayList<>();
|
||||
if (story != null && story.numParagraphs() > 0) {
|
||||
List<Paragraph> current = new ArrayList<>();
|
||||
for (int i = 0; i < story.numParagraphs(); i++) {
|
||||
Paragraph p;
|
||||
String text;
|
||||
try {
|
||||
p = story.getParagraph(i);
|
||||
text = p.text();
|
||||
} catch (RuntimeException e) {
|
||||
continue;
|
||||
}
|
||||
current.add(p);
|
||||
if (text != null && text.indexOf(SECTION_END) >= 0) {
|
||||
chunks.add(current);
|
||||
current = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
if (!current.isEmpty()) {
|
||||
chunks.add(current);
|
||||
}
|
||||
}
|
||||
if (chunks.isEmpty()) {
|
||||
for (int i = 0; i < sectionCount; i++) {
|
||||
chunks.add(null);
|
||||
}
|
||||
} else if (chunks.size() != sectionCount) {
|
||||
List<Paragraph> first = chunks.get(0);
|
||||
chunks = new ArrayList<>();
|
||||
for (int i = 0; i < sectionCount; i++) {
|
||||
chunks.add(first);
|
||||
}
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
private static Element findMaster(Document foDoc, String masterName) {
|
||||
NodeList masters = foDoc.getElementsByTagNameNS(FO_NS, "simple-page-master");
|
||||
for (int i = 0; i < masters.getLength(); i++) {
|
||||
Element m = (Element) masters.item(i);
|
||||
if (masterName.equals(m.getAttribute("master-name"))) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** {@code margin="T R B L"} region-body мастера (шортхэнд POI). */
|
||||
private static String[] parseMarginShorthand(Element master) {
|
||||
Element body = child(master, "region-body");
|
||||
if (body == null) {
|
||||
return null;
|
||||
}
|
||||
String margin = body.getAttribute("margin");
|
||||
if (margin == null) {
|
||||
return null;
|
||||
}
|
||||
String[] parts = margin.trim().split("\\s+");
|
||||
return parts.length == 4 ? parts : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Регион колонтитула: extent = поле страницы, текст прижат к body
|
||||
* (низ заголовка / верх футера); зазор — маргинами блоков.
|
||||
*/
|
||||
private static Element appendRegion(Element master, String kind, String extent,
|
||||
String displayAlign) {
|
||||
Element region = master.getOwnerDocument().createElementNS(FO_NS, "fo:" + kind);
|
||||
region.setAttribute("extent", extent);
|
||||
region.setAttribute("display-align", displayAlign);
|
||||
master.appendChild(region);
|
||||
return region;
|
||||
}
|
||||
|
||||
/** В master-клоне варианта колонтитулы берутся из своего потока. */
|
||||
private static void renameRegionFlows(Element clone, String suffix) {
|
||||
for (String kind : new String[]{"region-before", "region-after"}) {
|
||||
Element region = child(clone, kind);
|
||||
if (region != null) {
|
||||
region.setAttribute("flow-name", "xsl-" + kind + suffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Мастер с first/even-вариантами оборачивается в
|
||||
* {@code fo:page-sequence-master} (на месте); {@code master-reference}
|
||||
* page-sequence не меняется — он указывает на имя обёртки.
|
||||
*/
|
||||
private static void wrapInPageSequenceMaster(Document foDoc, Element master,
|
||||
List<Element> variants) {
|
||||
String masterName = master.getAttribute("master-name");
|
||||
Element psm = foDoc.createElementNS(FO_NS, "fo:page-sequence-master");
|
||||
psm.setAttribute("master-name", masterName);
|
||||
Element alternatives = foDoc.createElementNS(FO_NS,
|
||||
"fo:repeatable-page-master-alternatives");
|
||||
psm.appendChild(alternatives);
|
||||
for (Element variant : variants) {
|
||||
String position = variant.getAttribute("master-name").endsWith("-first")
|
||||
? "first" : "even";
|
||||
alternatives.appendChild(conditionalRef(foDoc, position,
|
||||
variant.getAttribute("master-name")));
|
||||
}
|
||||
alternatives.appendChild(conditionalRef(foDoc, "rest", masterName));
|
||||
master.getParentNode().replaceChild(psm, master);
|
||||
}
|
||||
|
||||
private static Element conditionalRef(Document foDoc, String position, String masterRef) {
|
||||
Element ref = foDoc.createElementNS(FO_NS, "fo:conditional-page-master-reference");
|
||||
ref.setAttribute("master-reference", masterRef);
|
||||
ref.setAttribute("page-position", position);
|
||||
return ref;
|
||||
}
|
||||
|
||||
/**
|
||||
* static-content вставляется в page-sequence перед fo:flow; каждый блок
|
||||
* получает зазор {@code gapAttribute} к области контента (в самих
|
||||
* регионах padding запрещён XSL 1.1 — FOP валидирует).
|
||||
*/
|
||||
private static void insertStaticContent(Element sequence, String flowName,
|
||||
List<Element> content, String gapAttribute) {
|
||||
if (content.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Document doc = sequence.getOwnerDocument();
|
||||
Element staticContent = doc.createElementNS(FO_NS, "fo:static-content");
|
||||
staticContent.setAttribute("flow-name", flowName);
|
||||
for (Element block : content) {
|
||||
block.setAttribute(gapAttribute, REGION_GAP_IN + "in");
|
||||
staticContent.appendChild(block);
|
||||
}
|
||||
Element flow = child(sequence, "flow");
|
||||
if (flow == null) {
|
||||
sequence.appendChild(staticContent);
|
||||
} else {
|
||||
sequence.insertBefore(staticContent, flow);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== История -> блоки FO ====================
|
||||
|
||||
/** Параграфы чанка истории как {@code fo:block}-и; пустой чанк — пустой список. */
|
||||
private static List<Element> blocks(Document foDoc, List<Paragraph> chunk,
|
||||
String lastMasterName) {
|
||||
List<Element> result = new ArrayList<>();
|
||||
if (chunk == null) {
|
||||
return result;
|
||||
}
|
||||
for (Paragraph p : chunk) {
|
||||
Element block = paragraphBlock(foDoc, p, lastMasterName);
|
||||
if (block != null && blockHasVisibleContent(block)) {
|
||||
result.add(block);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Параграф истории как {@code fo:block}: выравнивание, табуляции, раны с
|
||||
* форматированием и поля (PAGE/NUMPAGES/SECTIONPAGES) из управляющих
|
||||
* символов текста ранов ({@code \u0013}\u2026{@code \u0014}\u2026{@code \u0015}).
|
||||
*/
|
||||
private static Element paragraphBlock(Document doc, Paragraph p,
|
||||
String lastMasterName) {
|
||||
Element block = doc.createElementNS(FO_NS, "fo:block");
|
||||
block.setAttribute("text-align", switch (p.getJustification()) {
|
||||
case 1 -> "center";
|
||||
case 2 -> "end";
|
||||
case 3 -> "justify";
|
||||
default -> "start";
|
||||
});
|
||||
// Наследуемый шрифт блока: fo:page-number — пустой элемент, без
|
||||
// font-family блока FOP рисует его базовым Helvetica.
|
||||
var blockFont = firstRunFont(p);
|
||||
block.setAttribute("font-family", blockFont != null
|
||||
? blockFont.getName()
|
||||
: BundledFonts.regular(BundledFonts.FALLBACK_FAMILY).getName());
|
||||
// state-machine полей: 0 — обычный текст, 1 — инструкция, 2 — кэш-результат
|
||||
StringBuilder instr = new StringBuilder();
|
||||
StringBuilder cached = new StringBuilder();
|
||||
StringBuilder plain = new StringBuilder();
|
||||
int column = 0;
|
||||
int mode = 0;
|
||||
for (int j = 0; j < p.numCharacterRuns(); j++) {
|
||||
CharacterRun cr;
|
||||
String text;
|
||||
try {
|
||||
cr = p.getCharacterRun(j);
|
||||
text = cr.text();
|
||||
} catch (RuntimeException e) {
|
||||
continue;
|
||||
}
|
||||
if (text == null) {
|
||||
continue;
|
||||
}
|
||||
for (int k = 0; k < text.length(); k++) {
|
||||
char c = text.charAt(k);
|
||||
if (c == FIELD_BEGIN) {
|
||||
mode = 1;
|
||||
instr.setLength(0);
|
||||
cached.setLength(0);
|
||||
} else if (c == FIELD_SEPARATOR && mode == 1) {
|
||||
mode = 2;
|
||||
} else if (c == FIELD_END && (mode == 1 || mode == 2)) {
|
||||
emitField(doc, block, instr.toString(), cached.toString(), lastMasterName);
|
||||
mode = 0;
|
||||
} else if (mode == 1) {
|
||||
instr.append(c);
|
||||
} else if (mode == 2) {
|
||||
cached.append(c);
|
||||
} else if (c == '\t') {
|
||||
column = appendTab(doc, block, plain, column, cr);
|
||||
} else {
|
||||
plain.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mode != 0) {
|
||||
// незакрытое поле: выводим накопленное как обычный текст
|
||||
plain.append(instr).append(cached);
|
||||
}
|
||||
flushText(doc, block, plain.toString(), null);
|
||||
return block;
|
||||
}
|
||||
|
||||
/** Распознанные поля — живые FO-элементы; прочие — кэш-текст как есть. */
|
||||
private static void emitField(Document doc, Element block, String instruction,
|
||||
String cachedResult, String lastMasterName) {
|
||||
String code = instruction.trim().toUpperCase(Locale.ROOT);
|
||||
if (code.startsWith("PAGE")) {
|
||||
Element pn = doc.createElementNS(FO_NS, "fo:page-number");
|
||||
block.appendChild(pn);
|
||||
} else if ((code.startsWith("NUMPAGES") || code.startsWith("SECTIONPAGES"))
|
||||
&& lastMasterName != null) {
|
||||
// нумерация FOP между page-sequence непрерывна — citation-last
|
||||
// по последнему мастеру = общее число страниц
|
||||
Element pn = doc.createElementNS(FO_NS, "fo:page-number-citation-last");
|
||||
pn.setAttribute("ref-name", lastMasterName);
|
||||
block.appendChild(pn);
|
||||
} else {
|
||||
flushText(doc, block, cachedResult, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code \t}: FOP-форк не поддерживает свойство {@code tabs}, поэтому
|
||||
* таб — пробелы до следующей дефолтной Word-остановки (1,25 см).
|
||||
* Возвращает новую «колонку» (символы до курсора).
|
||||
*/
|
||||
private static int appendTab(Document doc, Element block, StringBuilder plain,
|
||||
int column, CharacterRun cr) {
|
||||
flushText(doc, block, plain.toString(), null);
|
||||
plain.setLength(0);
|
||||
double charIn = charWidthIn(cr);
|
||||
double step = 1.25 / 2.54;
|
||||
double x = (column + 1) * charIn;
|
||||
double target = (Math.floor(x / step) + 1) * step;
|
||||
int spaces = (int) Math.max(1, Math.ceil((target - x) / charIn));
|
||||
flushText(doc, block, " ".repeat(spaces), cr);
|
||||
return column + 1 + spaces;
|
||||
}
|
||||
|
||||
/** Приблизительная ширина символа (полширины кегля) в дюймах. */
|
||||
private static double charWidthIn(CharacterRun cr) {
|
||||
double pt = 10.0;
|
||||
try {
|
||||
if (cr != null && cr.getFontSize() > 0) {
|
||||
pt = cr.getFontSize() / 2.0;
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// наследование из стиля — остаётся дефолт
|
||||
}
|
||||
return Math.max(0.03, pt * 0.5 / 72.0);
|
||||
}
|
||||
|
||||
private static void flushText(Document doc, Element block, String text,
|
||||
CharacterRun cr) {
|
||||
String cleaned = cleanText(text);
|
||||
if (cleaned.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (cr == null) {
|
||||
block.appendChild(doc.createTextNode(cleaned));
|
||||
return;
|
||||
}
|
||||
Element inline = doc.createElementNS(FO_NS, "fo:inline");
|
||||
var font = runFont(cr);
|
||||
if (font != null) {
|
||||
inline.setAttribute("font-family", font.getName());
|
||||
}
|
||||
int halfPoints = cr.getFontSize();
|
||||
inline.setAttribute("font-size", (halfPoints > 0 ? halfPoints / 2.0 : 10.0) + "pt");
|
||||
if (cr.isBold()) {
|
||||
inline.setAttribute("font-weight", "bold");
|
||||
}
|
||||
if (cr.isItalic()) {
|
||||
inline.setAttribute("font-style", "italic");
|
||||
}
|
||||
if (cr.getUnderlineCode() != 0) {
|
||||
inline.setAttribute("text-decoration", "underline");
|
||||
}
|
||||
inline.appendChild(doc.createTextNode(cleaned));
|
||||
block.appendChild(inline);
|
||||
}
|
||||
|
||||
/** Шрифт рана -> бандл-аналог (тот же маппинг, что у основного текста). */
|
||||
private static org.docx4j.fonts.PhysicalFont runFont(CharacterRun cr) {
|
||||
String name;
|
||||
try {
|
||||
name = cr.getFontName();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
String family = BundledFontMapper.bundledFamily(name == null ? "" : name);
|
||||
return BundledFonts.regular(family);
|
||||
}
|
||||
|
||||
/** Шрифт первого читаемого рана параграфа (для наследуемого font-family блока). */
|
||||
private static org.docx4j.fonts.PhysicalFont firstRunFont(Paragraph p) {
|
||||
try {
|
||||
for (int j = 0; j < p.numCharacterRuns(); j++) {
|
||||
var font = runFont(p.getCharacterRun(j));
|
||||
if (font != null) {
|
||||
return font;
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// повреждённый параграф — на fallback вызывающего
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* POI пишет маркеры списков {@code fo:inline} без font-family — FOP
|
||||
* рисует их базовым Helvetica. Проставляем фолбэк-семейство всем
|
||||
* инлайнам без семейства.
|
||||
*/
|
||||
private static void applyDefaultFont(Document foDoc) {
|
||||
String fallback = BundledFonts.regular(BundledFonts.FALLBACK_FAMILY).getName();
|
||||
NodeList inlines = foDoc.getElementsByTagNameNS(FO_NS, "inline");
|
||||
for (int i = 0; i < inlines.getLength(); i++) {
|
||||
Element inline = (Element) inlines.item(i);
|
||||
if (inline.getAttribute("font-family").isEmpty()) {
|
||||
inline.setAttribute("font-family", fallback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ==================== FOP ====================
|
||||
|
||||
private static void renderFo(Document foDoc, String title, Path baseDir,
|
||||
OutputStream out) throws Exception {
|
||||
byte[] config = fopConfig().getBytes(StandardCharsets.UTF_8);
|
||||
FopFactory fopFactory = FopFactory.newInstance(baseDir.toUri(),
|
||||
new ByteArrayInputStream(config));
|
||||
FOUserAgent ua = fopFactory.newFOUserAgent();
|
||||
if (title != null && !title.isBlank()) {
|
||||
ua.setTitle(title);
|
||||
}
|
||||
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, ua, out);
|
||||
javax.xml.transform.Transformer transformer =
|
||||
javax.xml.transform.TransformerFactory.newInstance().newTransformer();
|
||||
transformer.transform(new DOMSource(foDoc), new SAXResult(fop.getDefaultHandler()));
|
||||
}
|
||||
|
||||
/**
|
||||
* FOP-конфиг: только шрифты бандла (auto-detect="false" — системные в
|
||||
* рендер не попадают). Triplet-имена — из name-таблиц regular-вариантов,
|
||||
* как в {@link FopFallbackFonts}; {@code simulate-style="false"} — стили
|
||||
* настоящие TTF, а не синтез FOP.
|
||||
*/
|
||||
private static String fopConfig() {
|
||||
StringBuilder sb = new StringBuilder(
|
||||
"<fop version=\"1.0\"><renderers>"
|
||||
+ "<renderer mime=\"application/pdf\"><fonts auto-detect=\"false\">");
|
||||
for (String family : BundledFonts.families()) {
|
||||
var regular = BundledFonts.regular(family);
|
||||
if (regular == null) {
|
||||
continue;
|
||||
}
|
||||
String tripletName = regular.getName();
|
||||
appendFont(sb, regular, "regular", tripletName, "normal", "normal");
|
||||
appendFont(sb, BundledFonts.bold(family), "bold", tripletName, "normal", "bold");
|
||||
appendFont(sb, BundledFonts.italic(family), "italic", tripletName, "italic", "normal");
|
||||
appendFont(sb, BundledFonts.boldItalic(family), "boldItalic",
|
||||
tripletName, "italic", "bold");
|
||||
}
|
||||
sb.append("</fonts></renderer></renderers></fop>");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static void appendFont(StringBuilder sb, org.docx4j.fonts.PhysicalFont pf,
|
||||
String embedMode, String tripletName,
|
||||
String style, String weight) {
|
||||
if (pf == null) {
|
||||
return;
|
||||
}
|
||||
sb.append("<font embed-url=\"").append(pf.getEmbeddedURI())
|
||||
.append("\" embed-mode=\"").append(embedMode)
|
||||
.append("\" simulate-style=\"false\"><font-triplet name=\"")
|
||||
.append(tripletName).append("\" style=\"").append(style)
|
||||
.append("\" weight=\"").append(weight)
|
||||
.append("\"/></font>");
|
||||
}
|
||||
|
||||
// ==================== Утилиты DOM ====================
|
||||
|
||||
private static Element child(Element parent, String localName) {
|
||||
NodeList children = parent.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
Node n = children.item(i);
|
||||
if (n instanceof Element e && FO_NS.equals(e.getNamespaceURI())
|
||||
&& localName.equals(e.getLocalName())) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean blockHasVisibleContent(Element block) {
|
||||
if (block.getTextContent() != null && !block.getTextContent().isBlank()) {
|
||||
return true;
|
||||
}
|
||||
return block.getElementsByTagNameNS(FO_NS, "page-number").getLength() > 0
|
||||
|| block.getElementsByTagNameNS(FO_NS, "page-number-citation-last").getLength() > 0
|
||||
|| block.getElementsByTagNameNS(FO_NS, "leader").getLength() > 0;
|
||||
}
|
||||
|
||||
/** Есть ли в чанке хоть один параграф с видимым содержимым. */
|
||||
private static boolean hasText(List<Paragraph> chunk) {
|
||||
if (chunk == null) {
|
||||
return false;
|
||||
}
|
||||
for (Paragraph p : chunk) {
|
||||
try {
|
||||
for (int j = 0; j < p.numCharacterRuns(); j++) {
|
||||
String t = p.getCharacterRun(j).text();
|
||||
if (t != null && !cleanText(t).isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// повреждённый ран — не содержимое
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String cleanText(String t) {
|
||||
StringBuilder sb = new StringBuilder(t.length());
|
||||
for (int i = 0; i < t.length(); i++) {
|
||||
char c = t.charAt(i);
|
||||
if (c != PARA_END && c != CELL_END && c != SECTION_END) {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static void deleteRecursively(Path dir) {
|
||||
try (Stream<Path> walk = Files.walk(dir)) {
|
||||
walk.sorted(Comparator.reverseOrder()).forEach(p -> {
|
||||
try {
|
||||
Files.deleteIfExists(p);
|
||||
} catch (IOException ignored) {
|
||||
// temp-файлы: нечего делать при отказе удаления
|
||||
}
|
||||
});
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
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.pdmodel.graphics.PDXObject;
|
||||
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
import org.apache.pdfbox.text.TextPosition;
|
||||
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.util.ArrayList;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Конвертация бинарного .doc (Word 97-2003, OLE2) через ветку
|
||||
* {@code internal.DocToPdfRenderer} (POI HWPF -> XSL-FO -> FOP).
|
||||
* Фикстура — закоммиченный samples/legacy-doc.doc (создан Word'ом,
|
||||
* POI .doc не пишет — не перезагенерировать).
|
||||
*
|
||||
* <p>Ассерты только на фактическое содержимое фикстуры и на раны,
|
||||
* ушедшие в Tinos (аналог Times New Roman): текст ран, ушедших в
|
||||
* DejaVu-fallback, PDFBox на машинах с установленным DejaVu «чинит»
|
||||
* по системному шрифту и извлекает «#» — такие строки не ассертятся
|
||||
* (экзотические глифы фикстуры — принятая деградация .doc-ветки:
|
||||
* аналога GlyphCoverageNormalizer здесь нет).
|
||||
*/
|
||||
class DocToPdfTest {
|
||||
|
||||
private static byte[] sampleBytes(String name) throws IOException {
|
||||
try (InputStream in = DocToPdfTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/" + name)) {
|
||||
assertNotNull(in, "Нет тестового документа: samples/" + name);
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
private static Path convertPdf(byte[] docBytes, String title) throws IOException {
|
||||
Path out = Files.createTempFile("converted-doc-", ".pdf");
|
||||
Files.write(out, WordPdfConverter.convert(docBytes, title));
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String norm(String s) {
|
||||
return s.replaceAll("\\s+", "");
|
||||
}
|
||||
|
||||
private static String pdfPageText(Path pdf, int page) throws IOException {
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
stripper.setStartPage(page);
|
||||
stripper.setEndPage(page);
|
||||
return stripper.getText(doc);
|
||||
}
|
||||
}
|
||||
|
||||
/** Строка страницы: базовая линия y (от верха страницы, PDFBox YDirAdj) и текст. */
|
||||
private record Line(float y, String text) {
|
||||
}
|
||||
|
||||
/** Непустые строки страницы с базовыми линиями (порядок по позиции). */
|
||||
private static List<Line> pageLines(Path pdf, int page) throws IOException {
|
||||
List<Line> lines = new ArrayList<>();
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
PDFTextStripper stripper = new PDFTextStripper() {
|
||||
@Override
|
||||
protected void writeString(String text, List<TextPosition> textPositions)
|
||||
throws IOException {
|
||||
super.writeString(text, textPositions);
|
||||
if (!textPositions.isEmpty() && !norm(text).isEmpty()) {
|
||||
lines.add(new Line(textPositions.get(0).getYDirAdj(), text));
|
||||
}
|
||||
}
|
||||
};
|
||||
stripper.setStartPage(page);
|
||||
stripper.setEndPage(page);
|
||||
stripper.setSortByPosition(true);
|
||||
stripper.getText(doc);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** y базовой линии первой строки, содержащей needle (после norm); null если нет. */
|
||||
private static Float lineY(Path pdf, int page, String needle) throws IOException {
|
||||
String n = norm(needle);
|
||||
for (Line l : pageLines(pdf, page)) {
|
||||
if (norm(l.text()).contains(n)) {
|
||||
return l.y();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Максимум y по всем непустым строкам страницы (самая нижняя базовая линия). */
|
||||
private static float maxLineY(Path pdf, int page) throws IOException {
|
||||
float max = Float.MIN_VALUE;
|
||||
for (Line l : pageLines(pdf, page)) {
|
||||
max = Math.max(max, l.y());
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
/** BaseFont-имена вшитых шрифтов PDF (например "EAAAAA+Tinos-Bold"). */
|
||||
private static Set<String> embeddedFontNames(Path pdf) throws IOException {
|
||||
Set<String> names = new TreeSet<>();
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources res = page.getResources();
|
||||
for (COSName name : res.getFontNames()) {
|
||||
PDFont font = res.getFont(name);
|
||||
if (font != null) {
|
||||
names.add(font.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** Число уникальных Image XObject в PDF (наследованные ресурсы — один объект). */
|
||||
private static int imageCount(Path pdf) throws IOException {
|
||||
Set<PDXObject> seen = java.util.Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources res = page.getResources();
|
||||
for (COSName name : res.getXObjectNames()) {
|
||||
PDXObject xo = res.getXObject(name);
|
||||
if (xo instanceof PDImageXObject) {
|
||||
seen.add(xo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* .doc конвертируется в PDF: текст кириллический, таблицы и картинки
|
||||
* на месте, шрифт — встроенный Tinos (аналог Times New Roman),
|
||||
* базовый Helvetica не используется.
|
||||
* Регрессия — WordPdfConverter#isOle2 + internal.DocToPdfRenderer,
|
||||
* фикстура samples/legacy-doc.doc.
|
||||
*/
|
||||
@Test
|
||||
void legacyDoc_convertsToPdf() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("legacy-doc.doc"), "testDoc");
|
||||
String text;
|
||||
int pages;
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
pages = doc.getNumberOfPages();
|
||||
text = norm(new PDFTextStripper().getText(doc));
|
||||
}
|
||||
assertTrue(pages >= 10, "страниц меньше ожидаемого: " + pages);
|
||||
assertTrue(text.contains("Предметдоговора"), "нет заголовка раздела");
|
||||
assertTrue(text.contains("Договорарендыпомещения"), "нет заголовка");
|
||||
for (String font : embeddedFontNames(pdf)) {
|
||||
assertFalse(font.contains("Helvetica"), "базовый шрифт в PDF: " + font);
|
||||
}
|
||||
assertTrue(embeddedFontNames(pdf).stream().anyMatch(n -> n.contains("Tinos")),
|
||||
"нет Tinos (аналога Times New Roman): " + embeddedFontNames(pdf));
|
||||
assertTrue(imageCount(pdf) >= 1, "картинок нет");
|
||||
}
|
||||
|
||||
/**
|
||||
* Колонтитулы, которых POI в FO не пишет, дописываются в FO-DOM:
|
||||
* текст odd-footer («Нижний колонтитул») и номер страницы из PAGE-поля
|
||||
* на каждой странице.
|
||||
* Регрессия — DocToPdfRenderer#injectHeadersAndFooters,
|
||||
* фикстура samples/legacy-doc.doc.
|
||||
*/
|
||||
@Test
|
||||
void legacyDoc_footersCarryPageNumbers() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("legacy-doc.doc"), "testDoc");
|
||||
String page1 = norm(pdfPageText(pdf, 1));
|
||||
String page5 = norm(pdfPageText(pdf, 5));
|
||||
assertTrue(page5.contains("Нижнийколонтитул"), "нет текста футера на стр. 5");
|
||||
assertTrue(page1.startsWith("1"), "нет номера страницы на стр. 1: "
|
||||
+ page1.substring(0, Math.min(20, page1.length())));
|
||||
assertTrue(page5.contains("5"), "нет номера страницы на стр. 5");
|
||||
}
|
||||
|
||||
/**
|
||||
* Текст body не наезжает на области колонтитулов: заголовок первой
|
||||
* строки лежит ниже header-региона (extent = верхнее поле 0.7875in =
|
||||
* 56.7pt), под строкой футера ничего нет. Форк FOP не вычитает
|
||||
* extent'ы регионов из body-области (area.Page = page-area минус
|
||||
* собственные margin'ы region-body), поэтому разводка body и
|
||||
* колонтитулов — только margin'ами region-body; их обнуление
|
||||
* растягивает body на всю страницу, и текст лезет в колонтитулы.
|
||||
* Регрессия — DocToPdfRenderer#injectHeadersAndFooters,
|
||||
* фикстура samples/legacy-doc.doc.
|
||||
*/
|
||||
@Test
|
||||
void legacyDoc_bodyClearsHeaderFooterRegions() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("legacy-doc.doc"), "testDoc");
|
||||
Float titleY = lineY(pdf, 1, "Договор аренды");
|
||||
assertNotNull(titleY, "нет заголовка на стр. 1");
|
||||
assertTrue(titleY > 50f, "заголовок внутри header-региона: y=" + titleY);
|
||||
Float footerY = lineY(pdf, 1, "Нижний колонтитул");
|
||||
assertNotNull(footerY, "нет футера на стр. 1");
|
||||
float lowest = maxLineY(pdf, 1);
|
||||
assertTrue(lowest <= footerY + 1f,
|
||||
"строка ниже футера: y=" + lowest + " > y футера " + footerY);
|
||||
}
|
||||
|
||||
/**
|
||||
* OLE2-магик + мусор: и валидатор, и конвертер обязаны отвергнуть
|
||||
* документ (не молча отдать пустой PDF).
|
||||
* Регрессия — DocToPdfRenderer#render, WordPdfValidator#checkDocPageCountLightweight.
|
||||
*/
|
||||
@Test
|
||||
void ole2Junk_rejected() {
|
||||
byte[] junk = new byte[1024];
|
||||
byte[] magic = {(byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0,
|
||||
(byte) 0xA1, (byte) 0xB1, 0x1A, (byte) 0xE1};
|
||||
System.arraycopy(magic, 0, junk, 0, magic.length);
|
||||
assertThrows(ConversionException.class,
|
||||
() -> WordPdfValidator.checkDocPageCountLightweight(junk));
|
||||
assertThrows(ConversionException.class,
|
||||
() -> WordPdfConverter.convert(junk, "junk"));
|
||||
}
|
||||
}
|
||||
@@ -359,4 +359,49 @@ class WordPdfValidatorTest {
|
||||
() -> WordPdfValidator.checkPageCountLightweight(docx, 3));
|
||||
assertTrue(ex.getMessage().contains("не менее 4"), ex.getMessage());
|
||||
}
|
||||
|
||||
/** Фикстура бинарного .doc (закоммичена, создана Word'ом — POI .doc не пишет). */
|
||||
private static byte[] legacyDocBytes() throws Exception {
|
||||
try (var in = WordPdfValidatorTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/legacy-doc.doc")) {
|
||||
assertNotNull(in, "Нет тестового документа: samples/legacy-doc.doc");
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Число страниц .doc — кэш SummaryInformation (для фикстуры 11):
|
||||
* лимит 10 должен отвергать, 20 — пропускать.
|
||||
* Регрессия — WordPdfValidator#checkDocPageCountLightweight,
|
||||
* фикстура samples/legacy-doc.doc.
|
||||
*/
|
||||
@Test
|
||||
void checkDocPageCountLightweight_overLimitRejected() throws Exception {
|
||||
ConversionException ex = assertThrows(ConversionException.class,
|
||||
() -> WordPdfValidator.checkDocPageCountLightweight(legacyDocBytes(), 10));
|
||||
assertTrue(ex.getMessage().contains("не менее 11"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkDocPageCountLightweight_underLimitPasses() throws Exception {
|
||||
byte[] doc = legacyDocBytes();
|
||||
assertDoesNotThrow(() -> WordPdfValidator.checkDocPageCountLightweight(doc, 20));
|
||||
assertDoesNotThrow(() -> WordPdfValidator.checkDocPageCountLightweight(doc));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkDocPageCountLightweight_junkRejected() {
|
||||
byte[] junk = new byte[1024];
|
||||
byte[] magic = {(byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0,
|
||||
(byte) 0xA1, (byte) 0xB1, 0x1A, (byte) 0xE1};
|
||||
System.arraycopy(magic, 0, junk, 0, magic.length);
|
||||
assertThrows(ConversionException.class,
|
||||
() -> WordPdfValidator.checkDocPageCountLightweight(junk));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkDocPageCountLightweight_bytesNull() {
|
||||
assertThrows(ConversionException.class,
|
||||
() -> WordPdfValidator.checkDocPageCountLightweight((byte[]) null));
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user