Мост .doc → .docx: конвертация бинарного Word 97-2003 (MS-DOC/MS-CFB/MS-OLEPS/MS-ODRAW)
- internal/doc: CfbReader, FibHeader, PieceTable, Grpprl, ChpxIndex, PapxIndex, Sections, FontTable, SummaryInfo, Headers, OfficeArt, DocFile, DocxWriter, DocToDocx — разбор бинарного .doc и сборка in-memory .docx (прямые свойства, колонтитуки с PAGE/NUMPAGES → fldSimple, BLIP-картинки PNG/JPEG/DIB) - роутинг WordPdfConverter по сигнатуре CFB; валидация страниц .doc по сырым байтам (SummaryInfo PageCount + 0x0C + pageBreakBefore) до конвертации - .docx/.doc: ConvertController, safeBaseName, фронт (DropZone accept) - фикстуры: 12 .doc (11 эталонов заказчика + doc-formats); doc-пары тестов - тесты: 13 классов internal/doc (98 @Test) + пары в конвертере/валидаторе/app; гейт mvn clean verify зелёный (core BRANCH 0.852, LINE 0.947) - AGENTS.md: секция «Мост .doc → .docx», обновлены счётчики и каталоги
This commit is contained in:
@@ -15,6 +15,7 @@ import ru.pjandro.wordpdf.internal.chart.DrawingPreRenderer;
|
||||
import ru.pjandro.wordpdf.internal.DependencyGuard;
|
||||
import ru.pjandro.wordpdf.internal.DocxNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.DocxRewritePipeline;
|
||||
import ru.pjandro.wordpdf.internal.doc.DocToDocx;
|
||||
import ru.pjandro.wordpdf.internal.OleObjectNormalizer;
|
||||
import ru.pjandro.wordpdf.internal.FopFallbackFonts;
|
||||
import ru.pjandro.wordpdf.internal.LayoutPostRenderer;
|
||||
@@ -61,20 +62,26 @@ public final class WordPdfConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертирует байты .docx в PDF. Работа с файлами — забота вызывающего
|
||||
* (файловое API было здесь раньше; ядро пути не принимает).
|
||||
* Конвертирует байты .docx (или бинарного .doc Word 97–2003 — формат
|
||||
* определяется по сигнатуре байтов) в PDF. Работа с файлами — забота
|
||||
* вызывающего (файловое API было здесь раньше; ядро пути не принимает).
|
||||
*
|
||||
* <p>Вход проверяется {@link WordPdfValidator#validate(byte[], ConvertOptions)} до рендера:
|
||||
* <p>.doc предварительно переносится в .docx мостом
|
||||
* {@link ru.pjandro.wordpdf.internal.doc.DocToDocx} (текст + прямое
|
||||
* форматирование); число страниц для .doc проверяется мостом по чистому
|
||||
* бинарному документу (кэш PageCount + явные разрывы), сгенерированный
|
||||
* .docx валидацией не проверяется. Для .docx вход проверяется
|
||||
* {@link WordPdfValidator#validate(byte[], ConvertOptions)} до рендера:
|
||||
* {@code null} / размер больше {@link WordPdfSettings#MAX_INPUT_MB} (МБ) / zip-подпись /
|
||||
* число страниц больше {@link WordPdfSettings#MAX_PAGES} — при отказе байтов результата нет;
|
||||
* страницы дополнительно перепроверяются по нормализованным байтам (шаг 2.5).
|
||||
*
|
||||
* @param docxBytes байты .docx
|
||||
* @param docxBytes байты .docx или бинарного .doc
|
||||
* @param title заголовок PDF (метаданные); {@code null}/пустая — заголовок не задаётся
|
||||
* @return байты готового PDF
|
||||
* @throws ValidationException некорректный вход: {@code null}, размер больше
|
||||
* {@link WordPdfSettings#MAX_INPUT_MB} (МБ), не zip-архив, документ длиннее
|
||||
* {@link WordPdfSettings#MAX_PAGES} страниц
|
||||
* {@link WordPdfSettings#MAX_INPUT_MB} (МБ), не .docx/.doc, зашифрованный .doc,
|
||||
* документ длиннее {@link WordPdfSettings#MAX_PAGES} страниц
|
||||
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
||||
*/
|
||||
public static byte[] convert(byte[] docxBytes, String title) throws ConversionException {
|
||||
@@ -82,30 +89,43 @@ public final class WordPdfConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертирует байты .docx в PDF с настройками на вызов: error-флаги
|
||||
* диаграмм/SmartArt и лимиты входа.
|
||||
* Конвертирует байты .docx (или бинарного .doc Word 97–2003 — формат
|
||||
* определяется по сигнатуре байтов, см. перегрузку выше) в PDF с
|
||||
* настройками на вызов: error-флаги диаграмм/SmartArt и лимиты входа.
|
||||
*
|
||||
* <p>Вход проверяется {@link WordPdfValidator#validate(byte[], ConvertOptions)} до рендера:
|
||||
* {@code null} / размер больше {@code options.maxMb()} (МБ) / zip-подпись / число страниц
|
||||
* больше {@code options.maxPages()} — при отказе байтов результата нет; страницы
|
||||
* дополнительно перепроверяются по нормализованным байтам (шаг 2.5).
|
||||
* <p>Вход проверяется {@link WordPdfValidator#validate(byte[], ConvertOptions)}
|
||||
* до рендера — одна проверка на оба формата: {@code null} / размер больше
|
||||
* {@code options.maxMb()} (МБ) / не .docx и не .doc / число страниц больше
|
||||
* {@code options.maxPages()} — при отказе байтов результата нет. Для .docx
|
||||
* страницы дополнительно перепроверяются по нормализованным байтам (шаг 2.5);
|
||||
* для .doc страницы считаются по чистому бинарному документу до конвертации,
|
||||
* конвертат не перепроверяется.
|
||||
*
|
||||
* @param docxBytes байты .docx
|
||||
* @param docxBytes байты .docx или бинарного .doc
|
||||
* @param title заголовок PDF (метаданные); {@code null}/пустая — заголовок не задаётся
|
||||
* @param options error-флаги и лимиты входа на этот вызов; {@code null} —
|
||||
* дефолты (константы {@link WordPdfSettings})
|
||||
* @return байты готового PDF
|
||||
* @throws ValidationException некорректный вход: {@code null}, размер больше
|
||||
* {@code options.maxMb()} (МБ), не zip-архив, документ длиннее
|
||||
* {@code options.maxPages()} страниц
|
||||
* {@code options.maxMb()} (МБ), не .docx/.doc, зашифрованный .doc,
|
||||
* документ длиннее {@code options.maxPages()} страниц
|
||||
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
||||
*/
|
||||
public static byte[] convert(byte[] docxBytes, String title, ConvertOptions options) throws ConversionException {
|
||||
ConvertOptions opts = options == null ? ConvertOptions.defaults() : options;
|
||||
// Полная проверка входа — одна на оба формата: размер до
|
||||
// классификации (враждебный вход без подписи обязан получить ошибку
|
||||
// лимита), затем для .docx — zip/контейнер/страницы, для .doc —
|
||||
// страницы по чистому бинарному документу (до конвертации).
|
||||
WordPdfValidator.validate(docxBytes, opts);
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(1 << 16, docxBytes.length));
|
||||
boolean fromDoc = WordPdfValidator.isBinaryDoc(docxBytes);
|
||||
// Бинарный .doc (Word 97–2003): мост internal.doc. Сгенерированный
|
||||
// .docx — собственный артефакт, его штатной валидацией/перепроверкой
|
||||
// (шаг 2.5) не проверяем.
|
||||
byte[] docx = fromDoc ? DocToDocx.convert(docxBytes) : docxBytes;
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(1 << 16, docx.length));
|
||||
try {
|
||||
convertToStream(docxBytes, title, opts, bos);
|
||||
convertToStream(docx, title, opts, bos, fromDoc);
|
||||
} catch (ConversionException e) {
|
||||
// ValidationException (отказ валидации входа) — подтип, уходит
|
||||
// вызывающему без обёртки
|
||||
@@ -122,7 +142,7 @@ public final class WordPdfConverter {
|
||||
* без неё старая версия библиотеки дала бы мутный NoSuchMethodError внутри docx4j.
|
||||
*/
|
||||
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
||||
OutputStream os) throws Exception {
|
||||
OutputStream os, boolean skipPageRecheck) throws Exception {
|
||||
// 0. Совместимость commons-compress: docx4j требует ковариантный
|
||||
// ZipArchiveInputStream.getNextEntry() (>= 1.25.0); ниже — понятный
|
||||
// ConversionException с инструкцией вместо NoSuchMethodError.
|
||||
@@ -153,7 +173,12 @@ public final class WordPdfConverter {
|
||||
// Делается до рендера, чтобы не тратить время на заведомо
|
||||
// длинный документ; внутри try — чтобы и на отказе отработал
|
||||
// finally с чисткой temp-файлов встроенных шрифтов.
|
||||
WordPdfValidator.checkPageCount(docxBytes, options.maxPages());
|
||||
// Для .doc пропущена: страницы уже посчитаны мостом по чистому
|
||||
// бинарному документу, перепроверять собственный конвертат —
|
||||
// значит проверять не вход.
|
||||
if (!skipPageRecheck) {
|
||||
WordPdfValidator.checkPageCount(docxBytes, options.maxPages());
|
||||
}
|
||||
// после этой строки docxBytes больше не читается — HotSpot с точными
|
||||
// картами liveness считает его недостижимым, нормализованная копия
|
||||
// освобождается до FOP-рендера (пик: JAXB-модель + FOP + PDF-буфер)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package ru.pjandro.wordpdf;
|
||||
|
||||
import ru.pjandro.wordpdf.internal.doc.DocToDocx;
|
||||
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
@@ -16,9 +18,10 @@ import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* Валидатор ограничений на входной .docx:
|
||||
* Валидатор ограничений на вход: .docx и бинарный .doc (Word 97–2003) —
|
||||
* размер входа, корректность контейнера (.docx-манифест, защита от
|
||||
* zip-бомбы) и число страниц.
|
||||
* zip-бомбы; для .doc — CFB/Word-разбор {@code internal.doc}) и число
|
||||
* страниц для обоих форматов.
|
||||
*
|
||||
* <p>Вход валидатора — только {@code byte[]}: файловых проверок нет,
|
||||
* работа с файлами — забота вызывающего (приложения).
|
||||
@@ -99,6 +102,26 @@ public final class WordPdfValidator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CFB-подпись D0 CF 11 E0 A1 B1 1A E1 (MS-CFB §2.2) — контейнер бинарного
|
||||
* .doc Word 97–2003. Классификация входа до любой работы с форматом:
|
||||
* такой вход не проверяется .docx-валидацией (zip-пути), его страницы
|
||||
* считает мост {@code internal.doc} по чистому бинарному документу.
|
||||
*/
|
||||
public static boolean isBinaryDoc(byte[] bytes) {
|
||||
byte[] sig = {(byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0,
|
||||
(byte) 0xA1, (byte) 0xB1, 0x1A, (byte) 0xE1};
|
||||
if (bytes == null || bytes.length < sig.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < sig.length; i++) {
|
||||
if (bytes[i] != sig[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет число страниц без загрузки документа в docx4j: .docx
|
||||
* читается как zip напрямую (StAX по {@code word/document.xml},
|
||||
@@ -183,8 +206,42 @@ public final class WordPdfValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Полная проверка входа: размер → zip-подпись → контейнер (.docx +
|
||||
* zip-бомба) → число страниц. Порядок
|
||||
* Число страниц бинарного .doc (Word 97–2003) — по чистому бинарному
|
||||
* документу, <b>до</b> какой-либо конвертации в .docx: нижняя оценка
|
||||
* {@code max(кэш SummaryInformation.PageCount [MS-OLEPS], 1 + явные
|
||||
* разрывы 0x0C − непрерывные межсекционные разрывы + абзацы с
|
||||
* pageBreakBefore)} — тот же контур, что lightweight-скан по zip для
|
||||
* .docx. Разбор делает {@code internal.doc} ({@link DocToDocx#countPages(byte[])}).
|
||||
*
|
||||
* @throws ValidationException при {@code null}, не-.doc-входе, шифровании
|
||||
* или превышении {@link WordPdfSettings#MAX_PAGES}
|
||||
*/
|
||||
public static void checkPageCountDoc(byte[] docBytes) throws ValidationException {
|
||||
checkPageCountDoc(docBytes, WordPdfSettings.MAX_PAGES);
|
||||
}
|
||||
|
||||
/**
|
||||
* То же, что {@link #checkPageCountDoc(byte[])}, с явным лимитом
|
||||
* страниц (переопределение на вызов, см. {@link ConvertOptions#maxPages()}).
|
||||
*
|
||||
* @throws ValidationException при {@code null}, не-.doc-входе, шифровании
|
||||
* или превышении {@code maxPages}
|
||||
*/
|
||||
public static void checkPageCountDoc(byte[] docBytes, int maxPages) throws ValidationException {
|
||||
if (docBytes == null) {
|
||||
throw new ValidationException("Не указаны байты входного .doc");
|
||||
}
|
||||
int pages = DocToDocx.countPages(docBytes);
|
||||
if (pages > maxPages) {
|
||||
throw new ValidationException("Документ длиннее " + maxPages
|
||||
+ " страниц: получено не менее " + pages);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Полная проверка входа: размер → классификация формата → (.docx:
|
||||
* zip-подпись → контейнер (.docx + zip-бомба) → число страниц) /
|
||||
* (.doc: число страниц по чистому бинарному документу). Порядок
|
||||
* значим: размер — дешёвая, разбор zip без подписи бессмысленен. Лимиты
|
||||
* берутся из {@link ConvertOptions} (переопределение на вызов, см.
|
||||
* {@link ConvertOptions#maxMb()}, {@link ConvertOptions#maxPages()}).
|
||||
@@ -212,9 +269,15 @@ public final class WordPdfValidator {
|
||||
*/
|
||||
public static void validate(byte[] docxBytes, ConvertOptions options) throws ValidationException {
|
||||
checkInput(docxBytes, options.maxMb());
|
||||
if (isBinaryDoc(docxBytes)) {
|
||||
// Бинарный .doc: страницы — по чистому бинарному документу,
|
||||
// без конвертации в .docx (регрессия — WordPdfValidatorTest#checkPageCountDoc_*).
|
||||
checkPageCountDoc(docxBytes, options.maxPages());
|
||||
return;
|
||||
}
|
||||
if (docxBytes.length < 4 || docxBytes[0] != 'P' || docxBytes[1] != 'K'
|
||||
|| (docxBytes[2] & 0xFF) != 0x03 || (docxBytes[3] & 0xFF) != 0x04) {
|
||||
throw new ValidationException("Содержимое не похоже на .docx (не zip-архив)");
|
||||
throw new ValidationException("Содержимое не похоже на .docx или .doc (не zip-архив)");
|
||||
}
|
||||
checkDocxContainer(docxBytes);
|
||||
checkPageCount(docxBytes, options.maxPages());
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Читатель OLE2-контейнера (CFB) — вход бинарного .doc.
|
||||
*
|
||||
* <p>Реализация строго по [MS-CFB]: заголовок §2.2, FAT/DIFAT §2.3–2.5,
|
||||
* Mini FAT §2.4, Directory §2.6. Возвращает только потоки (storage'ы
|
||||
* пропускаются): имя записи → содержимое. Сектор N лежит по смещению
|
||||
* (N + 1) × Sector Size (§2.3, ms-cfb.md:567); потоки короче cutoff
|
||||
* (4096 байт) — в mini stream по MiniFAT-цепочке (§2.4).</p>
|
||||
*
|
||||
* <p>Враждебный вход: битый заголовок, сектор за концом файла, цикл в
|
||||
* FAT/MiniFAT/DIFAT/directory-цепочке — {@link ValidationException}; длина
|
||||
* любой цепочки ограничена числом секторов файла, иначе враждебный FAT
|
||||
* зациклил бы разбор.</p>
|
||||
*/
|
||||
public final class CfbReader {
|
||||
|
||||
/** Сигнатура контейнера, MS-CFB §2.2 (Header Signature). */
|
||||
static final byte[] SIGNATURE = {(byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0,
|
||||
(byte) 0xA1, (byte) 0xB1, 0x1A, (byte) 0xE1};
|
||||
|
||||
/** Конец цепочки / специальные значения FAT (MS-CFB §2.1). */
|
||||
private static final long ENDOFCHAIN = 0xFFFFFFFEL;
|
||||
private static final long FREESECT = 0xFFFFFFFFL;
|
||||
private static final long MAX_SECT = 0xFFFFFFFAL;
|
||||
|
||||
/** Разумный потолок mini-sector shift: 2^16 = 64 KiB (MS-CFB §2.2). */
|
||||
private static final int MAX_MINI_SECTOR_SHIFT = 16;
|
||||
|
||||
/** Типы записей directory (MS-CFB §2.6, Object Type). */
|
||||
private static final int TYPE_STREAM = 0x02;
|
||||
private static final int TYPE_ROOT = 0x05;
|
||||
|
||||
/** Размер directory-записи, байт (MS-CFB §2.6). */
|
||||
private static final int ENTRY_SIZE = 128;
|
||||
|
||||
/** Смещения полей заголовка (MS-CFB §2.2: сигнатура 8 + CLSID 16). */
|
||||
private static final int OFF_SECTOR_SHIFT = 0x1E;
|
||||
private static final int OFF_MINI_SECTOR_SHIFT = 0x20;
|
||||
private static final int OFF_FIRST_DIR = 0x30;
|
||||
private static final int OFF_CUTOFF = 0x38;
|
||||
private static final int OFF_FIRST_MINI_FAT = 0x3C;
|
||||
private static final int OFF_FIRST_DIFAT = 0x44;
|
||||
private static final int OFF_DIFAT_COUNT = 0x48;
|
||||
private static final int OFF_DIFAT_ENTRIES = 0x4C;
|
||||
private static final int DIFAT_ENTRIES_IN_HEADER = 109;
|
||||
|
||||
/** Смещения полей directory-записи (MS-CFB §2.6). */
|
||||
private static final int ENTRY_NAME_LEN = 0x40;
|
||||
private static final int ENTRY_TYPE = 0x42;
|
||||
private static final int ENTRY_START_SECT = 0x74;
|
||||
private static final int ENTRY_SIZE_LO = 0x78;
|
||||
|
||||
/** Минимальный заголовок — 512 байт (сектор v3). */
|
||||
private static final int HEADER_SIZE = 512;
|
||||
|
||||
private CfbReader() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Разбирает контейнер и возвращает его потоки: имя записи → байты.
|
||||
* Имена регистронезависимо ищёт вызывающий ({@link #stream}).
|
||||
*
|
||||
* @throws ValidationException если это не CFB, файл обрезан или цепочки
|
||||
* секторов цикличны/указывают за конец файла
|
||||
*/
|
||||
public static Map<String, byte[]> readStreams(byte[] cfb) {
|
||||
if (cfb == null || cfb.length < HEADER_SIZE || !startsWithSignature(cfb)) {
|
||||
throw new ValidationException("Содержимое не похоже на .doc Word 97–2003");
|
||||
}
|
||||
int sectorShift = u16(cfb, OFF_SECTOR_SHIFT);
|
||||
int miniSectorShift = u16(cfb, OFF_MINI_SECTOR_SHIFT);
|
||||
if (sectorShift != 9 && sectorShift != 12) {
|
||||
throw new ValidationException("Неподдерживаемый размер сектора CFB: 2^" + sectorShift);
|
||||
}
|
||||
if (miniSectorShift > MAX_MINI_SECTOR_SHIFT) {
|
||||
throw new ValidationException("Неподдерживаемый размер mini-сектора CFB: 2^" + miniSectorShift);
|
||||
}
|
||||
int sectorSize = 1 << sectorShift;
|
||||
int miniSectorSize = 1 << miniSectorShift;
|
||||
long firstDir = u32(cfb, OFF_FIRST_DIR);
|
||||
long cutoff = u32(cfb, OFF_CUTOFF);
|
||||
long firstMiniFat = u32(cfb, OFF_FIRST_MINI_FAT);
|
||||
long firstDifat = u32(cfb, OFF_FIRST_DIFAT);
|
||||
long difatCount = u32(cfb, OFF_DIFAT_COUNT);
|
||||
|
||||
int sectorTotal = (cfb.length - sectorSize) / sectorSize + 1; // секторов после заголовка
|
||||
int[] fat = readFat(cfb, sectorSize, firstDifat, difatCount, sectorTotal);
|
||||
|
||||
byte[] miniStream = null;
|
||||
int[] miniFat = null;
|
||||
|
||||
int[] dirChain = chain(fat, firstDir, sectorTotal, "цепочка directory");
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
long rootStart = -1;
|
||||
long rootSize = 0;
|
||||
for (int sect : dirChain) {
|
||||
int base = sectorOffset(sect, sectorSize);
|
||||
for (int off = 0; off + ENTRY_SIZE <= sectorSize && base + off + ENTRY_SIZE <= cfb.length;
|
||||
off += ENTRY_SIZE) {
|
||||
int type = cfb[base + off + ENTRY_TYPE] & 0xFF;
|
||||
if (type == TYPE_ROOT) {
|
||||
rootStart = u32(cfb, base + off + ENTRY_START_SECT);
|
||||
rootSize = u32(cfb, base + off + ENTRY_SIZE_LO);
|
||||
} else if (type == TYPE_STREAM) {
|
||||
String name = entryName(cfb, base + off);
|
||||
long start = u32(cfb, base + off + ENTRY_START_SECT);
|
||||
long size = u32(cfb, base + off + ENTRY_SIZE_LO);
|
||||
if (!name.isEmpty() && size >= 0 && size <= cfb.length) {
|
||||
entries.add(new Entry(name, start, size));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rootStart >= 0 && rootSize > 0) {
|
||||
miniStream = readChain(cfb, fat, rootStart, rootSize, sectorSize, sectorTotal, "mini stream");
|
||||
}
|
||||
if (firstMiniFat != FREESECT && firstMiniFat != ENDOFCHAIN && firstMiniFat <= MAX_SECT) {
|
||||
int[] miniFatSects = chain(fat, firstMiniFat, sectorTotal, "цепочка MiniFAT");
|
||||
miniFat = new int[miniFatSects.length * sectorSize / 4];
|
||||
int i = 0;
|
||||
for (int sect : miniFatSects) {
|
||||
int base = sectorOffset(sect, sectorSize);
|
||||
for (int off = 0; off + 4 <= sectorSize && base + off + 4 <= cfb.length; off += 4) {
|
||||
miniFat[i++] = (int) u32(cfb, base + off);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// второй проход: содержимое потоков
|
||||
Map<String, byte[]> result = new HashMap<>();
|
||||
for (Entry e : entries) {
|
||||
byte[] data;
|
||||
if (e.size() >= cutoff) {
|
||||
data = readChain(cfb, fat, e.start(), e.size(), sectorSize, sectorTotal,
|
||||
"цепочка потока «" + e.name() + "»");
|
||||
} else {
|
||||
data = readMiniChain(miniFat, miniStream, e.start(), e.size(), miniSectorSize);
|
||||
}
|
||||
result.put(e.name(), data);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Directory-запись потока: имя + начало цепочки + размер (до чтения данных). */
|
||||
private record Entry(String name, long start, long size) {
|
||||
}
|
||||
|
||||
/** Потока {@code name} нет → пустой массив; поиск регистронезависимый (MS-CFB §2.6). */
|
||||
static byte[] stream(Map<String, byte[]> streams, String name) {
|
||||
byte[] direct = streams.get(name);
|
||||
if (direct != null) {
|
||||
return direct;
|
||||
}
|
||||
for (Map.Entry<String, byte[]> e : streams.entrySet()) {
|
||||
if (e.getKey().equalsIgnoreCase(name)) {
|
||||
return e.getValue();
|
||||
}
|
||||
}
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
// ---------- internals ----------
|
||||
|
||||
private static boolean startsWithSignature(byte[] b) {
|
||||
for (int i = 0; i < SIGNATURE.length; i++) {
|
||||
if (b[i] != SIGNATURE[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Список FAT-секторов: 109 из заголовка + DIFAT-цепочка (MS-CFB §2.5). */
|
||||
private static int[] readFat(byte[] cfb, int sectorSize, long firstDifat,
|
||||
long difatCount, int sectorTotal) {
|
||||
List<Integer> fatSectors = new ArrayList<>();
|
||||
for (int i = 0; i < DIFAT_ENTRIES_IN_HEADER; i++) {
|
||||
long s = u32(cfb, OFF_DIFAT_ENTRIES + i * 4);
|
||||
if (s != FREESECT && s <= MAX_SECT) {
|
||||
fatSectors.add((int) s);
|
||||
}
|
||||
}
|
||||
long seen = 0;
|
||||
long sect = firstDifat;
|
||||
long difatLimit = Math.min(difatCount + 1, sectorTotal + 1);
|
||||
while (sect != FREESECT && sect != ENDOFCHAIN && sect <= MAX_SECT) {
|
||||
if (++seen > difatLimit) {
|
||||
throw new ValidationException("Циклическая DIFAT-цепочка в .doc");
|
||||
}
|
||||
int base = sectorOffset((int) sect, sectorSize);
|
||||
requireInFile(base, sectorSize, cfb.length, "DIFAT-сектор");
|
||||
int entries = sectorSize / 4 - 1;
|
||||
for (int i = 0; i < entries; i++) {
|
||||
long s = u32(cfb, base + i * 4);
|
||||
if (s != FREESECT && s <= MAX_SECT) {
|
||||
fatSectors.add((int) s);
|
||||
}
|
||||
}
|
||||
sect = u32(cfb, base + entries * 4);
|
||||
}
|
||||
if (fatSectors.size() > sectorTotal) {
|
||||
throw new ValidationException("DIFAT объявляет больше FAT-секторов, чем может быть в файле");
|
||||
}
|
||||
int[] fat = new int[fatSectors.size() * sectorSize / 4];
|
||||
int i = 0;
|
||||
for (int fs : fatSectors) {
|
||||
int base = sectorOffset(fs, sectorSize);
|
||||
requireInFile(base, sectorSize, cfb.length, "FAT-сектор");
|
||||
for (int off = 0; off + 4 <= sectorSize && base + off + 4 <= cfb.length; off += 4) {
|
||||
fat[i++] = (int) u32(cfb, base + off);
|
||||
}
|
||||
}
|
||||
return fat;
|
||||
}
|
||||
|
||||
/** Цепочка секторов по FAT; цикл/выход за FAT → {@link ValidationException}. */
|
||||
private static int[] chain(int[] fat, long start, int sectorTotal, String what) {
|
||||
List<Integer> sectors = new ArrayList<>();
|
||||
long sect = start;
|
||||
int limit = Math.min(fat.length, sectorTotal) + 1;
|
||||
while (sect != ENDOFCHAIN && sect >= 0 && sect <= MAX_SECT) {
|
||||
if (sectors.size() > limit) {
|
||||
throw new ValidationException("Циклическая " + what + " в .doc");
|
||||
}
|
||||
if (sect >= fat.length) {
|
||||
throw new ValidationException("Сектор за концом FAT в .doc: " + what);
|
||||
}
|
||||
sectors.add((int) sect);
|
||||
sect = fat[(int) sect] & 0xFFFFFFFFL;
|
||||
}
|
||||
return sectors.stream().mapToInt(Integer::intValue).toArray();
|
||||
}
|
||||
|
||||
private static byte[] readChain(byte[] cfb, int[] fat, long start, long size,
|
||||
int sectorSize, int sectorTotal, String what) {
|
||||
byte[] out = new byte[(int) size];
|
||||
int done = 0;
|
||||
int[] chain = chain(fat, start, sectorTotal, what);
|
||||
for (int sect : chain) {
|
||||
if (done >= size) {
|
||||
break;
|
||||
}
|
||||
int base = sectorOffset(sect, sectorSize);
|
||||
int n = (int) Math.min(sectorSize, size - done);
|
||||
if (base + n > cfb.length) {
|
||||
throw new ValidationException("Поток .doc ссылается за конец файла: " + what);
|
||||
}
|
||||
System.arraycopy(cfb, base, out, done, n);
|
||||
done += n;
|
||||
}
|
||||
if (done != size) {
|
||||
throw new ValidationException("Обрезанный поток .doc: " + what + " (ожидалось " + size
|
||||
+ " байт, цепочка дала " + done + ")");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] readMiniChain(int[] miniFat, byte[] miniStream,
|
||||
long start, long size, int miniSectorSize) {
|
||||
byte[] out = new byte[(int) size];
|
||||
if (size == 0) {
|
||||
return out;
|
||||
}
|
||||
if (miniStream == null || miniFat == null) {
|
||||
throw new ValidationException("Mini stream отсутствует, но есть поток в mini FAT");
|
||||
}
|
||||
int done = 0;
|
||||
long sect = start;
|
||||
int limit = miniFat.length + 1;
|
||||
int steps = 0;
|
||||
while (sect != ENDOFCHAIN && sect >= 0 && sect <= MAX_SECT) {
|
||||
if (++steps > limit) {
|
||||
throw new ValidationException("Циклическая MiniFAT-цепочка в .doc");
|
||||
}
|
||||
if (sect >= miniFat.length) {
|
||||
throw new ValidationException("Mini-сектор за концом MiniFAT в .doc");
|
||||
}
|
||||
int base = (int) sect * miniSectorSize;
|
||||
int n = Math.min(miniSectorSize, (int) size - done);
|
||||
if (base + n > miniStream.length) {
|
||||
throw new ValidationException("Mini-поток .doc ссылается за конец mini stream");
|
||||
}
|
||||
System.arraycopy(miniStream, base, out, done, n);
|
||||
done += n;
|
||||
sect = miniFat[(int) sect] & 0xFFFFFFFFL;
|
||||
}
|
||||
if (done != size) {
|
||||
throw new ValidationException("Обрезанный mini-поток .doc (ожидалось " + size
|
||||
+ " байт, цепочка дала " + done + ")");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static int sectorOffset(int sector, int sectorSize) {
|
||||
return (sector + 1) * sectorSize;
|
||||
}
|
||||
|
||||
private static void requireInFile(int offset, int len, int fileLen, String what) {
|
||||
if (offset < HEADER_SIZE || offset + len > fileLen) {
|
||||
throw new ValidationException("Ссылка за конец файла в .doc: " + what);
|
||||
}
|
||||
}
|
||||
|
||||
private static String entryName(byte[] cfb, int entryBase) {
|
||||
int nameLen = u16(cfb, entryBase + ENTRY_NAME_LEN);
|
||||
if (nameLen < 2 || nameLen > 64) {
|
||||
return "";
|
||||
}
|
||||
return new String(cfb, entryBase, nameLen - 2, StandardCharsets.UTF_16LE);
|
||||
}
|
||||
|
||||
private static int u16(byte[] b, int off) {
|
||||
return (b[off] & 0xFF) | ((b[off + 1] & 0xFF) << 8);
|
||||
}
|
||||
|
||||
static long u32(byte[] b, int off) {
|
||||
return (b[off] & 0xFFL) | ((b[off + 1] & 0xFFL) << 8)
|
||||
| ((b[off + 2] & 0xFFL) << 16) | ((b[off + 3] & 0xFFL) << 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Индекс прямых символьных свойств CHPX: FC-диапазон → Grpprl.
|
||||
*
|
||||
* <p>Алгоритм [MS-DOC] §2.4.6.2 (Direct Character Formatting): PlcfBteChpx —
|
||||
* PLC (aFc n+1, PnFkpChpx n по 4 байта: pn 22 бита); ChpxFkp-страница по
|
||||
* {@code pn*512} в WordDocument-потоке: rgfc (crun+1 × 4 FC-границы),
|
||||
* rgb (crun × 1 байт, смещение Chpx = байт×2), crun — последний байт
|
||||
* страницы; Chpx = cb (1) + grpprl (cb байт). Диапазон rgfc[j]..rgfc[j+1]
|
||||
* получает grpprl своего Chpx; bOffset=0 — свойств нет (дефолт).</p>
|
||||
*/
|
||||
final class ChpxIndex {
|
||||
|
||||
/** Размер FKP-страницы, байт (§2.9, ChpxFkp). */
|
||||
private static final int FKP_PAGE_SIZE = 512;
|
||||
|
||||
private record Range(long fcStart, long fcEnd, byte[] grpprl) {
|
||||
}
|
||||
|
||||
private final List<Range> ranges = new ArrayList<>();
|
||||
|
||||
private ChpxIndex(byte[] tableStream, long fcBte, long lcbBte, byte[] wordDocument) {
|
||||
if (lcbBte <= 0) {
|
||||
return;
|
||||
}
|
||||
if (fcBte < 0 || fcBte + lcbBte > tableStream.length || (lcbBte - 4) % 8 != 0) {
|
||||
throw new ValidationException("Битый PlcfBteChpx в .doc");
|
||||
}
|
||||
int n = (int) ((lcbBte - 4) / 8);
|
||||
for (int i = 0; i < n; i++) {
|
||||
long fcStart = CfbReader.u32(tableStream, (int) fcBte + i * 4);
|
||||
long fcEnd = CfbReader.u32(tableStream, (int) fcBte + i * 4 + 4);
|
||||
long pn = CfbReader.u32(tableStream, (int) fcBte + (n + 1) * 4 + i * 4) & 0x3FFFFFL;
|
||||
long pageOff = pn * FKP_PAGE_SIZE;
|
||||
if (pageOff + FKP_PAGE_SIZE > wordDocument.length) {
|
||||
throw new ValidationException("ChpxFkp вне WordDocument-потока в .doc");
|
||||
}
|
||||
int crun = wordDocument[(int) (pageOff + FKP_PAGE_SIZE - 1)] & 0xFF;
|
||||
if (crun < 1 || crun > 0x65) {
|
||||
throw new ValidationException("Битый crun в ChpxFkp .doc");
|
||||
}
|
||||
for (int j = 0; j < crun; j++) {
|
||||
long rgfcStart = CfbReader.u32(wordDocument, (int) pageOff + j * 4);
|
||||
long rgfcEnd = CfbReader.u32(wordDocument, (int) pageOff + (j + 1) * 4);
|
||||
int bx = wordDocument[(int) pageOff + 4 * (crun + 1) + j] & 0xFF;
|
||||
if (bx == 0 || rgfcEnd <= rgfcStart) {
|
||||
continue;
|
||||
}
|
||||
int chpxOff = (int) pageOff + bx * 2;
|
||||
int cb = wordDocument[chpxOff] & 0xFF;
|
||||
if (cb == 0 || chpxOff + 1 + cb > pageOff + FKP_PAGE_SIZE) {
|
||||
continue;
|
||||
}
|
||||
byte[] grpprl = new byte[cb];
|
||||
System.arraycopy(wordDocument, chpxOff + 1, grpprl, 0, cb);
|
||||
ranges.add(new Range(Math.max(rgfcStart, fcStart), Math.min(rgfcEnd, fcEnd), grpprl));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static ChpxIndex read(byte[] tableStream, long fcBte, long lcbBte, byte[] wordDocument) {
|
||||
return new ChpxIndex(tableStream, fcBte, lcbBte, wordDocument);
|
||||
}
|
||||
|
||||
/** Grpprl для FC или пустой массив (дефолтные свойства). */
|
||||
byte[] grpprlFor(long fc) {
|
||||
for (Range r : ranges) {
|
||||
if (fc >= r.fcStart() && fc < r.fcEnd()) {
|
||||
return r.grpprl();
|
||||
}
|
||||
}
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
/** FC конца текущего диапазона свойств (или {@code fcLimit}) — граница рана. */
|
||||
long rangeEnd(long fc, long fcLimit) {
|
||||
for (Range r : ranges) {
|
||||
if (fc >= r.fcStart() && fc < r.fcEnd()) {
|
||||
return Math.min(r.fcEnd(), fcLimit);
|
||||
}
|
||||
}
|
||||
return fcLimit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Дешёвый разбор бинарного .doc: CFB-контейнер → FIB → piece table.
|
||||
*
|
||||
* <p>Общая основа моста {@link DocToDocx} и проверки числа страниц
|
||||
* ({@link #countPages()}), которую {@code WordPdfValidator} вызывает через
|
||||
* {@link DocToDocx#countPages(byte[]}) <b>до</b> конвертации в .docx —
|
||||
* аналог lightweight-прохода валидатора по zip.</p>
|
||||
*
|
||||
* <p>Контракт ошибок: любой некорректный вход (не CFB, не Word, шифрование,
|
||||
* Word 6/95, обрезка) — {@link ValidationException}.</p>
|
||||
*/
|
||||
final class DocFile {
|
||||
|
||||
private final Map<String, byte[]> streams;
|
||||
private final byte[] wordDocument;
|
||||
private final FibHeader fib;
|
||||
private final byte[] table;
|
||||
private final PieceTable pieces;
|
||||
|
||||
private DocFile(byte[] docBytes) {
|
||||
streams = CfbReader.readStreams(docBytes);
|
||||
if (CfbReader.stream(streams, "EncryptedPackage").length > 0
|
||||
|| CfbReader.stream(streams, "EncryptedStream").length > 0) {
|
||||
throw new ValidationException(
|
||||
"Документ зашифрован (пароль на открытие) — конвертация невозможна");
|
||||
}
|
||||
wordDocument = CfbReader.stream(streams, "WordDocument");
|
||||
if (wordDocument.length == 0) {
|
||||
throw new ValidationException("Содержимое не похоже на .doc Word 97–2003");
|
||||
}
|
||||
fib = FibHeader.read(wordDocument);
|
||||
table = CfbReader.stream(streams, fib.use1Table() ? "1Table" : "0Table");
|
||||
if (table.length == 0) {
|
||||
throw new ValidationException("В .doc нет потока "
|
||||
+ (fib.use1Table() ? "1Table" : "0Table"));
|
||||
}
|
||||
pieces = PieceTable.read(table, fib.fcClx(), fib.lcbClx(), wordDocument);
|
||||
}
|
||||
|
||||
static DocFile open(byte[] docBytes) {
|
||||
return new DocFile(docBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Число страниц (нижняя оценка, тот же нижний контур, что lightweight-скан
|
||||
* валидатора для .docx): {@code max(кэш PageCount [MS-OLEPS], 1 + ручные
|
||||
* разрывы 0x0C (§2.8.26) − непрерывные межсекционные разрывы (sprmSBkc) +
|
||||
* абзацы с sprmPFPageBreakBefore)}. Кэша нет (0) — работают разрывы.
|
||||
*/
|
||||
int countPages() {
|
||||
int cached = SummaryInfo.pageCount(
|
||||
CfbReader.stream(streams, "\u0005SummaryInformation"));
|
||||
PapxIndex papx = PapxIndex.read(table, fib.fcPlcfBtePapx(), fib.lcbPlcfBtePapx(),
|
||||
wordDocument);
|
||||
Sections sections = Sections.read(table, fib.fcPlcfSed(), fib.lcbPlcfSed(),
|
||||
wordDocument);
|
||||
return Math.max(cached, 1 + countPageBreaks() - sections.continuousSectionEnds()
|
||||
+ papx.countPageBreakBefore());
|
||||
}
|
||||
|
||||
/** Число символов 0x0C (разрыв страницы/колонки/секции, §2.2) в основном тексте. */
|
||||
int countPageBreaks() {
|
||||
int count = 0;
|
||||
for (int cp = 0; cp < fib.ccpText(); cp++) {
|
||||
if (pieces.charAt(cp) == DocToDocx.PAGE_OR_SECTION_BREAK) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
Map<String, byte[]> streams() {
|
||||
return streams;
|
||||
}
|
||||
|
||||
byte[] wordDocument() {
|
||||
return wordDocument;
|
||||
}
|
||||
|
||||
FibHeader fib() {
|
||||
return fib;
|
||||
}
|
||||
|
||||
byte[] table() {
|
||||
return table;
|
||||
}
|
||||
|
||||
PieceTable pieces() {
|
||||
return pieces;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Мост бинарного .doc (Word 97–2003) → минимальный transitional-.docx.
|
||||
*
|
||||
* <p>Точки входа пакета: {@link #convert(byte[])} (конвертация) и
|
||||
* {@link #countPages(byte[])} (нижняя оценка страниц для валидатора).
|
||||
* Разбор строго по [MS-DOC]/[MS-CFB]/[MS-OLEPS]: контейнер — {@link CfbReader},
|
||||
* общий разбор — {@link DocFile}, заголовок — {@link FibHeader}, текст —
|
||||
* {@link PieceTable} (§2.4.1), прямые
|
||||
* свойства — {@link ChpxIndex}/{@link PapxIndex} (§2.4.6.1/.2), полоса набора —
|
||||
* {@link Sections} (§2.8.26). Стили STSH, списки, таблицы-как-таблицы,
|
||||
* картинки и колонтитуки в первом инкременте не переносятся: содержимое ячеек
|
||||
* становится абзацами, объекты/сноски/комментарии (0x01/0x02/0x05/0x08) и
|
||||
* инструкции полей (0x13–0x14) выбрасываются, результат поля (0x14–0x15)
|
||||
* остаётся; прочие управляющие символы не эмитятся.</p>
|
||||
*
|
||||
* <p>Контракт ошибок: любой некорректный вход (не CFB, не Word, шифрование,
|
||||
* Word 6/95, обрезка, цикл в цепочках, страницы сверх лимита) —
|
||||
* {@link ValidationException}.</p>
|
||||
*/
|
||||
public final class DocToDocx {
|
||||
|
||||
/** Символы .doc (§2.2/§2.4). */
|
||||
private static final char CELL_MARK = 0x07;
|
||||
private static final char EMBEDDED_OBJECT = 0x01;
|
||||
private static final char ANNOTATION_REF = 0x05;
|
||||
private static final char DRAWN_OBJECT = 0x08;
|
||||
private static final char FOOTNOTE_REF = 0x02;
|
||||
private static final char TAB = 0x09;
|
||||
private static final char LINE_BREAK = 0x0B;
|
||||
static final char PAGE_OR_SECTION_BREAK = 0x0C;
|
||||
private static final char PARA_MARK = 0x0D;
|
||||
private static final char FIELD_BEGIN = 0x13;
|
||||
private static final char FIELD_SEPARATOR = 0x14;
|
||||
private static final char FIELD_END = 0x15;
|
||||
|
||||
/** Ниже — управляющие символы без текстового смысла (§2.2) → граница рана. */
|
||||
private static final char CONTROL_LIMIT = 0x20;
|
||||
private static final char NON_BREAKING_HYPHEN = 0x1E;
|
||||
private static final char SOFT_HYPHEN = 0x1F;
|
||||
|
||||
/** Content-type/тип связи частей колонтитуков (ECMA-376 Part 2). */
|
||||
private static final String HEADER_CONTENT_TYPE =
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml";
|
||||
private static final String FOOTER_CONTENT_TYPE =
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml";
|
||||
private static final String HEADER_REL_TYPE =
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
|
||||
private static final String FOOTER_REL_TYPE =
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
|
||||
private static final String IMAGE_REL_TYPE =
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
|
||||
|
||||
private DocToDocx() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Конвертирует байты .doc в байты .docx для штатного пайплайна.
|
||||
*
|
||||
* <p>Число страниц здесь НЕ проверяется — это ответственность
|
||||
* {@code WordPdfValidator.checkPageCountDoc} (тот же разбор через
|
||||
* {@link #countPages(byte[])}, но до всякой конвертации).</p>
|
||||
*
|
||||
* @param docBytes контейнер Word 97–2003
|
||||
* @throws ValidationException на некорректном/зашифрованном/чужом входе
|
||||
*/
|
||||
public static byte[] convert(byte[] docBytes) {
|
||||
DocFile file = DocFile.open(docBytes);
|
||||
FibHeader fib = file.fib();
|
||||
FontTable fonts = FontTable.read(file.table(), fib.fcSttbfFfn(), fib.lcbSttbfFfn());
|
||||
PapxIndex papx = PapxIndex.read(file.table(), fib.fcPlcfBtePapx(), fib.lcbPlcfBtePapx(),
|
||||
file.wordDocument());
|
||||
Sections sections = Sections.read(file.table(), fib.fcPlcfSed(), fib.lcbPlcfSed(),
|
||||
file.wordDocument());
|
||||
ChpxIndex chpx = ChpxIndex.read(file.table(), fib.fcPlcfBteChpx(), fib.lcbPlcfBteChpx(),
|
||||
file.wordDocument());
|
||||
Headers headers = Headers.read(file.table(), fib.fcPlcfHdd(), fib.lcbPlcfHdd(),
|
||||
fib.ccpText() + fib.ccpFtn());
|
||||
List<DocxWriter.Part> parts = new ArrayList<>();
|
||||
DocxBody body = new DocxBody(file.pieces(), chpx, papx, fonts, fib.ccpText(),
|
||||
CfbReader.stream(file.streams(), "Data"), parts);
|
||||
String headerRelId = null;
|
||||
String footerRelId = null;
|
||||
// Odd header/footer секции 0 → type="default" (FOP не различает
|
||||
// чётные/нечётные); guard-абзац истории отбрасывается
|
||||
Headers.Story hdr = headers.oddHeader(0);
|
||||
if (hdr.hasContent()) {
|
||||
parts.add(new DocxWriter.Part("word/header1.xml", HEADER_CONTENT_TYPE,
|
||||
HEADER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:hdr",
|
||||
body.buildRange(hdr.cpStart(), hdr.contentEnd(), true))));
|
||||
headerRelId = "rId" + parts.size();
|
||||
}
|
||||
Headers.Story ftr = headers.oddFooter(0);
|
||||
if (ftr.hasContent()) {
|
||||
parts.add(new DocxWriter.Part("word/footer1.xml", FOOTER_CONTENT_TYPE,
|
||||
FOOTER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:ftr",
|
||||
body.buildRange(ftr.cpStart(), ftr.contentEnd(), true))));
|
||||
footerRelId = "rId" + parts.size();
|
||||
}
|
||||
return DocxWriter.write(body.build(sections, headerRelId, footerRelId), parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Нижняя оценка числа страниц бинарного .doc (кэш PageCount + явные
|
||||
* разрывы) — для {@code WordPdfValidator.checkPageCountDoc}.
|
||||
*
|
||||
* @throws ValidationException на некорректном/зашифрованном/чужом входе
|
||||
*/
|
||||
public static int countPages(byte[] docBytes) {
|
||||
return DocFile.open(docBytes).countPages();
|
||||
}
|
||||
|
||||
/** Текст CP 0..ccpText → XML-тело {@code <w:body>}. */
|
||||
private static final class DocxBody {
|
||||
|
||||
private final PieceTable pieces;
|
||||
private final ChpxIndex chpx;
|
||||
private final PapxIndex papx;
|
||||
private final FontTable fonts;
|
||||
private final int ccpText;
|
||||
/** Data-поток (.doc) для BLIP по sprmCPicLocation. */
|
||||
private final byte[] dataStream;
|
||||
/** Части пакета (колонтитуки + media); id связи = rId{позиция+1}. */
|
||||
private final List<DocxWriter.Part> parts;
|
||||
private final Deque<Boolean> fieldStack = new ArrayDeque<>();
|
||||
/** Состояние полей текущего buildRange (сбрасывается на входе). */
|
||||
private boolean fieldsAsSimple;
|
||||
private final StringBuilder instr = new StringBuilder();
|
||||
private boolean capturing;
|
||||
private int fldSimpleOpen;
|
||||
|
||||
DocxBody(PieceTable pieces, ChpxIndex chpx, PapxIndex papx, FontTable fonts,
|
||||
int ccpText, byte[] dataStream, List<DocxWriter.Part> parts) {
|
||||
this.pieces = pieces;
|
||||
this.chpx = chpx;
|
||||
this.papx = papx;
|
||||
this.fonts = fonts;
|
||||
this.ccpText = ccpText;
|
||||
this.dataStream = dataStream;
|
||||
this.parts = parts;
|
||||
}
|
||||
|
||||
String build(Sections sections, String headerRelId, String footerRelId) {
|
||||
return buildRange(0, ccpText, false)
|
||||
+ sectPr(sections, headerRelId, footerRelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Абзацы CP-диапазона [from, to) без sectPr — основной текст или
|
||||
* история колонтитука. {@code fieldsAsSimple}: поля PAGE/NUMPAGES/
|
||||
* SECTIONPAGES (первый токен инструкции, §2.9.133) → {@code w:fldSimple}
|
||||
* (FOP пере-вычисляет их, кэш результата отбрасывается); прочие поля —
|
||||
* как в теле: инструкция скрыта, кэш-результат сохранён.
|
||||
*/
|
||||
String buildRange(int from, int to, boolean fieldsAsSimple) {
|
||||
this.fieldsAsSimple = fieldsAsSimple;
|
||||
fieldStack.clear();
|
||||
instr.setLength(0);
|
||||
capturing = false;
|
||||
fldSimpleOpen = 0;
|
||||
StringBuilder body = new StringBuilder();
|
||||
int cp = from;
|
||||
while (cp < to) {
|
||||
int paraStart = cp;
|
||||
StringBuilder runs = new StringBuilder();
|
||||
char termMark = 0;
|
||||
while (cp < to) {
|
||||
char ch = pieces.charAt(cp);
|
||||
if (ch == PARA_MARK || ch == CELL_MARK) {
|
||||
termMark = ch;
|
||||
cp++;
|
||||
break;
|
||||
}
|
||||
long fc = pieces.fcOf(cp);
|
||||
byte[] grpprl = chpx.grpprlFor(fc);
|
||||
int step = pieces.step(cp);
|
||||
long rangeEnd = chpx.rangeEnd(fc, Long.MAX_VALUE >>> 1);
|
||||
int runEnd = (int) Math.max(cp + 1L, Math.min(
|
||||
pieces.nextPieceBoundary(cp, to),
|
||||
cp + (rangeEnd - fc) / step));
|
||||
cp = emitRun(runs, cp, runEnd, grpprl);
|
||||
}
|
||||
emitPara(body, paraStart, runs, termMark);
|
||||
}
|
||||
return body.toString();
|
||||
}
|
||||
|
||||
/** Один ран свойств CHPX; возвращает CP после рана. */
|
||||
private int emitRun(StringBuilder runs, int cpStart, int cpEnd, byte[] grpprl) {
|
||||
String rPr = runProps(grpprl);
|
||||
StringBuilder content = new StringBuilder();
|
||||
StringBuilder text = new StringBuilder();
|
||||
int cp = cpStart;
|
||||
while (cp < cpEnd) {
|
||||
char ch = pieces.charAt(cp);
|
||||
if (ch == PARA_MARK || ch == CELL_MARK) {
|
||||
// CHPX-ран может простираться за границу абзаца/ячейки —
|
||||
// саму границу не потребляем, её видит внешний цикл
|
||||
break;
|
||||
}
|
||||
switch (ch) {
|
||||
case TAB:
|
||||
flushText(text, content);
|
||||
if (capturing) {
|
||||
instr.append(' ');
|
||||
} else if (visible()) {
|
||||
content.append("<w:tab/>");
|
||||
}
|
||||
break;
|
||||
case LINE_BREAK:
|
||||
flushText(text, content);
|
||||
if (visible()) {
|
||||
content.append("<w:br/>");
|
||||
}
|
||||
break;
|
||||
case PAGE_OR_SECTION_BREAK:
|
||||
flushText(text, content);
|
||||
if (visible()) {
|
||||
content.append("<w:br w:type=\"page\"/>");
|
||||
}
|
||||
break;
|
||||
case FIELD_BEGIN:
|
||||
// fldSimple — sibling w:r, ран закрывается на границе поля
|
||||
closeRun(runs, rPr, content, text);
|
||||
if (fieldsAsSimple) {
|
||||
instr.setLength(0);
|
||||
capturing = true;
|
||||
}
|
||||
fieldStack.push(Boolean.FALSE);
|
||||
break;
|
||||
case FIELD_SEPARATOR:
|
||||
closeRun(runs, rPr, content, text);
|
||||
capturing = false;
|
||||
if (!fieldStack.isEmpty()) {
|
||||
fieldStack.pop();
|
||||
fieldStack.push(Boolean.TRUE);
|
||||
}
|
||||
String field = fieldsAsSimple ? pageField(instr) : null;
|
||||
if (field != null) {
|
||||
runs.append("<w:fldSimple w:instr=\"").append(escapeAttr(field))
|
||||
.append("\">");
|
||||
fldSimpleOpen++;
|
||||
}
|
||||
break;
|
||||
case FIELD_END:
|
||||
closeRun(runs, rPr, content, text);
|
||||
if (fldSimpleOpen > 0) {
|
||||
runs.append("</w:fldSimple>");
|
||||
fldSimpleOpen--;
|
||||
}
|
||||
if (!fieldStack.isEmpty()) {
|
||||
fieldStack.pop();
|
||||
}
|
||||
break;
|
||||
case EMBEDDED_OBJECT:
|
||||
flushText(text, content);
|
||||
if (visible()) {
|
||||
emitPicture(runs, rPr, cp);
|
||||
}
|
||||
break;
|
||||
case FOOTNOTE_REF:
|
||||
case ANNOTATION_REF:
|
||||
case DRAWN_OBJECT:
|
||||
flushText(text, content);
|
||||
break;
|
||||
case NON_BREAKING_HYPHEN:
|
||||
appendVisible(text, '\u2011');
|
||||
break;
|
||||
case SOFT_HYPHEN:
|
||||
appendVisible(text, '\u00AD');
|
||||
break;
|
||||
default:
|
||||
if (capturing) {
|
||||
instr.append(ch);
|
||||
} else if (ch < CONTROL_LIMIT) {
|
||||
flushText(text, content);
|
||||
} else {
|
||||
appendVisible(text, ch);
|
||||
}
|
||||
break;
|
||||
}
|
||||
cp++;
|
||||
}
|
||||
closeRun(runs, rPr, content, text);
|
||||
return cp;
|
||||
}
|
||||
|
||||
/** Закрыть накопленный {@code <w:r>}: fldSimple обязан лежать вне рана. */
|
||||
private void closeRun(StringBuilder runs, String rPr, StringBuilder content,
|
||||
StringBuilder text) {
|
||||
flushText(text, content);
|
||||
if (content.length() > 0) {
|
||||
runs.append("<w:r>").append(rPr).append(content).append("</w:r>");
|
||||
content.setLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* U+0001 с {@code sprmCPicLocation} → inline-DrawingML на image-часть
|
||||
* (та же форма, что плейсхолдеры {@code OleObjectNormalizer}); OLE-
|
||||
* бинарник (NilPICFAndBinData) и битый/векторный BLIP — объект
|
||||
* пропускается. CHPX берётся по CP самого символа: ран может
|
||||
* простираться дальше картинки.
|
||||
*/
|
||||
private void emitPicture(StringBuilder runs, String rPr, int cp) {
|
||||
long picLoc = picLocationFor(chpx.grpprlFor(pieces.fcOf(cp)));
|
||||
if (picLoc < 0) {
|
||||
return;
|
||||
}
|
||||
OfficeArt.Picture pic = OfficeArt.read(dataStream, picLoc);
|
||||
if (pic == null) {
|
||||
return;
|
||||
}
|
||||
int imageNo = 1;
|
||||
for (DocxWriter.Part p : parts) {
|
||||
if (p.entry().startsWith("word/media/")) {
|
||||
imageNo++;
|
||||
}
|
||||
}
|
||||
String entry = "word/media/image" + imageNo + "." + pic.extension();
|
||||
parts.add(new DocxWriter.Part(entry, pic.contentType(), IMAGE_REL_TYPE, pic.data()));
|
||||
String relId = "rId" + parts.size();
|
||||
runs.append("<w:r>").append(rPr).append("<w:drawing>")
|
||||
.append("<wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\">")
|
||||
.append("<wp:extent cx=\"").append(pic.cxEmu())
|
||||
.append("\" cy=\"").append(pic.cyEmu()).append("\"/>")
|
||||
.append("<wp:docPr id=\"").append(imageNo).append("\" name=\"Picture ")
|
||||
.append(imageNo).append("\"/>")
|
||||
.append("<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org")
|
||||
.append("/drawingml/2006/picture\">")
|
||||
.append("<pic:pic><pic:nvPicPr><pic:cNvPr id=\"").append(imageNo)
|
||||
.append("\" name=\"").append(entry).append("\"/><pic:cNvPicPr/></pic:nvPicPr>")
|
||||
.append("<pic:blipFill><a:blip r:embed=\"").append(relId)
|
||||
.append("\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>")
|
||||
.append("<pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"")
|
||||
.append(pic.cxEmu()).append("\" cy=\"").append(pic.cyEmu())
|
||||
.append("\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom>")
|
||||
.append("</pic:spPr></pic:pic></a:graphicData></a:graphic>")
|
||||
.append("</wp:inline></w:drawing></w:r>");
|
||||
}
|
||||
|
||||
/** Операнд sprmCPicLocation из CHPX; -1 — атрибута нет. */
|
||||
private static long picLocationFor(byte[] grpprl) {
|
||||
long[] loc = {-1};
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_C_PIC_LOCATION && len >= 4) {
|
||||
loc[0] = Grpprl.operandInt(buf, off, len) & 0xFFFF_FFFFL;
|
||||
}
|
||||
});
|
||||
return loc[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя поля PAGE-семейства по инструкции (§2.9.133): первый токен
|
||||
* (регистронезависимо), суффиксы {@code \* MERGEFORMAT} и т.п. не
|
||||
* мешают. Не PAGE-семейство → {@code null} (кэш-результат).
|
||||
*/
|
||||
private static String pageField(CharSequence instruction) {
|
||||
String s = instruction.toString().trim();
|
||||
int end = 0;
|
||||
while (end < s.length() && !Character.isWhitespace(s.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return switch (s.substring(0, end).toUpperCase(Locale.ROOT)) {
|
||||
case "PAGE", "NUMPAGES", "SECTIONPAGES" -> s;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean visible() {
|
||||
return fieldStack.isEmpty() || fieldStack.peek();
|
||||
}
|
||||
|
||||
private void appendVisible(StringBuilder text, char ch) {
|
||||
if (visible()) {
|
||||
text.append(ch);
|
||||
}
|
||||
}
|
||||
|
||||
private void flushText(StringBuilder text, StringBuilder content) {
|
||||
if (text.length() > 0) {
|
||||
content.append("<w:t xml:space=\"preserve\">").append(escape(text)).append("</w:t>");
|
||||
text.setLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
private void emitPara(StringBuilder body, int paraStart, StringBuilder runs, char termMark) {
|
||||
byte[] grpprl = papx.grpprlFor(pieces.fcOf(paraStart));
|
||||
// Конец строки таблицы — пустой абзац с 0x07 и sprmPFTtp (§2.2):
|
||||
// это не ячейка, в вывод не попадает
|
||||
if (runs.length() == 0 && termMark == CELL_MARK && hasTtp(grpprl)) {
|
||||
return;
|
||||
}
|
||||
String pPr = paraProps(grpprl);
|
||||
if (runs.length() == 0 && pPr.isEmpty()) {
|
||||
body.append("<w:p/>");
|
||||
return;
|
||||
}
|
||||
body.append("<w:p>").append(pPr).append(runs).append("</w:p>");
|
||||
}
|
||||
|
||||
private static boolean hasTtp(byte[] grpprl) {
|
||||
boolean[] ttp = {false};
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_P_F_TTP) {
|
||||
ttp[0] = Grpprl.toggleOn(buf, off);
|
||||
}
|
||||
});
|
||||
return ttp[0];
|
||||
}
|
||||
|
||||
/** rPr по CHPX-порядку CT_RPr: rFonts, b, i, strike, color, sz, szCs, u. */
|
||||
private String runProps(byte[] grpprl) {
|
||||
RunProps p = new RunProps();
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
switch (sprm) {
|
||||
case Grpprl.SPRM_C_F_BOLD -> p.bold = Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_C_F_ITALIC -> p.italic = Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_C_F_STRIKE -> p.strike = Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_C_KUL -> p.underline = Grpprl.operandInt(buf, off, len) != 0;
|
||||
case Grpprl.SPRM_C_HPS -> p.sz = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_HPS_BI -> p.szCs = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_RG_FTC0 -> p.ftc0 = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_RG_FTC1 -> p.ftc1 = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_CV -> p.color = colorOf(buf, off, len);
|
||||
default -> { }
|
||||
}
|
||||
});
|
||||
StringBuilder xml = new StringBuilder();
|
||||
String ascii = p.ftc0 >= 0 ? fonts.font(p.ftc0) : null;
|
||||
String cs = p.ftc1 >= 0 ? fonts.font(p.ftc1) : null;
|
||||
if (ascii != null || cs != null) {
|
||||
xml.append("<w:rFonts");
|
||||
if (ascii != null) {
|
||||
xml.append(" w:ascii=\"").append(escapeAttr(ascii))
|
||||
.append("\" w:hAnsi=\"").append(escapeAttr(ascii)).append('"');
|
||||
}
|
||||
if (cs != null) {
|
||||
xml.append(" w:cs=\"").append(escapeAttr(cs)).append('"');
|
||||
}
|
||||
xml.append("/>");
|
||||
}
|
||||
if (p.bold) {
|
||||
xml.append("<w:b/>");
|
||||
}
|
||||
if (p.italic) {
|
||||
xml.append("<w:i/>");
|
||||
}
|
||||
if (p.strike) {
|
||||
xml.append("<w:strike/>");
|
||||
}
|
||||
if (p.color != null) {
|
||||
xml.append("<w:color w:val=\"").append(p.color).append("\"/>");
|
||||
}
|
||||
if (p.sz > 0) {
|
||||
xml.append("<w:sz w:val=\"").append(p.sz).append("\"/>");
|
||||
}
|
||||
if (p.szCs > 0) {
|
||||
xml.append("<w:szCs w:val=\"").append(p.szCs).append("\"/>");
|
||||
}
|
||||
if (p.underline) {
|
||||
xml.append("<w:u w:val=\"single\"/>");
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:rPr>" + xml + "</w:rPr>";
|
||||
}
|
||||
|
||||
/** pPr по CT_PPr: pageBreakBefore, ind, jc. */
|
||||
private String paraProps(byte[] grpprl) {
|
||||
int[] jc = {-1};
|
||||
int[] left = {-1};
|
||||
int[] right = {-1};
|
||||
int[] left1 = {Integer.MIN_VALUE};
|
||||
boolean[] pageBreak = {false};
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
switch (sprm) {
|
||||
case Grpprl.SPRM_P_JC80, Grpprl.SPRM_P_JC -> jc[0] =
|
||||
Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_F_PAGE_BREAK_BEFORE -> pageBreak[0] =
|
||||
Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_P_DXA_LEFT -> left[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_DXA_RIGHT -> right[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_DXA_LEFT1 -> left1[0] = signedXas(buf, off, len);
|
||||
default -> { }
|
||||
}
|
||||
});
|
||||
StringBuilder xml = new StringBuilder();
|
||||
if (pageBreak[0]) {
|
||||
xml.append("<w:pageBreakBefore/>");
|
||||
}
|
||||
boolean hasInd = left[0] > 0 || right[0] > 0
|
||||
|| (left1[0] != Integer.MIN_VALUE && left1[0] != 0);
|
||||
if (hasInd) {
|
||||
xml.append("<w:ind");
|
||||
if (left[0] > 0) {
|
||||
xml.append(" w:left=\"").append(left[0]).append('"');
|
||||
}
|
||||
if (right[0] > 0) {
|
||||
xml.append(" w:right=\"").append(right[0]).append('"');
|
||||
}
|
||||
if (left1[0] != Integer.MIN_VALUE && left1[0] != 0) {
|
||||
// sprmPDxaLeft1 — отступ первой строки ОТНОСИТЕЛЬНО остального
|
||||
// абзаца (XAS со знаком): >0 выступ (firstLine), <0 висющий
|
||||
if (left1[0] > 0) {
|
||||
xml.append(" w:firstLine=\"").append(left1[0]).append('"');
|
||||
} else {
|
||||
xml.append(" w:hanging=\"").append(-left1[0]).append('"');
|
||||
}
|
||||
}
|
||||
xml.append("/>");
|
||||
}
|
||||
String jcVal = switch (jc[0]) {
|
||||
case 1 -> "center";
|
||||
case 2 -> "right";
|
||||
case 3 -> "both";
|
||||
case 4 -> "distribute";
|
||||
default -> null;
|
||||
};
|
||||
if (jcVal != null) {
|
||||
xml.append("<w:jc w:val=\"").append(jcVal).append("\"/>");
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:pPr>" + xml + "</w:pPr>";
|
||||
}
|
||||
|
||||
/** XAS-операнд со знаком (§2.6.2): 2-байтовый отрицательный — старший бит. */
|
||||
private static int signedXas(byte[] buf, int off, int len) {
|
||||
int v = Grpprl.operandInt(buf, off, len);
|
||||
if (len == 2 && (v & 0x8000) != 0) {
|
||||
v -= 0x10000;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/** COLORREF (§2.9.43): red, green, blue, fAuto; cvAuto не эмитится. */
|
||||
private static String colorOf(byte[] buf, int off, int len) {
|
||||
|
||||
if (len < 4 || (buf[off + 3] & 0xFF) == 0xFF) {
|
||||
return null;
|
||||
}
|
||||
return String.format("%02X%02X%02X", buf[off] & 0xFF, buf[off + 1] & 0xFF,
|
||||
buf[off + 2] & 0xFF);
|
||||
}
|
||||
|
||||
private static String sectPr(Sections s, String headerRelId, String footerRelId) {
|
||||
StringBuilder xml = new StringBuilder("<w:sectPr>");
|
||||
// EG_HdrFtrReferences — до содержимого секции (CT_SectPr, ECMA-376 §17.2.3)
|
||||
if (headerRelId != null) {
|
||||
xml.append("<w:headerReference w:type=\"default\" r:id=\"")
|
||||
.append(headerRelId).append("\"/>");
|
||||
}
|
||||
if (footerRelId != null) {
|
||||
xml.append("<w:footerReference w:type=\"default\" r:id=\"")
|
||||
.append(footerRelId).append("\"/>");
|
||||
}
|
||||
xml.append("<w:pgSz w:w=\"").append(s.pageWidth()).append("\" w:h=\"")
|
||||
.append(s.pageHeight())
|
||||
.append("\"/><w:pgMar w:top=\"").append(s.marginTop())
|
||||
.append("\" w:right=\"").append(s.marginRight())
|
||||
.append("\" w:bottom=\"").append(s.marginBottom())
|
||||
.append("\" w:left=\"").append(s.marginLeft())
|
||||
.append("\" w:header=\"").append(s.header())
|
||||
.append("\" w:footer=\"").append(s.footer())
|
||||
.append("\" w:gutter=\"0\"/></w:sectPr>");
|
||||
return xml.toString();
|
||||
}
|
||||
|
||||
private static String escape(StringBuilder text) {
|
||||
StringBuilder out = new StringBuilder(text.length() + 16);
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char ch = text.charAt(i);
|
||||
switch (ch) {
|
||||
case '&' -> out.append("&");
|
||||
case '<' -> out.append("<");
|
||||
case '>' -> out.append(">");
|
||||
default -> out.append(ch);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String escapeAttr(String value) {
|
||||
StringBuilder out = new StringBuilder(value.length() + 8);
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char ch = value.charAt(i);
|
||||
switch (ch) {
|
||||
case '&' -> out.append("&");
|
||||
case '<' -> out.append("<");
|
||||
case '"' -> out.append(""");
|
||||
default -> out.append(ch);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** Прямые символьные свойства рана (last-wins по порядку Prl). */
|
||||
private static final class RunProps {
|
||||
private boolean bold;
|
||||
private boolean italic;
|
||||
private boolean strike;
|
||||
private boolean underline;
|
||||
private int sz;
|
||||
private int szCs;
|
||||
private int ftc0 = -1;
|
||||
private int ftc1 = -1;
|
||||
private String color;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* Сборка минимального transitional-OOXML пакета (.docx) из тела
|
||||
* {@code <w:body>} и дополнительных частей (колонтитуки, картинки).
|
||||
*
|
||||
* <p>Части: [Content_Types].xml, _rels/.rels, word/_rels/document.xml.rels,
|
||||
* word/document.xml + переданные {@link Part}. Ссылки частей получают
|
||||
* {@code rId1…} в порядке списка (officeDocument — только в _rels/.rels,
|
||||
* self-ссылка в rels документа недопустима); вызывающий обязан
|
||||
* использовать те же id в {@code w:headerReference}/{@code w:pic}. XML-части
|
||||
* идут в [Content_Types].xml как Override, медиа — как Default по расширению
|
||||
* (дедупликация по расширению). Байты уходят в штатный пайплайн docx4j
|
||||
* (шаги 1–7 {@code WordPdfConverter}).</p>
|
||||
*/
|
||||
final class DocxWriter {
|
||||
|
||||
/** Часть пакета кроме document.xml: zip-запись, content-type, тип связи, байты. */
|
||||
record Part(String entry, String contentType, String relType, byte[] content) {
|
||||
}
|
||||
|
||||
/** Пространства имён корня document.xml/hdr/ftr: w + r (rels) + DrawingML. */
|
||||
static final String NAMESPACES = "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\""
|
||||
+ " xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\""
|
||||
+ " xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\""
|
||||
+ " xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\""
|
||||
+ " xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"";
|
||||
|
||||
private static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
|
||||
|
||||
private static final String ROOT_RELS = XML_DECL
|
||||
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
||||
+ "<Relationship Id=\"rId1\" "
|
||||
+ "Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" "
|
||||
+ "Target=\"word/document.xml\"/></Relationships>";
|
||||
|
||||
private DocxWriter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Пакет из готового XML-тела {@code <w:body>} (без самого элемента)
|
||||
* и дополнительных частей (их id — {@code rId2…} по порядку списка).
|
||||
*/
|
||||
static byte[] write(String bodyXml, List<Part> parts) {
|
||||
String document = XML_DECL + "<w:document " + NAMESPACES + "><w:body>"
|
||||
+ bodyXml + "</w:body></w:document>";
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(1 << 14);
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bos, StandardCharsets.UTF_8)) {
|
||||
put(zip, "[Content_Types].xml", contentTypes(parts));
|
||||
put(zip, "_rels/.rels", ROOT_RELS);
|
||||
put(zip, "word/_rels/document.xml.rels", documentRels(parts));
|
||||
put(zip, "word/document.xml", document);
|
||||
for (Part part : parts) {
|
||||
zip.putNextEntry(new ZipEntry(part.entry()));
|
||||
zip.write(part.content());
|
||||
zip.closeEntry();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Не удалось собрать .docx из .doc", e);
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
/** XML-часть колонтитука: {@code <w:hdr>}/{@code <w:ftr>} с полным набором имён. */
|
||||
static byte[] storyPart(String rootElement, String paragraphsXml) {
|
||||
return (XML_DECL + "<" + rootElement + " " + NAMESPACES + ">"
|
||||
+ paragraphsXml + "</" + rootElement + ">").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String contentTypes(List<Part> parts) {
|
||||
StringBuilder xml = new StringBuilder(XML_DECL)
|
||||
.append("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">")
|
||||
.append("<Default Extension=\"rels\" ")
|
||||
.append("ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>")
|
||||
.append("<Default Extension=\"xml\" ContentType=\"application/xml\"/>");
|
||||
Set<String> mediaExtensions = new LinkedHashSet<>();
|
||||
for (Part part : parts) {
|
||||
if (part.entry().endsWith(".xml")) {
|
||||
xml.append("<Override PartName=\"/").append(part.entry())
|
||||
.append("\" ContentType=\"").append(part.contentType()).append("\"/>");
|
||||
} else {
|
||||
int dot = part.entry().lastIndexOf('.');
|
||||
String ext = dot < 0 ? part.entry() : part.entry().substring(dot + 1);
|
||||
if (mediaExtensions.add(ext)) {
|
||||
xml.append("<Default Extension=\"").append(ext)
|
||||
.append("\" ContentType=\"").append(part.contentType()).append("\"/>");
|
||||
}
|
||||
}
|
||||
}
|
||||
xml.append("<Override PartName=\"/word/document.xml\" ")
|
||||
.append("ContentType=\"application/vnd.openxmlformats-officedocument")
|
||||
.append(".wordprocessingml.document.main+xml\"/></Types>");
|
||||
return xml.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Связи document.xml: части в порядке списка (rId1…). officeDocument
|
||||
* здесь нет — он только в _rels/.rels; self-ссылка зациклила бы
|
||||
* docx4j {@code PartialDeepCopy.deepCopyRelationships}.
|
||||
*/
|
||||
private static String documentRels(List<Part> parts) {
|
||||
StringBuilder xml = new StringBuilder(XML_DECL)
|
||||
.append("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
|
||||
for (int i = 0; i < parts.size(); i++) {
|
||||
Part part = parts.get(i);
|
||||
String target = part.entry().startsWith("word/")
|
||||
? part.entry().substring("word/".length()) : part.entry();
|
||||
xml.append("<Relationship Id=\"rId").append(1 + i).append("\" Type=\"")
|
||||
.append(part.relType()).append("\" Target=\"").append(target).append("\"/>");
|
||||
}
|
||||
return xml.append("</Relationships>").toString();
|
||||
}
|
||||
|
||||
private static void put(ZipOutputStream zip, String name, String content) throws IOException {
|
||||
zip.putNextEntry(new ZipEntry(name));
|
||||
zip.write(content.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Разбор File Information Block (FIB) — заголовка WordDocument-потока.
|
||||
*
|
||||
* <p>По [MS-DOC] §2.5: Fib = FibBase (32) + csw + FibRgW97 + cslw + FibRgLw97
|
||||
* + cbRgFcLcb + FibRgFcLcbBlob (§2.5.1). Читаются только нужные поля;
|
||||
* порядок и смещения — §2.5.15 «How to read the FIB», побайтовые примеры —
|
||||
* §3 (Figure 22/30). Число 136 пар в blob (Word 2003+) не мешает: нужные
|
||||
* пары стоят на фиксированных индексах.</p>
|
||||
*/
|
||||
final class FibHeader {
|
||||
|
||||
/** Магическое число Word Binary File (§2.5.2, wIdent). */
|
||||
private static final int W_IDENT = 0xA5EC;
|
||||
|
||||
/** Минимальная версия — Word 97 (§2.5.14 «Determining the nFib»). */
|
||||
private static final int N_FIB_WORD97 = 0x00C1;
|
||||
|
||||
/** Смещения FibBase (§2.5.2). */
|
||||
private static final int OFF_W_IDENT = 0;
|
||||
private static final int OFF_N_FIB = 2;
|
||||
private static final int OFF_FLAGS = 10;
|
||||
private static final int BIT_F_ENCRYPTED = 8;
|
||||
private static final int BIT_F_WHICH_TBL_STM = 9;
|
||||
|
||||
/** Значение бита флага «включён» (§2.5.2, grpprl FIB). */
|
||||
private static final int BIT_ON = 1;
|
||||
|
||||
/** Минимум FibRgW97 (4 коротких значения, §2.5.4). */
|
||||
private static final int MIN_CSLW = 4;
|
||||
|
||||
/** Смещения после FibBase (§2.5.1). */
|
||||
private static final int OFF_CSLW = 62;
|
||||
private static final int OFF_FIB_RG_LW = 64;
|
||||
private static final int OFF_CB_MAC = OFF_FIB_RG_LW;
|
||||
private static final int OFF_CCP_TEXT = OFF_FIB_RG_LW + 3 * 4;
|
||||
private static final int OFF_CCP_FTN = OFF_FIB_RG_LW + 4 * 4;
|
||||
private static final int OFF_CCP_HDD = OFF_FIB_RG_LW + 5 * 4;
|
||||
private static final int OFF_CB_RG_FC_LCB = 152;
|
||||
private static final int OFF_BLOB = 154;
|
||||
|
||||
/** Индексы пар (fc,lcb) в FibRgFcLcb97 (§2.5.6, порядок полей). */
|
||||
private static final int PAIR_PLCF_SED = 6;
|
||||
private static final int PAIR_PLCF_HDD = 11;
|
||||
private static final int PAIR_PLCF_BTE_CHPX = 12;
|
||||
private static final int PAIR_PLCF_BTE_PAPX = 13;
|
||||
private static final int PAIR_STTBF_FFN = 15;
|
||||
private static final int PAIR_CLX = 33;
|
||||
|
||||
private final int ccpText;
|
||||
private final int ccpFtn;
|
||||
private final int ccpHdd;
|
||||
private final int cbMac;
|
||||
private final boolean use1Table;
|
||||
private final long fcPlcfSed;
|
||||
private final long lcbPlcfSed;
|
||||
private final long fcPlcfHdd;
|
||||
private final long lcbPlcfHdd;
|
||||
private final long fcPlcfBteChpx;
|
||||
private final long lcbPlcfBteChpx;
|
||||
private final long fcPlcfBtePapx;
|
||||
private final long lcbPlcfBtePapx;
|
||||
private final long fcSttbfFfn;
|
||||
private final long lcbSttbfFfn;
|
||||
private final long fcClx;
|
||||
private final long lcbClx;
|
||||
|
||||
private FibHeader(byte[] wd) {
|
||||
int wIdent = (int) CfbReader.u32(wd, OFF_W_IDENT) & 0xFFFF;
|
||||
int nFib = (int) CfbReader.u32(wd, OFF_N_FIB) & 0xFFFF;
|
||||
if (wIdent != W_IDENT) {
|
||||
throw new ValidationException("Содержимое не похоже на .doc Word 97–2003");
|
||||
}
|
||||
if (nFib < N_FIB_WORD97) {
|
||||
throw new ValidationException("Поддерживаются только документы Word 97–2003");
|
||||
}
|
||||
int flags = (int) CfbReader.u32(wd, OFF_FLAGS) & 0xFFFF;
|
||||
if (((flags >> BIT_F_ENCRYPTED) & BIT_ON) == BIT_ON) {
|
||||
throw new ValidationException("Документ зашифрован (пароль на открытие) — конвертация невозможна");
|
||||
}
|
||||
use1Table = ((flags >> BIT_F_WHICH_TBL_STM) & BIT_ON) == BIT_ON;
|
||||
int cslw = (int) CfbReader.u32(wd, OFF_CSLW) & 0xFFFF;
|
||||
if (cslw < MIN_CSLW) {
|
||||
throw new ValidationException("Обрезанный FIB в .doc");
|
||||
}
|
||||
cbMac = (int) CfbReader.u32(wd, OFF_CB_MAC);
|
||||
ccpText = (int) CfbReader.u32(wd, OFF_CCP_TEXT);
|
||||
ccpFtn = (int) CfbReader.u32(wd, OFF_CCP_FTN);
|
||||
ccpHdd = (int) CfbReader.u32(wd, OFF_CCP_HDD);
|
||||
if (ccpText < 0) {
|
||||
throw new ValidationException("Отрицательная длина текста в .doc");
|
||||
}
|
||||
int cbRgFcLcb = (int) CfbReader.u32(wd, OFF_CB_RG_FC_LCB) & 0xFFFF;
|
||||
if (cbRgFcLcb <= PAIR_CLX) {
|
||||
throw new ValidationException("Устаревшая структура FIB в .doc");
|
||||
}
|
||||
long[] sed = pair(wd, PAIR_PLCF_SED);
|
||||
fcPlcfSed = sed[0];
|
||||
lcbPlcfSed = sed[1];
|
||||
long[] hdd = pair(wd, PAIR_PLCF_HDD);
|
||||
fcPlcfHdd = hdd[0];
|
||||
lcbPlcfHdd = hdd[1];
|
||||
long[] chpx = pair(wd, PAIR_PLCF_BTE_CHPX);
|
||||
fcPlcfBteChpx = chpx[0];
|
||||
lcbPlcfBteChpx = chpx[1];
|
||||
long[] papx = pair(wd, PAIR_PLCF_BTE_PAPX);
|
||||
fcPlcfBtePapx = papx[0];
|
||||
lcbPlcfBtePapx = papx[1];
|
||||
long[] ffn = pair(wd, PAIR_STTBF_FFN);
|
||||
fcSttbfFfn = ffn[0];
|
||||
lcbSttbfFfn = ffn[1];
|
||||
long[] clx = pair(wd, PAIR_CLX);
|
||||
fcClx = clx[0];
|
||||
lcbClx = clx[1];
|
||||
}
|
||||
|
||||
/** Точка входа: разбор WordDocument-потока. */
|
||||
static FibHeader read(byte[] wordDocument) {
|
||||
if (wordDocument.length < OFF_BLOB) {
|
||||
throw new ValidationException("Содержимое не похоже на .doc Word 97–2003");
|
||||
}
|
||||
return new FibHeader(wordDocument);
|
||||
}
|
||||
|
||||
private static long[] pair(byte[] wd, int index) {
|
||||
int off = OFF_BLOB + index * 8;
|
||||
if (off + 8 > wd.length) {
|
||||
throw new ValidationException("Обрезанный FIB в .doc");
|
||||
}
|
||||
return new long[] {CfbReader.u32(wd, off), CfbReader.u32(wd, off + 4)};
|
||||
}
|
||||
|
||||
/** Число CP основного текста (§2.5.4 ccpText). */
|
||||
int ccpText() {
|
||||
return ccpText;
|
||||
}
|
||||
|
||||
/** Число CP сносок (§2.5.4 ccpFtn) — стори колонтитуков идут после них. */
|
||||
int ccpFtn() {
|
||||
return ccpFtn;
|
||||
}
|
||||
|
||||
/** Число CP колонтитуков (§2.5.4 ccpHdd). */
|
||||
int ccpHdd() {
|
||||
return ccpHdd;
|
||||
}
|
||||
|
||||
/** Предел значимых байт WordDocument-потока (§2.5.4 cbMac). */
|
||||
int cbMac() {
|
||||
return cbMac;
|
||||
}
|
||||
|
||||
/** Табличный поток — {@code 1Table} при true, иначе {@code 0Table} (§2.2). */
|
||||
boolean use1Table() {
|
||||
return use1Table;
|
||||
}
|
||||
|
||||
long fcPlcfSed() {
|
||||
return fcPlcfSed;
|
||||
}
|
||||
|
||||
long lcbPlcfSed() {
|
||||
return lcbPlcfSed;
|
||||
}
|
||||
|
||||
long fcPlcfHdd() {
|
||||
return fcPlcfHdd;
|
||||
}
|
||||
|
||||
long lcbPlcfHdd() {
|
||||
return lcbPlcfHdd;
|
||||
}
|
||||
|
||||
long fcPlcfBteChpx() {
|
||||
return fcPlcfBteChpx;
|
||||
}
|
||||
|
||||
long lcbPlcfBteChpx() {
|
||||
return lcbPlcfBteChpx;
|
||||
}
|
||||
|
||||
long fcPlcfBtePapx() {
|
||||
return fcPlcfBtePapx;
|
||||
}
|
||||
|
||||
long lcbPlcfBtePapx() {
|
||||
return lcbPlcfBtePapx;
|
||||
}
|
||||
|
||||
long fcSttbfFfn() {
|
||||
return fcSttbfFfn;
|
||||
}
|
||||
|
||||
long lcbSttbfFfn() {
|
||||
return lcbSttbfFfn;
|
||||
}
|
||||
|
||||
long fcClx() {
|
||||
return fcClx;
|
||||
}
|
||||
|
||||
long lcbClx() {
|
||||
return lcbClx;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Таблица шрифтов SttbfFfn — имена по индексам sprmCRgFtc0/1.
|
||||
*
|
||||
* <p>[MS-DOC] §2.9: SttbfFfn — не-extended STTB (заголовок cData 2 + cbExtra 2,
|
||||
* без fExtend), элементы: cchData (1 байт) + Data (FFN-запись). FFN (§2.9):
|
||||
* ffid(1) + wWeight(2) + chs(1) + ixchSzAlt(1) + panose(10) + fs(24) = 39 байт,
|
||||
* затем xszFfn — null-terminated Unicode-имя шрифта. Проверено на фикстуре
|
||||
* ru-plain.doc (9 шрифтов, lcb выбран целиком).</p>
|
||||
*/
|
||||
final class FontTable {
|
||||
|
||||
/** Размер FFN-записи до имени (ffid+wWeight+chs+ixchSzAlt+panose+fs). */
|
||||
private static final int FFN_NAME_OFFSET = 1 + 2 + 1 + 1 + 10 + 24;
|
||||
|
||||
private final List<String> names;
|
||||
|
||||
private FontTable(byte[] table, long fc, long lcb) {
|
||||
names = new ArrayList<>();
|
||||
if (lcb <= 0) {
|
||||
return;
|
||||
}
|
||||
if (fc < 0 || lcb <= 0 || fc + lcb > table.length || lcb < 4) {
|
||||
throw new ValidationException("Таблица шрифтов .doc выходит за поток");
|
||||
}
|
||||
int cData = (int) CfbReader.u32(table, (int) fc) & 0xFFFF;
|
||||
int p = (int) fc + 4;
|
||||
int end = (int) (fc + lcb);
|
||||
for (int i = 0; i < cData; i++) {
|
||||
if (p + 1 > end) {
|
||||
throw new ValidationException("Обрезанная таблица шрифтов .doc");
|
||||
}
|
||||
int cch = table[p] & 0xFF;
|
||||
p += 1;
|
||||
if (cch < FFN_NAME_OFFSET || p + cch > end) {
|
||||
throw new ValidationException("Битая FFN-запись в .doc");
|
||||
}
|
||||
String raw = new String(table, p + FFN_NAME_OFFSET, cch - FFN_NAME_OFFSET,
|
||||
StandardCharsets.UTF_16LE);
|
||||
names.add(raw.split("\0", 2)[0]);
|
||||
p += cch;
|
||||
}
|
||||
}
|
||||
|
||||
/** Таблица по {@code fcSttbfFfn} из табличного потока; lcb=0 → пустая. */
|
||||
static FontTable read(byte[] tableStream, long fc, long lcb) {
|
||||
return new FontTable(tableStream, fc, lcb);
|
||||
}
|
||||
|
||||
/** Имя шрифта по индексу sprmCRgFtc0/1; вне таблицы → {@code null}. */
|
||||
String font(int index) {
|
||||
return index >= 0 && index < names.size() ? names.get(index) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
/**
|
||||
* Разбор Grpprl — массива Prl (sprm + операнд), [MS-DOC] §2.6.
|
||||
*
|
||||
* <p>Sprm (16 бит): ispmd = sprm & 0x1FF, fSpec = (sprm >> 9) & 1,
|
||||
* sgc = (sprm >> 10) & 7, spra = sprm >> 13. Размер операнда по
|
||||
* spra (§2.6, таблица Spra): 0 = ToggleOperand (1 байт), 1 = 1, 2 = 2,
|
||||
* 3 = 4, 4 = 2, 5 = 2, 6 = переменный (первый байт — длина остального),
|
||||
* 7 = 3. Неизвестный sprm пропускается по spra (ms-doc.md:1809).</p>
|
||||
*
|
||||
* <p>Значения sprm — таблицы §2.6.1/2.6.2/2.6.3 dated-.docx [MS-DOC] 12.5
|
||||
* (в md репозитория потеряны как [TABLE]); кросс-чек с примерами §3:
|
||||
* sprmPJc = 0x2461, sprmSDxaLeft = 0xB021, sprmCKul ispmd 0x3E fSpec 1.</p>
|
||||
*/
|
||||
final class Grpprl {
|
||||
|
||||
// Character Properties (§2.6.1, sgc 2)
|
||||
static final int SPRM_C_F_BOLD = 0x0835;
|
||||
static final int SPRM_C_F_ITALIC = 0x0836;
|
||||
static final int SPRM_C_F_STRIKE = 0x0837;
|
||||
static final int SPRM_C_KUL = 0x2A3E;
|
||||
static final int SPRM_C_HPS = 0x4A43;
|
||||
static final int SPRM_C_HPS_BI = 0x4A61;
|
||||
static final int SPRM_C_RG_FTC0 = 0x4A4F;
|
||||
static final int SPRM_C_RG_FTC1 = 0x4A50;
|
||||
static final int SPRM_C_CV = 0x6870;
|
||||
/**
|
||||
* sprmCPicLocation (§2.6.1, 4 байта): offset в Data-потоке —
|
||||
* PICFAndOfficeArtData (картинка) или NilPICFAndBinData (OLE-бинарник,
|
||||
* {@code picf.cbHeader≠0x44} → {@link OfficeArt#read} вернёт null).
|
||||
* sprmCFSpec=0x0875/sprmCFData=0x0806/sprmCFOle2=0x084B не читаем:
|
||||
* фикстуры пишут их непоследовательно (ole-embedded — без CFSpec),
|
||||
* а различает картинку/бинарник сам cbHeader.
|
||||
*/
|
||||
static final int SPRM_C_PIC_LOCATION = 0x6A03;
|
||||
|
||||
// Paragraph Properties (§2.6.2, sgc 1)
|
||||
static final int SPRM_P_JC80 = 0x2403;
|
||||
static final int SPRM_P_F_PAGE_BREAK_BEFORE = 0x2407;
|
||||
static final int SPRM_P_F_TTP = 0x2417;
|
||||
static final int SPRM_P_JC = 0x2461;
|
||||
static final int SPRM_P_DXA_RIGHT = 0x845D;
|
||||
static final int SPRM_P_DXA_LEFT = 0x845E;
|
||||
static final int SPRM_P_DXA_LEFT1 = 0x8460;
|
||||
|
||||
// Section Properties (§2.6.3, sgc 4)
|
||||
static final int SPRM_S_DYA_HDR_TOP = 0xB017;
|
||||
static final int SPRM_S_DYA_HDR_BOTTOM = 0xB018;
|
||||
static final int SPRM_S_XA_PAGE = 0xB01F;
|
||||
static final int SPRM_S_YA_PAGE = 0xB020;
|
||||
static final int SPRM_S_DXA_LEFT = 0xB021;
|
||||
static final int SPRM_S_DXA_RIGHT = 0xB022;
|
||||
static final int SPRM_S_DYA_TOP = 0x9023;
|
||||
static final int SPRM_S_DYA_BOTTOM = 0x9024;
|
||||
static final int SPRM_S_BKC = 0x3009;
|
||||
|
||||
/** Вызывается на каждый Prl в порядке следования (last-wins у вызывающего). */
|
||||
interface PrlSink {
|
||||
/**
|
||||
* @param sprm 16-битный sprm
|
||||
* @param buf буфер с операндом
|
||||
* @param off смещение операнда в buf
|
||||
* @param len длина операнда (0 для spra=0 без байта — не встречается)
|
||||
*/
|
||||
void prl(int sprm, byte[] buf, int off, int len);
|
||||
}
|
||||
|
||||
private Grpprl() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Обходит grpprl {@code buf[off..off+len)}, вызывая sink на каждый Prl.
|
||||
* Битый хвост (операнд не влезает) — обрыв без исключения: свойства
|
||||
* перестают применяться, документ не отбрасывается.
|
||||
*/
|
||||
static void scan(byte[] buf, int off, int len, PrlSink sink) {
|
||||
int p = off;
|
||||
int end = off + len;
|
||||
while (p + 2 <= end) {
|
||||
int sprm = (buf[p] & 0xFF) | ((buf[p + 1] & 0xFF) << 8);
|
||||
p += 2;
|
||||
int size = operandSize(sprm, buf, p, end);
|
||||
if (size < 0 || p + size > end) {
|
||||
return;
|
||||
}
|
||||
sink.prl(sprm, buf, p, size);
|
||||
p += size;
|
||||
}
|
||||
}
|
||||
|
||||
/** Длина операнда по spra; -1 — переменный формат битый. */
|
||||
private static int operandSize(int sprm, byte[] buf, int p, int end) {
|
||||
int spra = sprm >> 13;
|
||||
switch (spra) {
|
||||
case 0: // ToggleOperand — 1 байт
|
||||
case 1:
|
||||
return 1;
|
||||
case 2:
|
||||
case 4:
|
||||
case 5:
|
||||
return 2;
|
||||
case 3:
|
||||
return 4;
|
||||
case 7:
|
||||
return 3;
|
||||
case 6: { // переменный: первый байт — длина остального
|
||||
if (p >= end) {
|
||||
return -1;
|
||||
}
|
||||
return 1 + (buf[p] & 0xFF);
|
||||
}
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Операнд как unsigned int (младшие байты). */
|
||||
static int operandInt(byte[] buf, int off, int len) {
|
||||
int v = 0;
|
||||
for (int i = 0; i < len && i < 4; i++) {
|
||||
v |= (buf[off + i] & 0xFF) << (8 * i);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Toggle-операнд: бит 0 = on; чётное («переключить от предыдущего») = off. */
|
||||
static boolean toggleOn(byte[] buf, int off) {
|
||||
return (buf[off] & 1) == 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Header Document (.doc): истории колонтитуков по {@code Plcfhdd}
|
||||
* ([MS-DOC] §2.8.22 — PLC из одних CP; §2.4.4 — порядок историй).
|
||||
*
|
||||
* <p>Массив aCP размечает подряд идущие CP-диапазоны: первые шесть — пустые
|
||||
* абзацы-разделители, далее на каждую секцию шесть историй
|
||||
* [even header, odd header, even footer, odd footer, first-page header,
|
||||
* first-page footer]; последний aCP (§2.8.22 «the last CP is ignored») в
|
||||
* расчёт не входит. Каждая история заканчивается guard-абзацем (¶), который
|
||||
* в вывод не попадает.</p>
|
||||
*
|
||||
* <p>В перенос идут odd header/footer секции 0 как {@code type="default"} —
|
||||
* FOP не различает чётные/нечётные страницы, а {@code titlePg} (первая
|
||||
* страница) в первом инкременте не поддерживается.</p>
|
||||
*/
|
||||
final class Headers {
|
||||
|
||||
/** CP-диапазон одной истории [cpStart, cpEnd); последний ¶ — guard-абзац. */
|
||||
record Story(int cpStart, int cpEnd) {
|
||||
|
||||
/** Есть ли содержимое за пределами guard-абзаца. */
|
||||
boolean hasContent() {
|
||||
return cpEnd - cpStart > 1;
|
||||
}
|
||||
|
||||
/** Конец содержимого (без guard-¶). */
|
||||
int contentEnd() {
|
||||
return cpEnd - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Пустых абзацев-разделителей перед историями первой секции (§2.4.4). */
|
||||
private static final int SEPARATOR_STORIES = 6;
|
||||
/** Историй на секцию (§2.4.4). */
|
||||
private static final int STORIES_PER_SECTION = 6;
|
||||
/** Индексы внутри группы секции: 0 even hdr, 1 odd hdr, 2 even ftr, 3 odd ftr… */
|
||||
private static final int ODD_HEADER = 1;
|
||||
private static final int ODD_FOOTER = 3;
|
||||
|
||||
private final int[] aCp;
|
||||
|
||||
private Headers(byte[] table, long fcPlcfHdd, long lcbPlcfHdd, int baseCp) {
|
||||
if (lcbPlcfHdd <= 0) {
|
||||
aCp = new int[0];
|
||||
return;
|
||||
}
|
||||
if (fcPlcfHdd < 0 || fcPlcfHdd + lcbPlcfHdd > table.length) {
|
||||
throw new ValidationException("Plcfhdd выходит за табличный поток в .doc");
|
||||
}
|
||||
if (lcbPlcfHdd % 4 != 0) {
|
||||
throw new ValidationException("Битый Plcfhdd в .doc");
|
||||
}
|
||||
int n = (int) (lcbPlcfHdd / 4);
|
||||
aCp = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
// aCP относительны начала Header Document (§2.8.22: penultimate =
|
||||
// ccpHdd−1); абсолютный CP = ccpText + ccpFtn + aCP
|
||||
aCp[i] = baseCp + (int) CfbReader.u32(table, (int) fcPlcfHdd + i * 4);
|
||||
if (i > 0 && aCp[i] < aCp[i - 1]) {
|
||||
throw new ValidationException("Невозрастающие aCP в Plcfhdd .doc");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Headers read(byte[] table, long fcPlcfHdd, long lcbPlcfHdd, int baseCp) {
|
||||
return new Headers(table, fcPlcfHdd, lcbPlcfHdd, baseCp);
|
||||
}
|
||||
|
||||
/** Заголовок нечётных полос набора секции {@code section} (§2.4.4). */
|
||||
Story oddHeader(int section) {
|
||||
return story(SEPARATOR_STORIES + section * STORIES_PER_SECTION + ODD_HEADER);
|
||||
}
|
||||
|
||||
/** Колонтитул нечётных полос набора секции {@code section} (§2.4.4). */
|
||||
Story oddFooter(int section) {
|
||||
return story(SEPARATOR_STORIES + section * STORIES_PER_SECTION + ODD_FOOTER);
|
||||
}
|
||||
|
||||
private Story story(int index) {
|
||||
if (index + 1 >= aCp.length) {
|
||||
return new Story(0, 0);
|
||||
}
|
||||
return new Story(aCp[index], aCp[index + 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
/**
|
||||
* Извлечение растровой картинки из {@code PICFAndOfficeArtData}
|
||||
* ([MS-DOC] §2.9.192, операнд {@code sprmCPicLocation} = offset в Data-потоке)
|
||||
* по [MS-ODRAW]: PICF (68 байт, §2.9.190) → OfficeArt-записи → BLIP
|
||||
* (§2.2.23–.31: recType 0xF01A EMF / 0xF01B WMF / 0xF01C PICT / 0xF01D JPEG /
|
||||
* 0xF01E PNG / 0xF01F DIB; нечётный recInstance — второй UID, §2.2.24).
|
||||
*
|
||||
* <p>Word кладёт BLIP в разные места (BStoreContainer 0xF004,
|
||||
* BStoreContainerDelay 0xF007, инлайн-контейнер), а POI-продукция пишет
|
||||
* FBSE без заголовков — поэтому поиск по диапазону {@code [picLocation,
|
||||
* picLocation+lcb)} (lcb из PICF), а не обход дерева: кандидат принимается
|
||||
* только если recType BLIP'а, {@code cb} влезает в диапазон и данные после
|
||||
* uid+tag начинаются с сигнатуры PNG/JPEG/DIB. Ложные срабатывания
|
||||
* (встроенные OLE-архивы) отсекаются ровно этим условием — скан по всему
|
||||
* потоку их плодит, скан по картинному диапазону нет.</p>
|
||||
*
|
||||
* <p>EMF/WMF/PICT в PDF не рендерятся (Java2D-движка для метафайлов в ядре
|
||||
* нет) — {@code null} (объект исчезает, как удалённый {@code w:object}).
|
||||
* DIB перекодируется в PNG через ImageIO.</p>
|
||||
*/
|
||||
final class OfficeArt {
|
||||
|
||||
/** Растр: расширение/ mime-подтип для content-type, байты, размер в EMU. */
|
||||
record Picture(String extension, String contentType, byte[] data, int cxEmu, int cyEmu) {
|
||||
}
|
||||
|
||||
/** PICF: lcb(4) cbHeader(2)=0x44 mfpf(8) innerHeader(14) picmid(38) cProps(2). */
|
||||
private static final int PICF_SIZE = 68;
|
||||
private static final int OFF_CB_HEADER = 4;
|
||||
private static final int OFF_MM = 6;
|
||||
private static final int MM_SHAPEFILE = 0x0066;
|
||||
/** PICMID (смещение 28 от начала PICF): dxaGoal, dyaGoal, mx, my (§2.9.193). */
|
||||
private static final int OFF_DXA_GOAL = 0x1C;
|
||||
private static final int OFF_DYA_GOAL = 0x1E;
|
||||
private static final int OFF_MX = 0x20;
|
||||
private static final int OFF_MY = 0x22;
|
||||
/** Границы отображаемого размера, twips (§2.9.193: 15…31680). */
|
||||
private static final int DXA_MIN = 15;
|
||||
private static final int DXA_MAX = 31_680;
|
||||
/** twips → EMU (ECMA-376 §20.1.8: 1 twip = 635 EMU). */
|
||||
private static final int EMU_PER_TWIP = 635;
|
||||
|
||||
private static final int BLIP_EMF = 0xF01A;
|
||||
private static final int BLIP_WMF = 0xF01B;
|
||||
private static final int BLIP_PICT = 0xF01C;
|
||||
private static final int BLIP_JPEG = 0xF01D;
|
||||
private static final int BLIP_JPEG_ALT = 0xF02A; // [MS-ODRAW] A.1: = 0xF01D
|
||||
private static final int BLIP_PNG = 0xF01E;
|
||||
private static final int BLIP_DIB = 0xF01F;
|
||||
|
||||
/** recInstance с двумя UID ([MS-ODRAW] §2.2.24–.31). */
|
||||
private static final java.util.Set<Integer> TWO_UIDS =
|
||||
java.util.Set.of(0x217, 0x3D5, 0x543, 0x6E1, 0x6E3, 0x6E5, 0x7A9);
|
||||
|
||||
private OfficeArt() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Картинка по {@code picLocation} в Data-потоке; {@code null} — нет
|
||||
* данных/векторный формат/битая запись (деградация, не ошибка).
|
||||
*/
|
||||
static Picture read(byte[] dataStream, long picLocation) {
|
||||
if (picLocation < 0 || picLocation + PICF_SIZE > dataStream.length) {
|
||||
return null;
|
||||
}
|
||||
int off = (int) picLocation;
|
||||
long lcb = CfbReader.u32(dataStream, off);
|
||||
if (lcb < PICF_SIZE || off + lcb > dataStream.length
|
||||
|| (CfbReader.u32(dataStream, off + OFF_CB_HEADER) & 0xFFFF) != PICF_SIZE) {
|
||||
return null;
|
||||
}
|
||||
int end = off + (int) lcb;
|
||||
int sizeX = displayDxa(dataStream, off + OFF_DXA_GOAL, off + OFF_MX);
|
||||
int sizeY = displayDxa(dataStream, off + OFF_DYA_GOAL, off + OFF_MY);
|
||||
int scanFrom = off + PICF_SIZE;
|
||||
if (CfbReader.u32(dataStream, off + OFF_MM) == MM_SHAPEFILE && scanFrom < end) {
|
||||
scanFrom += 1 + (dataStream[scanFrom] & 0xFF); // cchPicName + stPicName
|
||||
}
|
||||
for (int p = scanFrom; p + 8 <= end; p++) {
|
||||
Picture pic = tryBlip(dataStream, p, end, sizeX, sizeY);
|
||||
if (pic != null) {
|
||||
return pic;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Кандидат на BLIP-запись по смещению {@code p}; {@code null} — не он. */
|
||||
private static Picture tryBlip(byte[] data, int p, int end, int sizeX, int sizeY) {
|
||||
int verInstance = (int) (CfbReader.u32(data, p) & 0xFFFF);
|
||||
int type = (int) (CfbReader.u32(data, p + 2) & 0xFFFF);
|
||||
long cb = CfbReader.u32(data, p + 4);
|
||||
if (cb < 17 || p + 8 + cb > end) {
|
||||
return null;
|
||||
}
|
||||
// Второй UID — только перечисленные recInstance (§2.2.24–.31:
|
||||
// EMF 0x3D5, WMF 0x217, PICT 0x543, JPEG 0x6E3, PNG 0x6E1,
|
||||
// DIB 0x7A9, EMF+ 0x6E5; JPEG 0x46B — нечётный, но ОДИН UID).
|
||||
// Word/POI кладут значение в raw verInstance (0x06E1), спека —
|
||||
// в 12-битное поле (0x6E10): проверяем обе формы.
|
||||
int uidSize = (TWO_UIDS.contains(verInstance >>> 4) || TWO_UIDS.contains(verInstance))
|
||||
? 32 : 16;
|
||||
int dataOff = p + 8 + uidSize + 1; // после uid + tag
|
||||
int dataLen = (int) (cb - uidSize - 1);
|
||||
if (dataLen <= 0) {
|
||||
return null;
|
||||
}
|
||||
return switch (type) {
|
||||
case BLIP_PNG -> startsWith(data, dataOff, dataLen, new byte[] {(byte) 0x89, 'P', 'N', 'G'})
|
||||
? new Picture("png", "image/png", slice(data, dataOff, dataLen),
|
||||
emu(sizeX > 0 ? sizeX : pngDxa(data, dataOff, true)),
|
||||
emu(sizeY > 0 ? sizeY : pngDxa(data, dataOff, false)))
|
||||
: null;
|
||||
case BLIP_JPEG, BLIP_JPEG_ALT -> startsWith(data, dataOff, dataLen, new byte[] {(byte) 0xFF, (byte) 0xD8})
|
||||
? new Picture("jpg", "image/jpeg", slice(data, dataOff, dataLen),
|
||||
emu(sizeX), emu(sizeY))
|
||||
: null;
|
||||
case BLIP_DIB -> dibToPng(data, dataOff, dataLen, sizeX, sizeY);
|
||||
case BLIP_EMF, BLIP_WMF, BLIP_PICT -> null; // метафайлы не рендерим
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/** PICMID отсутствует/битый — размер из PNG IHDR @96 dpi (1 px = 15 twips). */
|
||||
private static int pngDxa(byte[] data, int pngOff, boolean width) {
|
||||
if (pngOff + 24 > data.length) {
|
||||
return DXA_MIN;
|
||||
}
|
||||
int px = (int) ((data[pngOff + 16 + (width ? 0 : 4)] & 0xFFL) << 24
|
||||
| (data[pngOff + 17 + (width ? 0 : 4)] & 0xFFL) << 16
|
||||
| (data[pngOff + 18 + (width ? 0 : 4)] & 0xFFL) << 8
|
||||
| (data[pngOff + 19 + (width ? 0 : 4)] & 0xFFL));
|
||||
if (px <= 0) {
|
||||
return DXA_MIN;
|
||||
}
|
||||
return clampDxa(px * 15L);
|
||||
}
|
||||
|
||||
private static int clampDxa(long dxa) {
|
||||
return (int) Math.max(DXA_MIN, Math.min(dxa, DXA_MAX));
|
||||
}
|
||||
|
||||
/** Отображаемый размер: goal × (mx|my / 1000), clamp 15…31680 twips. */
|
||||
private static int displayDxa(byte[] data, int goalOff, int scaleOff) {
|
||||
int goal = (short) CfbReader.u32(data, goalOff);
|
||||
int scale = (int) (CfbReader.u32(data, scaleOff) & 0xFFFF);
|
||||
if (goal <= 0 || scale <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return clampDxa(goal * (long) scale / 1000);
|
||||
}
|
||||
|
||||
private static int emu(int dxa) {
|
||||
return Math.max(dxa, DXA_MIN) * EMU_PER_TWIP;
|
||||
}
|
||||
|
||||
/** BITMAPINFOHEADER (§2.2.29): минимальный размер DIB-данных. */
|
||||
private static final int BITMAPINFOHEADER_SIZE = 40;
|
||||
|
||||
/** DIB (BITMAPINFOHEADER + пиксели) → PNG через ImageIO; битый → null. */
|
||||
private static Picture dibToPng(byte[] data, int off, int len, int sizeX, int sizeY) {
|
||||
if (len < BITMAPINFOHEADER_SIZE) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
java.awt.image.BufferedImage img = javax.imageio.ImageIO.read(
|
||||
new java.io.ByteArrayInputStream(wrapAsBmp(data, off, len)));
|
||||
if (img == null) {
|
||||
return null;
|
||||
}
|
||||
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
|
||||
javax.imageio.ImageIO.write(img, "png", bos);
|
||||
return new Picture("png", "image/png", bos.toByteArray(), emu(sizeX), emu(sizeY));
|
||||
} catch (java.io.IOException | RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** DIB → BMP: BITMAPFILEHEADER(14) + как есть (§2.2.29 — DIB без хедера). */
|
||||
private static byte[] wrapAsBmp(byte[] data, int off, int len) {
|
||||
byte[] bmp = new byte[14 + len];
|
||||
bmp[0] = 'B';
|
||||
bmp[1] = 'M';
|
||||
int fileSize = 14 + len;
|
||||
bmp[2] = (byte) fileSize;
|
||||
bmp[3] = (byte) (fileSize >>> 8);
|
||||
bmp[4] = (byte) (fileSize >>> 16);
|
||||
bmp[5] = (byte) (fileSize >>> 24);
|
||||
int bits = (int) (CfbReader.u32(data, off + 14) & 0xFFFF);
|
||||
int headerSize = (int) CfbReader.u32(data, off);
|
||||
int dataOff = 14 + headerSize
|
||||
+ (bits == 1 || bits == 4 || bits == 8 ? (1 << bits) * 4 : 0);
|
||||
bmp[10] = (byte) dataOff;
|
||||
bmp[11] = (byte) (dataOff >>> 8);
|
||||
System.arraycopy(data, off, bmp, 14, len);
|
||||
return bmp;
|
||||
}
|
||||
|
||||
private static boolean startsWith(byte[] data, int off, int len, byte[] sig) {
|
||||
if (len < sig.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < sig.length; i++) {
|
||||
if (data[off + i] != sig[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static byte[] slice(byte[] data, int off, int len) {
|
||||
byte[] out = new byte[len];
|
||||
System.arraycopy(data, off, out, 0, len);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Индекс прямых свойств абзацев PAPX: FC-диапазон абзаца → Grpprl.
|
||||
*
|
||||
* <p>Алгоритм [MS-DOC] §2.4.6.1 (Direct Paragraph Formatting): PlcfBtePapx —
|
||||
* PLC (aFc n+1, PnFkpPapx n по 4 байта: pn 22 бита); PapxFkp-страница по
|
||||
* {@code pn*512} в WordDocument-потоке: rgfc (cpara+1 × 4), rgbx (cpara ×
|
||||
* BxPap — по 13 байт: bOffset 1 + reserved 12, §2.9.16; PapxInFkp по
|
||||
* {@code bOffset*2}), cpara — последний байт. BxPap.bOffset=0 → абзац по
|
||||
* умолчанию (ms-doc.md:5635). PapxInFkp (§2.9.175):
|
||||
* cb (1 байт); при cb≠0 GrpPrlAndIstd занимает 2×cb−1 байт, при cb=0 —
|
||||
* следующий байт cb' и 2×cb' байт; GrpPrlAndIstd = istd(2) + grpprl.
|
||||
* istd игнорируется (стили — вне контура первого инкремента).</p>
|
||||
*/
|
||||
final class PapxIndex {
|
||||
|
||||
private static final int FKP_PAGE_SIZE = 512;
|
||||
|
||||
private record Range(long fcStart, long fcEnd, byte[] grpprl) {
|
||||
}
|
||||
|
||||
private final List<Range> ranges = new ArrayList<>();
|
||||
|
||||
private PapxIndex(byte[] tableStream, long fcBte, long lcbBte, byte[] wordDocument) {
|
||||
if (lcbBte <= 0) {
|
||||
return;
|
||||
}
|
||||
if (fcBte < 0 || fcBte + lcbBte > tableStream.length || (lcbBte - 4) % 8 != 0) {
|
||||
throw new ValidationException("Битый PlcfBtePapx в .doc");
|
||||
}
|
||||
int n = (int) ((lcbBte - 4) / 8);
|
||||
for (int i = 0; i < n; i++) {
|
||||
long fcStart = CfbReader.u32(tableStream, (int) fcBte + i * 4);
|
||||
long fcEnd = CfbReader.u32(tableStream, (int) fcBte + i * 4 + 4);
|
||||
long pn = CfbReader.u32(tableStream, (int) fcBte + (n + 1) * 4 + i * 4) & 0x3FFFFFL;
|
||||
long pageOff = pn * FKP_PAGE_SIZE;
|
||||
if (pageOff + FKP_PAGE_SIZE > wordDocument.length) {
|
||||
throw new ValidationException("PapxFkp вне WordDocument-потока в .doc");
|
||||
}
|
||||
int cpara = wordDocument[(int) (pageOff + FKP_PAGE_SIZE - 1)] & 0xFF;
|
||||
if (cpara < 1 || cpara > 0x60) {
|
||||
throw new ValidationException("Битый cpara в PapxFkp .doc");
|
||||
}
|
||||
for (int j = 0; j < cpara; j++) {
|
||||
long rgfcStart = CfbReader.u32(wordDocument, (int) pageOff + j * 4);
|
||||
long rgfcEnd = CfbReader.u32(wordDocument, (int) pageOff + (j + 1) * 4);
|
||||
int bx = wordDocument[(int) pageOff + 4 * (cpara + 1) + j * 13] & 0xFF;
|
||||
if (bx == 0 || rgfcEnd <= rgfcStart) {
|
||||
continue;
|
||||
}
|
||||
int infkp = (int) pageOff + bx * 2;
|
||||
int cb = wordDocument[infkp] & 0xFF;
|
||||
// GrpPrlAndIstd: при cb≠0 занимает 2×cb−1 байт со следующего;
|
||||
// при cb=0 — следующий байт cb' и 2×cb' байт со следующего+1
|
||||
// (§2.9.175). Внутри: istd(2) + Prl'ы без счётчика (§3, Figure 33).
|
||||
int stdStart = cb != 0 ? infkp + 1 : infkp + 2;
|
||||
int stdSize = cb != 0 ? 2 * cb - 1 : 2 * (wordDocument[infkp + 1] & 0xFF);
|
||||
int grpprlLen = stdSize - 2;
|
||||
if (grpprlLen <= 0 || stdStart + 2 + grpprlLen > pageOff + FKP_PAGE_SIZE) {
|
||||
continue;
|
||||
}
|
||||
byte[] grpprl = new byte[grpprlLen];
|
||||
System.arraycopy(wordDocument, stdStart + 2, grpprl, 0, grpprlLen);
|
||||
ranges.add(new Range(Math.max(rgfcStart, fcStart), Math.min(rgfcEnd, fcEnd), grpprl));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static PapxIndex read(byte[] tableStream, long fcBte, long lcbBte, byte[] wordDocument) {
|
||||
return new PapxIndex(tableStream, fcBte, lcbBte, wordDocument);
|
||||
}
|
||||
|
||||
/** Grpprl абзаца, содержащего FC, или пустой массив (дефолт). */
|
||||
byte[] grpprlFor(long fc) {
|
||||
for (Range r : ranges) {
|
||||
if (fc >= r.fcStart() && fc < r.fcEnd()) {
|
||||
return r.grpprl();
|
||||
}
|
||||
}
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
/** Число абзацев с sprmPFPageBreakBefore=1 (для lightweight-подсчёта страниц). */
|
||||
int countPageBreakBefore() {
|
||||
int[] count = {0};
|
||||
for (Range r : ranges) {
|
||||
Grpprl.scan(r.grpprl(), 0, r.grpprl().length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_P_F_PAGE_BREAK_BEFORE && Grpprl.toggleOn(buf, off)) {
|
||||
count[0]++;
|
||||
}
|
||||
});
|
||||
}
|
||||
return count[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Piece table (.doc): карта Character Position → текст в WordDocument-потоке.
|
||||
*
|
||||
* <p>[MS-DOC] §2.4.1 (Retrieving Text): Clx (§2.9.38) — последовательность
|
||||
* Prc ({@code clxt}=0x01, пропускается по длине) и ровно один Pcdt
|
||||
* ({@code clxt}=0x02, §2.9.178) с PlcPcd (§2.8.35). Pcd (§2.9.177): fc —
|
||||
* 30 бит смещения + {@code fCompressed} (бит 30): при 1 текст 8-битный по
|
||||
* {@code fc/2} (байты 0x82–0x9F маппятся на Unicode, остальные U+00XX),
|
||||
* при 0 — UTF-16LE по {@code fc}.</p>
|
||||
*
|
||||
* <p>FC для поиска свойств (§2.4.6.1 шаг 3) — та же поправка: сжатый кусок
|
||||
* даёт {@code fc/2 + (cp - aCp[i])}, несжатый — {@code fc + 2*(cp - aCp[i])}.</p>
|
||||
*/
|
||||
final class PieceTable {
|
||||
|
||||
/** clxt-маркеры Clx (§2.9.38). */
|
||||
private static final int CLXT_PRC = 0x01;
|
||||
private static final int CLXT_PCDT = 0x02;
|
||||
|
||||
/** Бит fCompressed в Pcd.fc (§2.9.177). */
|
||||
private static final long F_COMPRESSED = 0x4000_0000L;
|
||||
private static final long FC_MASK = 0x3FFF_FFFFL;
|
||||
|
||||
/** Байты 0x80–0x9F сжатого текста → Unicode (§2.4.1, таблица Pcd.fc). */
|
||||
private static final char[] COMPRESSED_MAP = new char[32];
|
||||
|
||||
static {
|
||||
int[][] map = {
|
||||
{0x82, 0x201A}, {0x83, 0x0192}, {0x84, 0x201E}, {0x85, 0x2026},
|
||||
{0x86, 0x2020}, {0x87, 0x2021}, {0x88, 0x02C6}, {0x89, 0x2030},
|
||||
{0x8A, 0x0160}, {0x8B, 0x2039}, {0x8C, 0x0152}, {0x91, 0x2018},
|
||||
{0x92, 0x2019}, {0x93, 0x201C}, {0x94, 0x201D}, {0x95, 0x2022},
|
||||
{0x96, 0x2013}, {0x97, 0x2014}, {0x98, 0x02DC}, {0x99, 0x2122},
|
||||
{0x9A, 0x0161}, {0x9B, 0x203A}, {0x9C, 0x0153}, {0x9F, 0x0178},
|
||||
};
|
||||
for (int[] e : map) {
|
||||
COMPRESSED_MAP[e[0] - 0x80] = (char) e[1];
|
||||
}
|
||||
}
|
||||
|
||||
private final byte[] wordDocument;
|
||||
private final int[] aCp;
|
||||
private final long[] fc;
|
||||
private final boolean[] compressed;
|
||||
|
||||
private PieceTable(byte[] tableStream, long fcClx, long lcbClx, byte[] wordDocument) {
|
||||
this.wordDocument = wordDocument;
|
||||
if (lcbClx <= 0) {
|
||||
throw new ValidationException("В .doc нет piece table");
|
||||
}
|
||||
if (fcClx < 0 || fcClx + lcbClx > tableStream.length) {
|
||||
throw new ValidationException("Clx .doc выходит за табличный поток");
|
||||
}
|
||||
int p = (int) fcClx;
|
||||
int end = (int) (fcClx + lcbClx);
|
||||
int plcStart = -1;
|
||||
int plcEnd = -1;
|
||||
while (p < end) {
|
||||
int clxt = tableStream[p] & 0xFF;
|
||||
if (clxt == CLXT_PRC) {
|
||||
if (p + 3 > end) {
|
||||
throw new ValidationException("Обрезанный Clx в .doc");
|
||||
}
|
||||
int cb = (int) (CfbReader.u32(tableStream, p + 1) & 0xFFFF);
|
||||
p += 3 + cb;
|
||||
} else if (clxt == CLXT_PCDT) {
|
||||
if (p + 5 > end) {
|
||||
throw new ValidationException("Обрезанный Clx в .doc");
|
||||
}
|
||||
long lcb = CfbReader.u32(tableStream, p + 1);
|
||||
plcStart = p + 5;
|
||||
plcEnd = plcStart + (int) lcb;
|
||||
if (plcEnd > end) {
|
||||
throw new ValidationException("Pcdt выходит за Clx в .doc");
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
throw new ValidationException("Неизвестный clxt 0x" + Integer.toHexString(clxt) + " в Clx .doc");
|
||||
}
|
||||
}
|
||||
if (plcStart < 0) {
|
||||
throw new ValidationException("В Clx .doc нет Pcdt");
|
||||
}
|
||||
int lcb = plcEnd - plcStart;
|
||||
if ((lcb - 4) % 12 != 0 || lcb < 16) {
|
||||
throw new ValidationException("Битый PlcPcd в .doc");
|
||||
}
|
||||
int n = (lcb - 4) / 12;
|
||||
aCp = new int[n + 1];
|
||||
fc = new long[n];
|
||||
compressed = new boolean[n];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
aCp[i] = (int) CfbReader.u32(tableStream, plcStart + i * 4);
|
||||
if (i > 0 && aCp[i] < aCp[i - 1]) {
|
||||
throw new ValidationException("Невозрастающие aCP в PlcPcd .doc");
|
||||
}
|
||||
}
|
||||
int pcdBase = plcStart + (n + 1) * 4;
|
||||
for (int i = 0; i < n; i++) {
|
||||
long fcw = CfbReader.u32(tableStream, pcdBase + i * 8 + 2);
|
||||
fc[i] = fcw & FC_MASK;
|
||||
compressed[i] = (fcw & F_COMPRESSED) != 0;
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
long start = compressed[i] ? fc[i] / 2 : fc[i];
|
||||
long span = (long) (aCp[i + 1] - aCp[i]) * (compressed[i] ? 1 : 2);
|
||||
if (start + span > wordDocument.length) {
|
||||
throw new ValidationException("Кусок piece table .doc выходит за WordDocument");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static PieceTable read(byte[] tableStream, long fcClx, long lcbClx, byte[] wordDocument) {
|
||||
return new PieceTable(tableStream, fcClx, lcbClx, wordDocument);
|
||||
}
|
||||
|
||||
/** Символ по CP (§2.4.1); {@code cp} вне [0, ccpText) не запрашивается. */
|
||||
char charAt(int cp) {
|
||||
int i = pieceOf(cp);
|
||||
int delta = cp - aCp[i];
|
||||
if (compressed[i]) {
|
||||
int b = wordDocument[(int) (fc[i] / 2) + delta] & 0xFF;
|
||||
if (b >= 0x80 && b < 0xA0) {
|
||||
char mapped = COMPRESSED_MAP[b - 0x80];
|
||||
return mapped != 0 ? mapped : (char) b;
|
||||
}
|
||||
return (char) b;
|
||||
}
|
||||
int off = (int) fc[i] + 2 * delta;
|
||||
return (char) ((wordDocument[off] & 0xFF) | ((wordDocument[off + 1] & 0xFF) << 8));
|
||||
}
|
||||
|
||||
/** FC для поиска CHPX/PAPX (§2.4.6.1 шаг 3): со сжатием — {@code fc/2 + delta}. */
|
||||
long fcOf(int cp) {
|
||||
int i = pieceOf(cp);
|
||||
int delta = cp - aCp[i];
|
||||
return compressed[i] ? fc[i] / 2 + delta : fc[i] + 2L * delta;
|
||||
}
|
||||
|
||||
/** Шаг FC на символ в куске, содержащем {@code cp}: 1 (сжатый) или 2. */
|
||||
int step(int cp) {
|
||||
return compressed[pieceOf(cp)] ? 1 : 2;
|
||||
}
|
||||
|
||||
/** CP первого символа следующего после {@code cp} куска (или {@code ccpLimit}). */
|
||||
int nextPieceBoundary(int cp, int ccpLimit) {
|
||||
int i = pieceOf(cp);
|
||||
return Math.min(aCp[i + 1], ccpLimit);
|
||||
}
|
||||
|
||||
private int pieceOf(int cp) {
|
||||
int lo = 0;
|
||||
int hi = fc.length - 1;
|
||||
while (lo < hi) {
|
||||
int mid = (lo + hi + 1) >>> 1;
|
||||
if (aCp[mid] <= cp) {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
if (cp >= aCp[lo + 1]) {
|
||||
throw new ValidationException("Символ .doc вне piece table");
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Свойства секций (.doc) → параметры полосы набора и поправка подсчёта страниц.
|
||||
*
|
||||
* <p>[MS-DOC] §2.8.26 PlcfSed: PLC (aCP n+1, Sed n по 12 байт); Sed =
|
||||
* fn(2) + fcSepx(4) + fnMpr(2) + fcMpr(4); fcSepx — указатель на Sepx
|
||||
* (§2.9.245) в WordDocument-потоке: cb (2 байта) + grpprl секционных sprm;
|
||||
* Sepx секции i описывает секцию от aCP[i] до aCP[i+1] (§3, Figure 13).
|
||||
* Выходной документ односекционный: геометрию берёт последняя секция
|
||||
* (как {@code w:sectPr} уровня документа). Свойств нет — дефолты Word 97:
|
||||
* Letter 12240×15840, поля 1440, колонтитуки 720 (значения §2.6.3
|
||||
* «By default» для sprmSXaPage/sprmSYaPage).</p>
|
||||
*
|
||||
* <p>{@link #continuousSectionEnds()} — число межсекционных разрывов, не
|
||||
* начинающих новую страницу (sprmSBkc = bkcContinuous/bkcNewColumn, §2.6.3;
|
||||
* дефолт — bkcNewPage, поэтому отсутствие sprmSBkc не вычитается).</p>
|
||||
*/
|
||||
final class Sections {
|
||||
|
||||
/** Дефолты Word 97 (§2.6.3, twips). */
|
||||
private static final int DEFAULT_PAGE_WIDTH = 12240;
|
||||
private static final int DEFAULT_PAGE_HEIGHT = 15840;
|
||||
private static final int DEFAULT_MARGIN = 1440;
|
||||
private static final int DEFAULT_HEADER_FOOTER = 720;
|
||||
|
||||
private static final int SED_SIZE = 12;
|
||||
private static final int SED_OFF_FC_SEPX = 2;
|
||||
|
||||
private int pageWidth = DEFAULT_PAGE_WIDTH;
|
||||
private int pageHeight = DEFAULT_PAGE_HEIGHT;
|
||||
private int marginLeft = DEFAULT_MARGIN;
|
||||
private int marginRight = DEFAULT_MARGIN;
|
||||
private int marginTop = DEFAULT_MARGIN;
|
||||
private int marginBottom = DEFAULT_MARGIN;
|
||||
private int header = DEFAULT_HEADER_FOOTER;
|
||||
private int footer = DEFAULT_HEADER_FOOTER;
|
||||
private int continuousEnds;
|
||||
|
||||
private Sections(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument) {
|
||||
if (lcbSed <= 0) {
|
||||
return;
|
||||
}
|
||||
if (fcSed < 0 || fcSed + lcbSed > tableStream.length || (lcbSed - 4) % (4 + SED_SIZE) != 0) {
|
||||
throw new ValidationException("Битый PlcfSed в .doc");
|
||||
}
|
||||
int n = (int) ((lcbSed - 4) / (4 + SED_SIZE));
|
||||
int sedBase = (int) fcSed + (n + 1) * 4;
|
||||
for (int i = 0; i < n; i++) {
|
||||
long fcSepx = CfbReader.u32(tableStream, sedBase + i * SED_SIZE + SED_OFF_FC_SEPX);
|
||||
if (fcSepx == 0 || fcSepx + 2 > wordDocument.length) {
|
||||
continue;
|
||||
}
|
||||
int cb = (int) (CfbReader.u32(wordDocument, (int) fcSepx) & 0xFFFF);
|
||||
if (cb <= 0 || fcSepx + 2 + cb > wordDocument.length) {
|
||||
continue;
|
||||
}
|
||||
boolean last = i == n - 1;
|
||||
Grpprl.scan(wordDocument, (int) fcSepx + 2, cb, (sprm, buf, off, len) -> {
|
||||
int v = Grpprl.operandInt(buf, off, len);
|
||||
if (last) {
|
||||
applyGeometry(sprm, v);
|
||||
} else if (sprm == Grpprl.SPRM_S_BKC && v <= 1) {
|
||||
// bkcContinuous=0 / bkcNewColumn=1 (§2.6.3 SBkcOperand):
|
||||
// разрыв не начинает новую страницу
|
||||
continuousEnds++;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void applyGeometry(int sprm, int value) {
|
||||
if (sprm == Grpprl.SPRM_S_XA_PAGE) {
|
||||
pageWidth = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_YA_PAGE) {
|
||||
pageHeight = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DXA_LEFT) {
|
||||
marginLeft = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DXA_RIGHT) {
|
||||
marginRight = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_TOP) {
|
||||
marginTop = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_BOTTOM) {
|
||||
marginBottom = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_HDR_TOP) {
|
||||
header = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_HDR_BOTTOM) {
|
||||
footer = value;
|
||||
}
|
||||
}
|
||||
|
||||
static Sections read(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument) {
|
||||
return new Sections(tableStream, fcSed, lcbSed, wordDocument);
|
||||
}
|
||||
|
||||
int pageWidth() {
|
||||
return pageWidth;
|
||||
}
|
||||
|
||||
int pageHeight() {
|
||||
return pageHeight;
|
||||
}
|
||||
|
||||
int marginLeft() {
|
||||
return marginLeft;
|
||||
}
|
||||
|
||||
int marginRight() {
|
||||
return marginRight;
|
||||
}
|
||||
|
||||
int marginTop() {
|
||||
return marginTop;
|
||||
}
|
||||
|
||||
int marginBottom() {
|
||||
return marginBottom;
|
||||
}
|
||||
|
||||
int header() {
|
||||
return header;
|
||||
}
|
||||
|
||||
int footer() {
|
||||
return footer;
|
||||
}
|
||||
|
||||
int continuousSectionEnds() {
|
||||
return continuousEnds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
/**
|
||||
* Кэш числа страниц из потока {@code \x05SummaryInformation}.
|
||||
*
|
||||
* <p>[MS-OLEPS] §2.21 PropertySetStream: заголовок — ByteOrder(2) Version(2)
|
||||
* SystemIdentifier(4) CLSID(16) NumPropertySets(4) FMTID0(16) Offset0(4);
|
||||
* PropertySet по Offset0 (§2.20): cbPropertySet(4) NumProperties(4) + массив
|
||||
* (pid, offset), где offset свойства — <b>относительно начала PropertySet</b>
|
||||
* (§2.2: «relative to the starting position of the PropertySet»), т.е. читать
|
||||
* по {@code Offset0 + offset}; свойство по offset — VT(4) + значение. Ищем PIDSI_PAGECOUNT
|
||||
* (0x0000000E, VT_I4=3) — аналог {@code <Pages>} из docProps/app.xml у .docx.
|
||||
* Потока/свойства нет или оно не VT_I4 → 0 (оценка нижняя, как у docx).</p>
|
||||
*/
|
||||
final class SummaryInfo {
|
||||
|
||||
/** PIDSI_PAGECOUNT (MS-OLEPS §2.4.2). */
|
||||
private static final int PID_PAGE_COUNT = 0x0000000E;
|
||||
|
||||
/** VT_I4 (MS-OLEPS §2.3.2). */
|
||||
private static final int VT_I4 = 0x00000003;
|
||||
|
||||
/** Смещения заголовка PropertySetStream (§2.21). */
|
||||
private static final int OFF_OFFSET0 = 0x2C;
|
||||
private static final int HEADER_SIZE = 0x30;
|
||||
|
||||
private SummaryInfo() {
|
||||
}
|
||||
|
||||
/** Кэшированное число страниц; 0 — нет данных. */
|
||||
static int pageCount(byte[] summaryStream) {
|
||||
if (summaryStream.length < HEADER_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
long offset0 = CfbReader.u32(summaryStream, OFF_OFFSET0);
|
||||
if (offset0 < HEADER_SIZE || offset0 + 8 > summaryStream.length) {
|
||||
return 0;
|
||||
}
|
||||
long numProps = CfbReader.u32(summaryStream, (int) offset0 + 4);
|
||||
if (numProps <= 0 || numProps > 0x1000) {
|
||||
return 0;
|
||||
}
|
||||
for (int i = 0; i < numProps; i++) {
|
||||
int pps = (int) offset0 + 8 + i * 8;
|
||||
if (pps + 8 > summaryStream.length) {
|
||||
return 0;
|
||||
}
|
||||
int pid = (int) CfbReader.u32(summaryStream, pps);
|
||||
long propOff = offset0 + CfbReader.u32(summaryStream, pps + 4);
|
||||
if (pid == PID_PAGE_COUNT && propOff + 8 <= summaryStream.length
|
||||
&& CfbReader.u32(summaryStream, (int) propOff) == VT_I4) {
|
||||
return (int) CfbReader.u32(summaryStream, (int) propOff + 4);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,20 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void chartsSmartArt_drawingsBecomeImages() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("charts-smartart.docx"), "charts-smartart");
|
||||
assertDrawingsBecomeImages("charts-smartart.docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* Тот же паритет для samples/charts-smartart.doc: BLIP'ы OfficeArt
|
||||
* извлекаются мостом в image-части, растров в PDF не меньше четырёх.
|
||||
*/
|
||||
@Test
|
||||
void chartsSmartArt_docDrawingsBecomeImages() throws Exception {
|
||||
assertDrawingsBecomeImages("charts-smartart.doc");
|
||||
}
|
||||
|
||||
private static void assertDrawingsBecomeImages(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("Диаграммы"), "пропал текст вокруг диаграмм: " + text);
|
||||
@@ -236,7 +249,21 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void oleObjects_removedAndConverted() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("ole-embedded.docx"), "ole-embedded");
|
||||
assertOleObjectsRemoved("ole-embedded.docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* samples/ole-embedded.doc: OLE-объект ([MS-DOC] U+0001 +
|
||||
* sprmCFOle2) не читается — мост берёт VML-плейсхолдер (BLIP по
|
||||
* {@code sprmCPicLocation}=0) и пишет штатной картинкой.
|
||||
*/
|
||||
@Test
|
||||
void oleObjects_docRemovedAndConverted() throws Exception {
|
||||
assertOleObjectsRemoved("ole-embedded.doc");
|
||||
}
|
||||
|
||||
private static void assertOleObjectsRemoved(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("OLE object test before"),
|
||||
@@ -251,6 +278,10 @@ class WordPdfConverterTest {
|
||||
/**
|
||||
* errorOnOle=true — {@link DrawingFoundException} с {@code Kind.OLE},
|
||||
* документ отвергается. Фикстура samples/ole-embedded.docx.
|
||||
*
|
||||
* <p>Флаг действует только на .docx: в бинарном .doc OLE-объект —
|
||||
* не часть, а форматирование U+0001, и мост деградирует его до
|
||||
* картинки-плейсхолдера (см. {@link #oleObjects_docRemovedAndConverted()}).</p>
|
||||
*/
|
||||
@Test
|
||||
void drawingErrors_errorFlagRejectsOle() throws Exception {
|
||||
@@ -296,25 +327,30 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void exoticGlyphs_drawnNotHash() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("exotic-glyphs.docx"), "exotic-glyphs");
|
||||
assertExoticGlyphs("exotic-glyphs.docx");
|
||||
assertExoticGlyphs("exotic-glyphs.doc");
|
||||
}
|
||||
|
||||
private static void assertExoticGlyphs(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
String text = norm(pdfText(pdf));
|
||||
|
||||
for (String ch : List.of("\u2152", "\u2181", "\u058D", "\u08E1")) {
|
||||
assertTrue(text.contains(ch), "нет символа U+"
|
||||
assertTrue(text.contains(ch), fixture + ": нет символа U+"
|
||||
+ Integer.toHexString(ch.charAt(0)) + ": " + text);
|
||||
}
|
||||
assertFalse(text.contains("#"),
|
||||
"в PDF остались .notdef-решётки: " + text);
|
||||
fixture + ": в PDF остались .notdef-решётки: " + text);
|
||||
|
||||
// Римская цифра — вшитым DejaVu Serif, а не базовым Helvetica
|
||||
assertTrue(fontNameOf(pdf, '\u2181').contains("DejaVuSerif"),
|
||||
"римская цифра нарисована не DejaVu Serif");
|
||||
fixture + ": римская цифра нарисована не DejaVu Serif");
|
||||
// Армянский знак Unicode 16 — Noto Sans Armenian
|
||||
assertTrue(fontNameOf(pdf, '\u058D').contains("NotoSansArmenian"),
|
||||
"армянский знак нарисован не Noto Sans Armenian");
|
||||
fixture + ": армянский знак нарисован не Noto Sans Armenian");
|
||||
// Соседний обычный текст не уехал в подставленное семейство
|
||||
assertTrue(fontNameOf(pdf, 'ы').contains("Tinos"),
|
||||
"кириллица уехала с Tinos");
|
||||
fixture + ": кириллица уехала с Tinos");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,26 +362,48 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void pageNumbers_recomputedNotCached() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("page-numbers.docx"), "page-numbers");
|
||||
assertPageNumbers("page-numbers.docx");
|
||||
// .doc: колонтитуки с полями PAGE/NUMPAGES переносит мост (Headers +
|
||||
// fldSimple), кэш результата (2 / 11) в PDF не попадает
|
||||
assertPageNumbers("page-numbers.doc");
|
||||
}
|
||||
|
||||
for (int page = 1; page <= 3; page++) {
|
||||
private static void assertPageNumbers(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
int pages;
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
pages = doc.getNumberOfPages();
|
||||
}
|
||||
assertTrue(pages >= 2, fixture + ": колонтитукам негде рендериться");
|
||||
for (int page = 1; page <= pages; page++) {
|
||||
String text = norm(pdfPageText(pdf, page));
|
||||
assertTrue(text.contains("Страница " + page),
|
||||
"страница " + page + " содержит не своё содержимое: " + text);
|
||||
assertTrue(text.contains(page + " / 3"),
|
||||
"колонтитул страницы " + page + " не пересчитан: " + text);
|
||||
fixture + ": страница " + page + " содержит не своё содержимое: " + text);
|
||||
assertTrue(text.contains(page + " / " + pages),
|
||||
fixture + ": колонтитул страницы " + page + " не пересчитан: " + text);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruPlain_cyrillicAndStyles() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("ru-plain.docx"), "ru-plain")));
|
||||
assertCyrillicAndStyles("ru-plain.docx");
|
||||
// .doc-двойник фикстуры — тот же текст через мост internal.doc
|
||||
assertCyrillicAndStyles("ru-plain.doc");
|
||||
}
|
||||
|
||||
assertTrue(text.contains("Привет, мир!"), "нет «Привет, мир!»: " + text);
|
||||
private static void assertCyrillicAndStyles(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Привет, мир!"), fixture + ": нет «Привет, мир!»: " + text);
|
||||
// Полный кириллический алфавит — проверка, что все глифы встроились
|
||||
assertTrue(text.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"),
|
||||
"нет кириллического алфавита: " + text);
|
||||
assertTrue(text.contains("жирный курсив"), "нет «жирный курсив»: " + text);
|
||||
fixture + ": нет кириллического алфавита: " + text);
|
||||
assertTrue(text.contains("жирный курсив"), fixture + ": нет «жирный курсив»: " + text);
|
||||
}
|
||||
|
||||
/** Имя фикстуры без расширения — PDF-title и имя temp-файла. */
|
||||
private static String baseName(String fixture) {
|
||||
return fixture.replaceAll("\\.docx?$", "");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -398,34 +456,63 @@ class WordPdfConverterTest {
|
||||
|
||||
@Test
|
||||
void enPlain_englishText() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("en-plain.docx"), "en-plain")));
|
||||
assertEnglishText("en-plain.docx");
|
||||
assertEnglishText("en-plain.doc");
|
||||
}
|
||||
|
||||
assertTrue(text.contains("Hello, world!"), "нет «Hello, world!»: " + text);
|
||||
assertTrue(text.contains("quick brown fox"), "нет «quick brown fox»: " + text);
|
||||
private static void assertEnglishText(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Hello, world!"), fixture + ": нет «Hello, world!»: " + text);
|
||||
assertTrue(text.contains("quick brown fox"), fixture + ": нет «quick brown fox»: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixed_headingListTable() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("ru-en-mixed.docx"), "ru-en-mixed")));
|
||||
assertHeadingListTable("ru-en-mixed.docx");
|
||||
assertHeadingListTable("ru-en-mixed.doc");
|
||||
}
|
||||
|
||||
assertTrue(text.contains("Смешанный документ"), "нет заголовка: " + text);
|
||||
assertTrue(text.contains("first item"), "нет пункта списка: " + text);
|
||||
private static void assertHeadingListTable(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Смешанный документ"), fixture + ": нет заголовка: " + text);
|
||||
assertTrue(text.contains("first item"), fixture + ": нет пункта списка: " + text);
|
||||
assertTrue(text.contains("Ячейка А") && text.contains("Cell B"),
|
||||
"нет ячеек таблицы: " + text);
|
||||
fixture + ": нет ячеек таблицы: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruTimes_russianInTimes() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("ru-times.docx"), "ru-times")));
|
||||
assertRussianInTimes("ru-times.docx");
|
||||
assertRussianInTimes("ru-times.doc");
|
||||
}
|
||||
|
||||
private static void assertRussianInTimes(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Съешь ещё этих мягких французских булок"),
|
||||
"нет русского текста: " + text);
|
||||
fixture + ": нет русского текста: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableImage_tableAndImage() throws Exception {
|
||||
byte[] docx = sampleBytes("ru-table-image.docx");
|
||||
String text = norm(pdfText(convertPdf(docx, "ru-table-image")));
|
||||
assertTableImage("ru-table-image.docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* samples/ru-table-image.doc: картинка — BLIP OfficeArt по
|
||||
* {@code sprmCPicLocation}; мост извлекает PNG в image-часть,
|
||||
* таблица и картинка рендерятся как в .docx.
|
||||
*/
|
||||
@Test
|
||||
void tableImage_docTableAndImage() throws Exception {
|
||||
assertTableImage("ru-table-image.doc");
|
||||
}
|
||||
|
||||
private static void assertTableImage(String fixture) throws Exception {
|
||||
byte[] docx = sampleBytes(fixture);
|
||||
String text = norm(pdfText(convertPdf(docx, baseName(fixture))));
|
||||
|
||||
// Таблица без tblGrid/tcW (auto-fit): docx4j 17.x считает ширины
|
||||
// колонок по контенту и вместе с padding'ом ячейки не оставляет
|
||||
@@ -436,7 +523,7 @@ class WordPdfConverterTest {
|
||||
assertTrue(flat.contains("Русский"), "нет «Русский»: " + text);
|
||||
|
||||
// Изображение: ищем XObject'ы-изображения среди ресурсов страниц
|
||||
Path pdf = convertPdf(docx, "ru-table-image");
|
||||
Path pdf = convertPdf(docx, baseName(fixture));
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
int images = 0;
|
||||
for (PDPage page : doc.getPages()) {
|
||||
@@ -482,9 +569,9 @@ class WordPdfConverterTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Вход без zip-подписи — отказ как некорректный вход (ValidationException),
|
||||
* а не ошибка рендера: вход конвертера прогоняет тот же
|
||||
* {@link WordPdfValidator#validate(byte[], ConvertOptions)}, что и приложение до очереди.
|
||||
* Вход без подписи какого-либо поддерживаемого контейнера (ни zip,
|
||||
* ни CFB) — отказ как некорректный вход (ValidationException),
|
||||
* а не ошибка рендера: сообщение перечисляет оба формата.
|
||||
* Регрессия — WordPdfValidatorTest#validate_notAZip.
|
||||
*/
|
||||
@Test
|
||||
@@ -492,8 +579,8 @@ class WordPdfConverterTest {
|
||||
byte[] junk = {1, 2, 3, 4, 5, 6, 7, 8};
|
||||
ValidationException ex = assertThrows(ValidationException.class, () ->
|
||||
WordPdfConverter.convert(junk, "junk"));
|
||||
assertTrue(ex.getMessage().contains("не zip-архив"),
|
||||
"сообщение должно упоминать zip-подпись: " + ex.getMessage());
|
||||
assertTrue(ex.getMessage().contains("не похоже на .docx или .doc"),
|
||||
"сообщение должно перечислять форматы: " + ex.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -539,12 +626,18 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void tooManyPages() {
|
||||
assertTooManyPages("too-many-pages.docx");
|
||||
// .doc: 150 разрывов 0x0C считает мост по чистому бинарному документу
|
||||
assertTooManyPages("too-many-pages.doc");
|
||||
}
|
||||
|
||||
private static void assertTooManyPages(String fixture) {
|
||||
ValidationException ex = assertThrows(ValidationException.class, () ->
|
||||
WordPdfConverter.convert(
|
||||
sampleBytes("too-many-pages.docx"), "too-many-pages",
|
||||
sampleBytes(fixture), baseName(fixture),
|
||||
new ConvertOptions(false, false, false, WordPdfSettings.MAX_INPUT_MB, 100)));
|
||||
assertTrue(ex.getMessage().contains("100"),
|
||||
"сообщение должно упоминать лимит: " + ex.getMessage());
|
||||
fixture + ": сообщение должно упоминать лимит: " + ex.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -563,6 +656,23 @@ class WordPdfConverterTest {
|
||||
"сообщение должно упоминать лимит: " + ex.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* Семантическое различие форматов: stale-cache.docx отвергается
|
||||
* (кэш {@code <Pages>1</Pages>} проигрывает 110 маркерам
|
||||
* {@code w:lastRenderedPageBreak}), а stale-cache.doc конвертируется:
|
||||
* в бинарном .doc понятия lastRenderedPageBreak нет, нижняя оценка —
|
||||
* кэш PageCount=5 плюс явные разрывы, и она в лимите 100.
|
||||
* Регрессия — WordPdfConverterTest#staleCache_docConvertsByCacheOnly.
|
||||
*/
|
||||
@Test
|
||||
void staleCache_docConvertsByCacheOnly() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("stale-cache.doc"), "stale-cache",
|
||||
new ConvertOptions(false, false, false, WordPdfSettings.MAX_INPUT_MB, 100));
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertTrue(doc.getNumberOfPages() >= 1, "PDF не отрендерился");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Заголовок PDF — параметр {@code title} (файлового API в ядре нет,
|
||||
* из имени файла заголовок больше не выводится).
|
||||
@@ -1165,4 +1275,43 @@ class WordPdfConverterTest {
|
||||
&& dfe.kind() == DrawingFoundException.Kind.CHARTS,
|
||||
"ожидался DrawingFoundException(CHARTS), получено: " + ex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Бинарный .doc (фикстура заказчика): текст и кириллица рендерятся
|
||||
* бандл-шрифтами без .notdef; страницы считаются по чистому .doc.
|
||||
* Регрессия — internal.doc.DocToDocx (мост .doc → .docx).
|
||||
*/
|
||||
@Test
|
||||
void docBinary_russianTextRenders() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("ru-plain.doc"), "ru-plain");
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("Тестовый документ (русский)"), "заголовок не отрисовался");
|
||||
assertTrue(text.contains("Привет, мир!"), "текст потерялся");
|
||||
assertTrue(text.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"), "алфавит потерялся");
|
||||
assertFalse(text.contains("#"), ".notdef-боксы в тексте");
|
||||
assertFalse(fontNameOf(pdf, 'П').contains("Helvetica"), "внешний шрифт");
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertEquals(1, doc.getNumberOfPages());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* .doc с прямым форматированием: sprmPFPageBreakBefore даёт вторую
|
||||
* страницу и удерживает лимит по чистому .doc (maxPages=1 → отказ).
|
||||
* Регрессия — Sections/PapxIndex (подсчёт страниц без конвертации).
|
||||
*/
|
||||
@Test
|
||||
void docBinary_formats_pageBreakAndLimit() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("doc-formats.doc"), "doc-formats");
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertEquals(2, doc.getNumberOfPages(), "pageBreakBefore не отделил страницу");
|
||||
}
|
||||
assertTrue(norm(pdfPageText(pdf, 2)).contains("Вторая страница после разрыва"),
|
||||
"второй страницы нет");
|
||||
assertThrows(ValidationException.class, () -> convertPdf(sampleBytes("doc-formats.doc"),
|
||||
"doc-formats", new ConvertOptions(false, false, false,
|
||||
WordPdfSettings.MAX_INPUT_MB, 1)),
|
||||
"лимит 1 страница не удержал двухстраничный .doc");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -571,4 +571,46 @@ class WordPdfValidatorTest {
|
||||
() -> WordPdfValidator.validate(new byte[]{'P', 'K', 0, 4},
|
||||
ConvertOptions.defaults()));
|
||||
}
|
||||
|
||||
/** Фикстура samples/*.doc (бинарный .doc заказчика). */
|
||||
private static byte[] sample(String name) throws Exception {
|
||||
try (java.io.InputStream in = WordPdfValidatorTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/" + name)) {
|
||||
assertNotNull(in, "Нет фикстуры: samples/" + name);
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* .doc: страницы считаются по чистому бинарному документу, ДО конвертации
|
||||
* в .docx (кэш PageCount + разрывы 0x0C + pageBreakBefore).
|
||||
* Регрессия — WordPdfValidator#checkPageCountDoc.
|
||||
*/
|
||||
@Test
|
||||
void checkPageCountDoc_onRawBinary() throws Exception {
|
||||
// too-many-pages.doc: 150 разрывов 0x0C → 151 — отказ
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> WordPdfValidator.checkPageCountDoc(sample("too-many-pages.doc"), PAGE_LIMIT));
|
||||
assertTrue(ex.getMessage().contains("не менее 151"), ex.getMessage());
|
||||
// stale-cache.doc: кэш 5 — проходит
|
||||
assertDoesNotThrow(() -> WordPdfValidator.checkPageCountDoc(
|
||||
sample("stale-cache.doc"), PAGE_LIMIT));
|
||||
// ru-plain.doc: 1 страница
|
||||
assertDoesNotThrow(() -> WordPdfValidator.checkPageCountDoc(
|
||||
sample("ru-plain.doc"), 1));
|
||||
// doc-formats.doc: 2 страницы (sprmPFPageBreakBefore) — лимит 1 отказывает
|
||||
ValidationException two = assertThrows(ValidationException.class,
|
||||
() -> WordPdfValidator.checkPageCountDoc(sample("doc-formats.doc"), 1));
|
||||
assertTrue(two.getMessage().contains("не менее 2"), two.getMessage());
|
||||
}
|
||||
|
||||
/** validate() роутирует .doc по CFB-подписи: страницы — без zip-проверок. */
|
||||
@Test
|
||||
void validate_binaryDocRoutedToDocPageCount() throws Exception {
|
||||
byte[] doc = sample("too-many-pages.doc");
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> WordPdfValidator.validate(doc,
|
||||
options(WordPdfSettings.MAX_INPUT_MB, PAGE_LIMIT)));
|
||||
assertTrue(ex.getMessage().contains("не менее 151"), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link CfbReader} ([MS-CFB]): крафтовый контейнер (сектор 512,
|
||||
* mini 64, cutoff 4096) и враждебные мутации — цикл в цепочках, ссылки за
|
||||
* файл, обрезанные потоки, битый заголовок.
|
||||
*/
|
||||
class CfbReaderTest {
|
||||
|
||||
private static final int SECTOR = 512;
|
||||
private static final int MINI = 64;
|
||||
private static final long FREE = 0xFFFF_FFFFL;
|
||||
private static final long END = 0xFFFF_FFFEL;
|
||||
private static final long FATSECT = 0xFFFF_FFFDL;
|
||||
|
||||
record Spec(String name, byte[] data) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Контейнер: сектор 0 — FAT, 1 — directory, 2 — MiniFAT (если есть
|
||||
* mini-потоки), далее mini stream, затем сектора больших потоков.
|
||||
*/
|
||||
private static byte[] build(Spec... specs) {
|
||||
List<Spec> small = new ArrayList<>();
|
||||
List<Spec> big = new ArrayList<>();
|
||||
for (Spec s : specs) {
|
||||
(s.data().length < 4096 ? small : big).add(s);
|
||||
}
|
||||
// mini stream + MiniFAT
|
||||
ByteArrayOutputStream mini = new ByteArrayOutputStream();
|
||||
int[] miniHead = new int[small.size()];
|
||||
int[] miniFat = new int[64];
|
||||
for (int i = 0; i < miniFat.length; i++) {
|
||||
miniFat[i] = (int) FREE;
|
||||
}
|
||||
int miniSects = 0;
|
||||
for (int i = 0; i < small.size(); i++) {
|
||||
byte[] d = small.get(i).data();
|
||||
miniHead[i] = miniSects;
|
||||
int n = Math.max(1, (d.length + MINI - 1) / MINI);
|
||||
mini.write(d, 0, d.length);
|
||||
for (int k = d.length; k < n * MINI; k++) {
|
||||
mini.write(0);
|
||||
}
|
||||
for (int k = 0; k < n; k++) {
|
||||
miniFat[miniSects + k] = k == n - 1 ? (int) END : miniSects + k + 1;
|
||||
}
|
||||
miniSects += n;
|
||||
}
|
||||
boolean hasMini = !small.isEmpty();
|
||||
int miniStart = hasMini ? 3 : -1;
|
||||
int bigStart = hasMini ? 3 + miniSects : 2;
|
||||
int[] fat = new int[128];
|
||||
for (int i = 0; i < fat.length; i++) {
|
||||
fat[i] = (int) FREE;
|
||||
}
|
||||
fat[0] = (int) FATSECT;
|
||||
fat[1] = (int) END;
|
||||
if (hasMini) {
|
||||
fat[2] = (int) END;
|
||||
}
|
||||
int next = bigStart;
|
||||
int[] bigHead = new int[big.size()];
|
||||
int[] bigSects = new int[big.size()];
|
||||
for (int i = 0; i < big.size(); i++) {
|
||||
bigHead[i] = next;
|
||||
int n = (big.get(i).data().length + SECTOR - 1) / SECTOR;
|
||||
bigSects[i] = n;
|
||||
for (int k = 0; k < n; k++) {
|
||||
fat[next + k] = k == n - 1 ? (int) END : next + k + 1;
|
||||
}
|
||||
next += n;
|
||||
}
|
||||
int sectorTotal = next;
|
||||
byte[] file = new byte[SECTOR * (1 + sectorTotal)];
|
||||
// заголовок (§2.2)
|
||||
System.arraycopy(CfbReader.SIGNATURE, 0, file, 0, 8);
|
||||
put16(file, 0x1E, 9); // sectorShift
|
||||
put16(file, 0x20, 6); // miniSectorShift
|
||||
put32(file, 0x30, 1); // firstDir
|
||||
put32(file, 0x38, 4096); // cutoff
|
||||
put32(file, 0x3C, hasMini ? 2 : (int) FREE); // firstMiniFat
|
||||
put32(file, 0x44, (int) FREE); // firstDifat
|
||||
put32(file, 0x48, 0); // cDifat
|
||||
put32(file, 0x4C, 0); // DIFAT[0] = сектор FAT
|
||||
for (int i = 1; i < 109; i++) {
|
||||
put32(file, 0x4C + i * 4, (int) FREE);
|
||||
}
|
||||
// FAT
|
||||
for (int i = 0; i < fat.length; i++) {
|
||||
put32(file, SECTOR + i * 4, fat[i]);
|
||||
}
|
||||
// directory: root + потоки
|
||||
dirEntry(file, 1, 0, "Root Entry", 5,
|
||||
hasMini ? miniStart : (int) END, mini.size());
|
||||
for (int i = 0; i < specs.length; i++) {
|
||||
Spec s = specs[i];
|
||||
boolean smallOne = s.data().length < 4096;
|
||||
int idx = -1;
|
||||
for (int k = 0; k < (smallOne ? small : big).size(); k++) {
|
||||
if ((smallOne ? small : big).get(k) == s) {
|
||||
idx = k;
|
||||
}
|
||||
}
|
||||
dirEntry(file, 1, 1 + i, s.name(), 2,
|
||||
smallOne ? miniHead[idx] : bigHead[idx], s.data().length);
|
||||
}
|
||||
// miniFAT
|
||||
if (hasMini) {
|
||||
for (int i = 0; i < miniFat.length; i++) {
|
||||
put32(file, SECTOR * (1 + 2) + i * 4, miniFat[i]);
|
||||
}
|
||||
System.arraycopy(mini.toByteArray(), 0, file, SECTOR * (1 + miniStart),
|
||||
mini.size());
|
||||
}
|
||||
// большие потоки
|
||||
for (int i = 0; i < big.size(); i++) {
|
||||
byte[] d = big.get(i).data();
|
||||
System.arraycopy(d, 0, file, SECTOR * (1 + bigHead[i]), d.length);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static void dirEntry(byte[] file, int dirSector, int index, String name,
|
||||
int type, int start, int size) {
|
||||
int base = SECTOR * (1 + dirSector) + index * 128;
|
||||
byte[] n = name.getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(n, 0, file, base, n.length);
|
||||
put16(file, base + 0x40, n.length + 2);
|
||||
file[base + 0x42] = (byte) type;
|
||||
put32(file, base + 0x74, start);
|
||||
put32(file, base + 0x78, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsBigAndMiniStreams() {
|
||||
byte[] big = new byte[5000];
|
||||
for (int i = 0; i < big.length; i++) {
|
||||
big[i] = (byte) i;
|
||||
}
|
||||
byte[] small = "WordDocument".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] file = build(new Spec("WordDocument", small), new Spec("Data", big));
|
||||
Map<String, byte[]> streams = CfbReader.readStreams(file);
|
||||
assertArrayEquals(small, streams.get("WordDocument"));
|
||||
assertArrayEquals(big, streams.get("Data"));
|
||||
// поиск регистронезависимый, отсутствующий — пустой массив
|
||||
assertArrayEquals(small, CfbReader.stream(streams, "worddocument"));
|
||||
assertEquals(0, CfbReader.stream(streams, "НетТакого").length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void badHeader_rejected() {
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(null));
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(new byte[511]));
|
||||
byte[] file = build();
|
||||
file[0] = 0;
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badSectorSizes_rejected() {
|
||||
byte[] badSector = build();
|
||||
put16(badSector, 0x1E, 10); // не 9 и не 12
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(badSector));
|
||||
byte[] badMini = build();
|
||||
put16(badMini, 0x20, 17); // mini shift за потолком
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(badMini));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dirChainLoop_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, SECTOR + 1 * 4, 1); // fat[1] = 1 — directory в цикл
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("цикл") || ex.getMessage().contains("Цикл"),
|
||||
ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dirSectorBeyondFat_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, 0x30, 200); // firstDir за FAT этого файла
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fatSectorBeyondFile_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, 0x4C, 100); // DIFAT[0] — FAT-сектор за концом файла
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void difatTooManyFatSectors_rejected() {
|
||||
byte[] file = build();
|
||||
for (int i = 0; i < 8; i++) {
|
||||
put32(file, 0x4C + i * 4, i); // 8 FAT-секторов в 4-секторном файле
|
||||
}
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("DIFAT"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void difatChainLoop_rejected() {
|
||||
byte[] file = build();
|
||||
// firstDifat = сектор 1; следующий указатель DIFAT — сам на себя
|
||||
put32(file, 0x44, 1);
|
||||
put32(file, SECTOR * 3 - 4, 1); // sect = u32(base + entries*4), entries=127
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("DIFAT"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void difatSectorBeyondFile_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, 0x44, 100);
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamChainBeyondFile_rejected() {
|
||||
byte[] big = new byte[5000];
|
||||
byte[] file = build(new Spec("Data", big));
|
||||
put32(file, SECTOR + 1 * 4, (int) END); // fat[1] — directory цела
|
||||
// цепочка Data (head=2): 2→3→100 — сектор за файлом, но в FAT
|
||||
put32(file, SECTOR + 4 * 4, 100);
|
||||
put32(file, SECTOR + 100 * 4, (int) END);
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamTruncated_rejected() {
|
||||
byte[] big = new byte[5000];
|
||||
byte[] file = build(new Spec("Data", big));
|
||||
put32(file, SECTOR + 2 * 4, (int) END); // цепочка из одного сектора
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный поток"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniWithoutRoot_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", "abc".getBytes()));
|
||||
// root: start=END, size=0 → mini stream нет, а поток mini-размера есть
|
||||
int root = SECTOR * 2;
|
||||
put32(file, root + 0x74, (int) END);
|
||||
put32(file, root + 0x78, 0);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("Mini stream"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniChainLoop_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", "abc".getBytes()));
|
||||
put32(file, SECTOR * 3, 0); // miniFat[0] = 0 — цикл
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("MiniFAT"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniBeyondStream_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", new byte[128]));
|
||||
// поток 128 байт (2 mini-сектора), а root объявляет mini stream в 64
|
||||
put32(file, SECTOR * 2 + 0x78, MINI);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("за конец mini stream"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniTruncated_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", new byte[128]));
|
||||
put32(file, SECTOR * 3, (int) END); // цепочка обрывается на первом
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный mini-поток"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badEntries_skipped() {
|
||||
byte[] good = "ok".getBytes();
|
||||
byte[] file = build(new Spec("Good", good));
|
||||
// запись 2: nameLen=0 — пропускается; запись 3: size за файлом — пропускается
|
||||
dirEntry(file, 1, 2, "", 2, 3, 2); // nameLen=2 → имя пустое — пропуск
|
||||
dirEntry(file, 1, 3, "Huge", 2, 3, file.length + 1);
|
||||
Map<String, byte[]> streams = CfbReader.readStreams(file);
|
||||
assertEquals(1, streams.size(), "битые записи не попадают в результат");
|
||||
assertArrayEquals(good, streams.get("Good"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootChainBeyondFile_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", "abc".getBytes()));
|
||||
put32(file, SECTOR * 2 + 0x74, 100); // root start за файлом
|
||||
put32(file, SECTOR * 2 + 0x78, 64);
|
||||
put32(file, SECTOR + 100 * 4, (int) END);
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
private static void put16(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
put16(b, off, v & 0xFFFF);
|
||||
put16(b, off + 2, (v >>> 16) & 0xFFFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link ChpxIndex} ([MS-DOC] §2.4.6.2, §2.9 ChpxFkp): крафтовый
|
||||
* PlcfBteChpx + FKP-страница WordDocument — happy path, пропуски
|
||||
* (bOffset=0, пустой Chpx, деградация за страницу) и отказные ветви.
|
||||
*/
|
||||
class ChpxIndexTest {
|
||||
|
||||
private static final byte[] GRPRL = {0x35, 0x08, 0x01}; // sprmCFBold on
|
||||
|
||||
/** Таблица: aFc [2048, 2100] + pn; FKP-страница pn=2 в wd. */
|
||||
private static byte[] table(int pn) {
|
||||
byte[] t = new byte[12];
|
||||
put32(t, 0, 2048);
|
||||
put32(t, 4, 2100);
|
||||
put32(t, 8, pn);
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* WordDocument с ChpxFkp на странице pn: crun=1, rgfc [2048, 2100],
|
||||
* rgb[0]=bx, Chpx (cb+grpprl) по bx*2; crun-байт = 1.
|
||||
*/
|
||||
private static byte[] wordDocument(int bx, int cb, byte[] grpprl) {
|
||||
byte[] wd = new byte[1536];
|
||||
int page = 2 * 512;
|
||||
put32(wd, page, 2048);
|
||||
put32(wd, page + 4, 2100);
|
||||
wd[page + 8] = (byte) bx;
|
||||
wd[page + 511] = 1; // crun
|
||||
if (bx > 0) {
|
||||
wd[page + bx * 2] = (byte) cb;
|
||||
System.arraycopy(grpprl, 0, wd, page + bx * 2 + 1,
|
||||
Math.min(grpprl.length, cb));
|
||||
}
|
||||
return wd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyBte_defaults() {
|
||||
ChpxIndex idx = ChpxIndex.read(new byte[0], 0, 0, new byte[0]);
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2048));
|
||||
assertEquals(999, idx.rangeEnd(2048, 999));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badBte_rejected() {
|
||||
byte[] t = table(2);
|
||||
byte[] wd = wordDocument(5, 3, GRPRL);
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(t, 0, 10, wd)); // (10-4)%8 != 0
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(t, 0, t.length + 1, wd)); // за таблицей
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageBeyondWordDocument_rejected() {
|
||||
byte[] t = table(100);
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(t, 0, t.length, new byte[1536]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badCrun_rejected() {
|
||||
byte[] wd = wordDocument(5, 3, GRPRL);
|
||||
wd[2 * 512 + 511] = 0;
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(table(2), 0, 12, wd));
|
||||
wd[2 * 512 + 511] = 0x66;
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(table(2), 0, 12, wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroOffsetAndEmptyChpx_skipped() {
|
||||
byte[] wd = wordDocument(0, 0, GRPRL);
|
||||
ChpxIndex idx = ChpxIndex.read(table(2), 0, 12, wd);
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2048), "bOffset=0 — дефолт");
|
||||
|
||||
byte[] cbZero = wordDocument(5, 0, GRPRL);
|
||||
assertArrayEquals(new byte[0],
|
||||
ChpxIndex.read(table(2), 0, 12, cbZero).grpprlFor(2048),
|
||||
"cb=0 — свойств нет");
|
||||
}
|
||||
|
||||
@Test
|
||||
void chpxBeyondPage_skipped() {
|
||||
byte[] wd = wordDocument(250, 200, GRPRL); // chpxOff+1+cb за 512
|
||||
assertArrayEquals(new byte[0],
|
||||
ChpxIndex.read(table(2), 0, 12, wd).grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void happyPath_grpprlAndRangeEnd() {
|
||||
ChpxIndex idx = ChpxIndex.read(table(2), 0, 12, wordDocument(5, 3, GRPRL));
|
||||
assertArrayEquals(GRPRL, idx.grpprlFor(2048));
|
||||
assertArrayEquals(GRPRL, idx.grpprlFor(2099));
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2100), "fc за диапазоном");
|
||||
assertEquals(2100, idx.rangeEnd(2048, Long.MAX_VALUE >>> 1));
|
||||
assertEquals(2060, idx.rangeEnd(2048, 2060), "rangeEnd режется fcLimit");
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
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 org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Мост на синтетическом .doc (крафтовый FIB + Clx + FKP-страницы, упаковка
|
||||
* POIFS): ветви {@code DocxBody}, которых нет в фикстурах заказчика —
|
||||
* полные CHPX/PAPX-свойства, знаки переноса/разрыва, поля в основном
|
||||
* тексте (не fldSimple), TTP-строка таблицы, картинки-пропуски, выбор
|
||||
* 0Table/1Table и отсутствующий табличный поток.
|
||||
*/
|
||||
class DocToDocxFormattingTest {
|
||||
|
||||
private static final int TEXT_FC = 2048;
|
||||
|
||||
private static final String DOCUMENT_XML = "word/document.xml";
|
||||
|
||||
/** Основной текст: форматированный абзац, знаки, U+0001, поле, TTP. */
|
||||
private static final String TEXT = "Bold&<>\r"
|
||||
+ "\t" + (char) 0x0B + (char) 0x0C + (char) 0x1E + (char) 0x1F + (char) 0x02
|
||||
+ "br1\r"
|
||||
+ (char) 1 + (char) 1 + "end\r"
|
||||
+ (char) 0x13 + "PAGE " + (char) 0x14 + "5" + (char) 0x18 + "\r"
|
||||
+ (char) 7 + "\r";
|
||||
|
||||
// --- крафтовый документ -------------------------------------------
|
||||
|
||||
private static byte[] wordDocument() {
|
||||
byte[] wd = new byte[TEXT_FC + TEXT.length() * 2];
|
||||
// FibBase + FibRgLw97
|
||||
put16(wd, 0, 0xA5EC);
|
||||
put16(wd, 2, 0x00C1);
|
||||
put16(wd, 10, 1 << 9); // fWhichTblStm → 1Table
|
||||
put16(wd, 62, 4); // cslw
|
||||
put32(wd, 64, wd.length); // cbMac
|
||||
put32(wd, 76, TEXT.length()); // ccpText
|
||||
put16(wd, 152, 98); // cbRgFcLcb
|
||||
// пары FibRgFcLcb97
|
||||
pair(wd, 6, 0, 20); // PlcfSed
|
||||
pair(wd, 12, 20, 12); // PlcfBteChpx
|
||||
pair(wd, 13, 32, 12); // PlcfBtePapx
|
||||
pair(wd, 15, 44, 110); // SttbfFfn
|
||||
pair(wd, 33, 160, 21); // Clx
|
||||
// текст UTF-16LE
|
||||
byte[] t = TEXT.getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(t, 0, wd, TEXT_FC, t.length);
|
||||
chpxPage(wd);
|
||||
papxPage(wd);
|
||||
return wd;
|
||||
}
|
||||
|
||||
/** ChpxFkp pn=2: ран 1 — полные свойства, ран 3 — cvAuto, ран 5 — picLocation. */
|
||||
private static void chpxPage(byte[] wd) {
|
||||
int page = 2 * 512;
|
||||
int[] rgfc = {TEXT_FC, TEXT_FC + 16, TEXT_FC + 28, TEXT_FC + 34,
|
||||
TEXT_FC + 38, TEXT_FC + 40};
|
||||
for (int i = 0; i < rgfc.length; i++) {
|
||||
put32(wd, page + i * 4, rgfc[i]);
|
||||
}
|
||||
wd[page + 24] = 16; // rgb[0] → chpx по page+32 (за rgfc+rgb)
|
||||
wd[page + 26] = 40; // rgb[2] → page+80 (cvAuto)
|
||||
wd[page + 28] = 44; // rgb[4] → page+88 (picLocation=0)
|
||||
wd[page + 511] = 5; // crun
|
||||
byte[] full = concat(
|
||||
prl(0x0835, 1), prl(0x0836, 1), prl(0x0837, 1), prl(0x2A3E, 1),
|
||||
prl2(0x4A43, 28), prl2(0x4A61, 24), prl2(0x4A4F, 0), prl2(0x4A50, 1),
|
||||
new byte[] {0x70, 0x68, (byte) 0xFF, 0, 0, 0});
|
||||
chpx(wd, page, 16, full);
|
||||
chpx(wd, page, 40, new byte[] {0x70, 0x68, (byte) 0xFF, 0, 0, (byte) 0xFF}); // cvAuto
|
||||
chpx(wd, page, 44, new byte[] {0x03, 0x6A, 0, 0, 0, 0}); // sprmCPicLocation=0
|
||||
}
|
||||
|
||||
private static void chpx(byte[] wd, int page, int bx, byte[] grpprl) {
|
||||
wd[page + bx * 2] = (byte) grpprl.length;
|
||||
System.arraycopy(grpprl, 0, wd, page + bx * 2 + 1, grpprl.length);
|
||||
}
|
||||
|
||||
/** PapxFkp pn=3: 5 абзацев с pPr, шестой (¶) — без диапазона → <w:p/>. */
|
||||
private static void papxPage(byte[] wd) {
|
||||
int page = 3 * 512;
|
||||
int[] rgfc = {TEXT_FC, TEXT_FC + 16, TEXT_FC + 36, TEXT_FC + 48,
|
||||
TEXT_FC + 68, TEXT_FC + 70, TEXT_FC + 72};
|
||||
for (int i = 0; i < rgfc.length; i++) {
|
||||
put32(wd, page + i * 4, rgfc[i]);
|
||||
}
|
||||
int rgbx = page + rgfc.length * 4;
|
||||
int[] bx = {54, 62, 72, 76, 80, 0};
|
||||
for (int i = 0; i < bx.length; i++) {
|
||||
wd[rgbx + i * 13] = (byte) bx[i];
|
||||
}
|
||||
wd[page + 511] = 6; // cpara
|
||||
// p1: center + left 720 + hanging 360 (cb≠0: istd + grpprl, 2cb−1)
|
||||
byte[] g1 = concat(prl(0x2403, 1), prl2(0x845E, 720),
|
||||
new byte[] {0x60, (byte) 0x84, (byte) 0x98, (byte) 0xFE});
|
||||
wd[page + 54 * 2] = 7; // 2·7−1 = 14 = istd(2) + g1(11) + istd… ровно 2cb−3=11
|
||||
System.arraycopy(g1, 0, wd, page + 54 * 2 + 3, g1.length);
|
||||
// p2: pageBreakBefore + right + firstLine 180 (cb=0 → cb', 2cb'−2)
|
||||
byte[] g2 = concat(prl(0x2407, 1), prl(0x2461, 2), prl2(0x845D, 240),
|
||||
prl2(0x8460, 180));
|
||||
wd[page + 62 * 2] = 0;
|
||||
wd[page + 62 * 2 + 1] = 8; // 2·8−2 = 14 = |g2|
|
||||
System.arraycopy(g2, 0, wd, page + 62 * 2 + 4, g2.length);
|
||||
// p3: both; p4: distribute; p5: TTP (cb=3 → grpprl 3 байта с +3)
|
||||
wd[page + 72 * 2] = 3;
|
||||
wd[page + 72 * 2 + 3] = 0x61;
|
||||
wd[page + 72 * 2 + 4] = 0x24;
|
||||
wd[page + 72 * 2 + 5] = 3;
|
||||
wd[page + 76 * 2] = 3;
|
||||
wd[page + 76 * 2 + 3] = 0x61;
|
||||
wd[page + 76 * 2 + 4] = 0x24;
|
||||
wd[page + 76 * 2 + 5] = 4;
|
||||
wd[page + 80 * 2] = 3;
|
||||
wd[page + 80 * 2 + 3] = 0x17; // sprmPFTtp
|
||||
wd[page + 80 * 2 + 4] = 0x24;
|
||||
wd[page + 80 * 2 + 5] = 1;
|
||||
}
|
||||
|
||||
private static byte[] tableStream() {
|
||||
byte[] t = new byte[181];
|
||||
// PlcfSed: aFc [0, ccpText] + SED (fcSepx=0)
|
||||
put32(t, 0, 0);
|
||||
put32(t, 4, TEXT.length());
|
||||
// PlcfBteChpx @20: aFc [TEXT_FC, TEXT_FC+72] + pn=2
|
||||
put32(t, 20, TEXT_FC);
|
||||
put32(t, 24, TEXT_FC + 72);
|
||||
put32(t, 28, 2);
|
||||
// PlcfBtePapx @32: то же, pn=3
|
||||
put32(t, 32, TEXT_FC);
|
||||
put32(t, 36, TEXT_FC + 72);
|
||||
put32(t, 40, 3);
|
||||
// SttbfFfn @44: Arial, T&imes
|
||||
t[44] = 2;
|
||||
t[48] = 51; // cch Arial: 39 + 12
|
||||
byte[] arial = "Arial\0".getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(arial, 0, t, 48 + 40, arial.length);
|
||||
t[48 + 52] = 53; // cch T&imes: 39 + 14
|
||||
byte[] times = "T&imes\0".getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(times, 0, t, 48 + 52 + 40, times.length);
|
||||
// Clx @160: Pcdt, один несжатый кусок
|
||||
t[160] = 0x02;
|
||||
put32(t, 161, 16);
|
||||
put32(t, 165, 0);
|
||||
put32(t, 169, TEXT.length());
|
||||
put32(t, 175, TEXT_FC); // PCD.fc (бит fCompressed = 0)
|
||||
return t;
|
||||
}
|
||||
|
||||
private static byte[] cfb(boolean use1Table, boolean withTable) throws IOException {
|
||||
POIFSFileSystem fs = new POIFSFileSystem();
|
||||
byte[] wd = wordDocument();
|
||||
if (!use1Table) {
|
||||
wd[11] &= ~0x02; // fWhichTblStm (бит 9 u16) → 0Table
|
||||
}
|
||||
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
|
||||
if (withTable) {
|
||||
fs.getRoot().createDocument(use1Table ? "1Table" : "0Table",
|
||||
new ByteArrayInputStream(tableStream()));
|
||||
}
|
||||
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
fs.writeFilesystem(out);
|
||||
fs.close();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static String documentXml(byte[] doc) throws IOException {
|
||||
byte[] docx = DocToDocx.convert(doc);
|
||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||
ZipEntry e;
|
||||
while ((e = zip.getNextEntry()) != null) {
|
||||
if (DOCUMENT_XML.equals(e.getName())) {
|
||||
return new String(zip.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AssertionError("нет document.xml");
|
||||
}
|
||||
|
||||
// --- тесты ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void runProps_fullDirectFormatting() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
assertTrue(xml.contains("<w:b/>"), xml);
|
||||
assertTrue(xml.contains("<w:i/>"), xml);
|
||||
assertTrue(xml.contains("<w:strike/>"), xml);
|
||||
assertTrue(xml.contains("<w:u w:val=\"single\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:sz w:val=\"28\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:szCs w:val=\"24\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:color w:val=\"FF0000\"/>"), xml);
|
||||
assertTrue(xml.contains("w:ascii=\"Arial\" w:hAnsi=\"Arial\""), xml);
|
||||
assertTrue(xml.contains("w:cs=\"T&imes\""), "escapeAttr имени шрифта: " + xml);
|
||||
assertTrue(xml.contains("Bold&<>"), "escape текста: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void paraProps_jcIndentsAndPageBreak() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
assertTrue(xml.contains("<w:jc w:val=\"center\"/>"), xml);
|
||||
assertTrue(xml.contains("w:left=\"720\""), xml);
|
||||
assertTrue(xml.contains("w:hanging=\"360\""), "XAS со знаком: " + xml);
|
||||
assertTrue(xml.contains("<w:pageBreakBefore/>"), xml);
|
||||
assertTrue(xml.contains("<w:jc w:val=\"right\"/>"), xml);
|
||||
assertTrue(xml.contains("w:right=\"240\""), xml);
|
||||
assertTrue(xml.contains("w:firstLine=\"180\""), xml);
|
||||
assertTrue(xml.contains("<w:jc w:val=\"both\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:jc w:val=\"distribute\"/>"), xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void specialMarks_rendered() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
assertTrue(xml.contains("<w:tab/>"), xml);
|
||||
assertTrue(xml.contains("<w:br/>"), xml);
|
||||
assertTrue(xml.contains("<w:br w:type=\"page\"/>"), xml);
|
||||
assertTrue(xml.contains("\u2011"), "неразрывный дефис: " + xml);
|
||||
assertTrue(xml.contains("\u00AD"), "мягкий перенос: " + xml);
|
||||
assertTrue(xml.contains("br1"), "ссылка на сноску пропущена, текст цел: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bodyField_resultVisibleInstructionHidden() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
// fieldsAsSimple=false в основном тексте: инструкция не попадает,
|
||||
// кэшированный результат после разделителя — да
|
||||
assertFalse(xml.contains("PAGE"), "инструкция поля утекла в вывод: " + xml);
|
||||
assertTrue(xml.contains(">5<"), "результат поля потерян: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void embeddedObjectsWithoutPicture_skipped() throws IOException {
|
||||
// U+0001 без sprmCPicLocation и с picLocation на мусорный Data —
|
||||
// ни одной image-части
|
||||
byte[] docx = DocToDocx.convert(cfb(true, true));
|
||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||
ZipEntry e;
|
||||
while ((e = zip.getNextEntry()) != null) {
|
||||
assertFalse(e.getName().startsWith("word/media/"),
|
||||
"битая картинка не должна становиться частью");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ttpRowMark_droppedEmptyParaKept() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
// абзацы: p1..p4 + пустой <w:p/> (последний ¶); TTP-строка (0x07) — не абзац
|
||||
int paras = xml.split("<w:p[ />]", -1).length - 1;
|
||||
assertEquals(5, paras, "TTP-маркер не должен давать абзац: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroTable_usedWhenFlagClear() throws IOException {
|
||||
String xml = documentXml(cfb(false, true));
|
||||
assertTrue(xml.contains("<w:b/>"), "0Table должен читаться так же: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTableStream_rejected() throws IOException {
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> DocToDocx.convert(cfb(true, false)));
|
||||
assertTrue(ex.getMessage().contains("1Table"), ex.getMessage());
|
||||
}
|
||||
|
||||
// --- мелочь ----------------------------------------------------------
|
||||
|
||||
private static byte[] prl(int sprm, int toggle) {
|
||||
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) toggle};
|
||||
}
|
||||
|
||||
private static byte[] prl2(int sprm, int v) {
|
||||
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
int len = 0;
|
||||
for (byte[] p : parts) {
|
||||
len += p.length;
|
||||
}
|
||||
byte[] out = new byte[len];
|
||||
int at = 0;
|
||||
for (byte[] p : parts) {
|
||||
System.arraycopy(p, 0, out, at, p.length);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void pair(byte[] wd, int index, int fc, int lcb) {
|
||||
put32(wd, 154 + index * 8, fc);
|
||||
put32(wd, 154 + index * 8 + 4, lcb);
|
||||
}
|
||||
|
||||
private static void put16(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
put16(b, off, v & 0xFFFF);
|
||||
put16(b, off + 2, (v >>> 16) & 0xFFFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Мост .doc → .docx на фикстурах заказчика (samples/*.doc, POI-продукция)
|
||||
* и синтетических CFB (POIFS).
|
||||
*/
|
||||
class DocToDocxTest {
|
||||
|
||||
private static final String DOCUMENT_ENTRY = "word/document.xml";
|
||||
|
||||
private static byte[] sample(String name) throws IOException {
|
||||
try (InputStream in = DocToDocxTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/" + name)) {
|
||||
assertNotNull(in, "Нет фикстуры: samples/" + name);
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
/** document.xml из конвертированного .docx. */
|
||||
private static String documentXml(byte[] docBytes) throws IOException {
|
||||
byte[] docx = DocToDocx.convert(docBytes);
|
||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zip.getNextEntry()) != null) {
|
||||
if (DOCUMENT_ENTRY.equals(entry.getName())) {
|
||||
return new String(zip.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AssertionError("в конвертате нет word/document.xml");
|
||||
}
|
||||
|
||||
/** CFB-контейнер с указанными потоками (для негативных случаев). */
|
||||
private static byte[] cfbWith(String... streamNames) throws IOException {
|
||||
try (POIFSFileSystem fs = new POIFSFileSystem(); ByteArrayOutputStream out =
|
||||
new ByteArrayOutputStream()) {
|
||||
for (String name : streamNames) {
|
||||
fs.createDocument(new ByteArrayInputStream(new byte[64]), name);
|
||||
}
|
||||
fs.writeFilesystem(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruFixture_runsCarryDirectFormatting() throws IOException {
|
||||
String xml = documentXml(sample("ru-plain.doc"));
|
||||
assertTrue(xml.contains("Тестовый документ (русский)"), "нет заголовка");
|
||||
assertTrue(xml.contains("<w:b/>"), "жирное начертание потеряно");
|
||||
assertTrue(xml.contains("<w:i/>"), "курсив потерян");
|
||||
assertTrue(xml.contains("<w:sz w:val=\"36\"/>"), "размер заголовка потерян");
|
||||
assertTrue(xml.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"), "алфавит потерян");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatsFixture_propsTabsAndCells() throws IOException {
|
||||
String xml = documentXml(sample("doc-formats.doc"));
|
||||
assertTrue(xml.contains("<w:jc w:val=\"center\"/>"), "центрирование потеряно");
|
||||
assertTrue(xml.contains("<w:jc w:val=\"right\"/>"), "правое выравнивание потеряно");
|
||||
assertTrue(xml.contains("<w:jc w:val=\"both\"/>"), "растягивание потеряно");
|
||||
assertTrue(xml.contains("<w:ind w:left=\"1440\" w:firstLine=\"720\"/>"),
|
||||
"отступы потеряны: " + xml.substring(0, Math.min(xml.length(), 2000)));
|
||||
assertTrue(xml.contains("<w:tab/>"), "табуляция потеряна");
|
||||
assertTrue(xml.contains("<w:pageBreakBefore/>"), "перенос страницы потерян");
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
assertTrue(xml.contains("Ячейка " + i), "ячейка " + i + " потеряна");
|
||||
}
|
||||
assertTrue(xml.indexOf("Ячейка 1") < xml.indexOf("Ячейка 2"), "порядок ячеек сбился");
|
||||
// конец строки таблицы (пустой абзац с 0x07+sprmPFTtp) в вывод не попадает
|
||||
assertTrue(xml.indexOf("Ячейка 2") < xml.indexOf("Ячейка 3"), "между строками мусор");
|
||||
assertTrue(!xml.contains("<w:p/>"), "пустые абзацы-концы строк не выброшены");
|
||||
}
|
||||
|
||||
@Test
|
||||
void encrypted_rejected() throws IOException {
|
||||
byte[] cfb = cfbWith("EncryptedPackage", "WordDocument");
|
||||
ValidationException e = assertThrows(ValidationException.class,
|
||||
() -> DocToDocx.convert(cfb));
|
||||
assertTrue(e.getMessage().contains("зашифрован"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cfbWithoutWordDocument_rejected() throws IOException {
|
||||
byte[] cfb = cfbWith("Workbook");
|
||||
ValidationException e = assertThrows(ValidationException.class,
|
||||
() -> DocToDocx.convert(cfb));
|
||||
assertTrue(e.getMessage().contains("не похоже"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncated_rejected() throws IOException {
|
||||
byte[] full = sample("ru-plain.doc");
|
||||
byte[] cut = Arrays.copyOf(full, 2048);
|
||||
assertThrows(ValidationException.class, () -> DocToDocx.convert(cut));
|
||||
}
|
||||
|
||||
@Test
|
||||
void countPages_breaksBeatStaleCache() throws IOException {
|
||||
// too-many-pages.doc: 150 разрывов 0x0C → 151; кэш PageCount=150 не выше
|
||||
assertEquals(151, DocToDocx.countPages(sample("too-many-pages.doc")));
|
||||
// page-numbers.doc: кэш PageCount=3 устарел, в тексте 3 разрыва 0x0C → 4
|
||||
// (каждый 0x0C — реальный разрыв, §2.8.26; нижняя оценка консервативна)
|
||||
assertEquals(4, DocToDocx.countPages(sample("page-numbers.doc")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageBreakBefore_countedWithoutCache() throws IOException {
|
||||
// фикстура без достоверного PageCount — «2 страницы» обязана дать
|
||||
// отсчёт по чистому .doc (абзац с sprmPFPageBreakBefore), не кэш
|
||||
assertEquals(2, DocToDocx.countPages(sample("doc-formats.doc")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link FibHeader} ([MS-DOC] §2.5): крафтовый WordDocument-поток —
|
||||
* happy path и все отказные ветви (битый wIdent, старая версия, шифрование,
|
||||
* обрезанный FIB, отрицательный ccpText, устаревший cbRgFcLcb).
|
||||
*/
|
||||
class FibHeaderTest {
|
||||
|
||||
/** Минимальный валидный FIB: 98 пар, 1Table, ccpText=10. */
|
||||
private static byte[] fib(int flags) {
|
||||
byte[] wd = new byte[154 + 98 * 8];
|
||||
put16(wd, 0, 0xA5EC); // wIdent
|
||||
put16(wd, 2, 0x00C1); // nFib = Word 97
|
||||
put16(wd, 10, flags); // grpprl FIB
|
||||
put16(wd, 62, 4); // cslw
|
||||
put32(wd, 76, 10); // ccpText
|
||||
put32(wd, 152, 98); // cbRgFcLcb
|
||||
return wd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void valid_readsFields() {
|
||||
FibHeader f = FibHeader.read(fib(1 << 9)); // fWhichTblStm=1
|
||||
assertEquals(10, f.ccpText());
|
||||
assertTrue(f.use1Table());
|
||||
FibHeader f0 = FibHeader.read(fib(0));
|
||||
assertFalse(f0.use1Table());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooShort_rejected() {
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(new byte[153]));
|
||||
assertTrue(ex.getMessage().contains("не похоже"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badWIdent_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 0, 0x1234);
|
||||
assertThrows(ValidationException.class, () -> FibHeader.read(wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldVersion_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 2, 0x00BF); // Word 95
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Word 97"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void encrypted_rejected() {
|
||||
byte[] wd = fib(1 << 8); // fEncrypted
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("зашифрован"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void smallCslw_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 62, 3);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный FIB"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeCcpText_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put32(wd, 76, -1);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Отрицательная длина"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleFib_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 152, 33); // cbRgFcLcb ≤ индекса fcClx — нет нужных пар
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Устаревшая структура"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatedPairs_rejected() {
|
||||
byte[] full = fib(1 << 9);
|
||||
byte[] wd = new byte[300]; // пары до индекса 33 не влезают
|
||||
System.arraycopy(full, 0, wd, 0, 300);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный FIB"), ex.getMessage());
|
||||
}
|
||||
|
||||
private static void put16(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
put16(b, off, v & 0xFFFF);
|
||||
put16(b, off + 2, (v >>> 16) & 0xFFFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/** Юниты {@link FontTable} ([MS-DOC] §2.9, SttbfFfn/FFN). */
|
||||
class FontTableTest {
|
||||
|
||||
/** SttbfFfn: cData(2)+cbExtra(2) + (cch + FFN(39)+имя) × n. */
|
||||
private static byte[] sttbf(String... names) {
|
||||
int size = 4;
|
||||
for (String n : names) {
|
||||
size += 1 + 39 + (n.length() + 1) * 2;
|
||||
}
|
||||
byte[] t = new byte[size];
|
||||
t[0] = (byte) names.length;
|
||||
int p = 4;
|
||||
for (String n : names) {
|
||||
byte[] name = (n + "\0").getBytes(StandardCharsets.UTF_16LE);
|
||||
t[p] = (byte) (39 + name.length);
|
||||
p += 40; // cch + FFN-тело до имени
|
||||
System.arraycopy(name, 0, t, p, name.length);
|
||||
p += name.length;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyLcb_emptyTable() {
|
||||
FontTable ft = FontTable.read(new byte[0], 0, 0);
|
||||
assertNull(ft.font(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outOfRange_rejected() {
|
||||
byte[] t = sttbf("Arial");
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, t.length + 1));
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 1, t.length));
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatedEntry_rejected() {
|
||||
byte[] cut = new byte[4]; // cData=1, но элемента нет вовсе
|
||||
cut[0] = 1;
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(cut, 0, cut.length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortFfn_rejected() {
|
||||
byte[] t = sttbf("Arial");
|
||||
t[4] = 38; // cch < 39
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, t.length));
|
||||
t[4] = 120; // cch за конец буфера
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, t.length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void happyPath_namesByIndex() {
|
||||
byte[] t = sttbf("Arial", "Times New Roman");
|
||||
FontTable ft = FontTable.read(t, 0, t.length);
|
||||
assertEquals("Arial", ft.font(0));
|
||||
assertEquals("Times New Roman", ft.font(1));
|
||||
assertNull(ft.font(2));
|
||||
assertNull(ft.font(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameBeyondCch_truncatedAtNul() {
|
||||
// имя длиннее cch-хвоста не читается: обрезаем по \0 в пределах cch
|
||||
byte[] t = sttbf("Arial");
|
||||
assertTrue(FontTable.read(t, 0, t.length).font(0).startsWith("Arial"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Юниты {@link Grpprl} ([MS-DOC] §2.6, §3 Figure 33): обход Prl всех форм. */
|
||||
class GrpprlTest {
|
||||
|
||||
@Test
|
||||
void scan_allOperandForms() {
|
||||
List<Integer> seen = new ArrayList<>();
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
byte[] buf = {
|
||||
0x35, 0x08, 0x01, // toggle (spra 0) — 1 байт
|
||||
0x3E, 0x2A, 0x01, // 1-байтовый (spra 1)
|
||||
0x43, 0x4A, 0x16, 0x00, // 2-байтовый (spra 2)
|
||||
0x03, 0x6A, 0x01, 0x00, 0x00, 0x00, // 4-байтовый (spra 3)
|
||||
(byte) 0x01, (byte) 0xE0, 0x0A, 0x00, 0x00, // 3-байтовый (spra 7)
|
||||
0x00, // хвост 1 байт — обрыв
|
||||
};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> {
|
||||
seen.add(sprm);
|
||||
sizes.add(len);
|
||||
});
|
||||
assertEquals(List.of(0x0835, 0x2A3E, 0x4A43, 0x6A03, 0xE001), seen);
|
||||
assertEquals(List.of(1, 1, 2, 4, 3), sizes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scan_variableOperand() {
|
||||
// spra 6 (старшие биты 110): первый байт операнда — длина остального
|
||||
byte[] buf = {0x10, (byte) 0xC0, 0x02, (byte) 0xAA, (byte) 0xBB};
|
||||
int[] got = {-1};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> {
|
||||
got[0] = len;
|
||||
assertEquals(0xC010, sprm);
|
||||
});
|
||||
assertEquals(3, got[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scan_truncatedOperand_stops() {
|
||||
byte[] buf = {0x43, 0x4A, 0x16}; // 2-байтовый операнд не влезает
|
||||
int[] count = {0};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||
assertEquals(0, count[0], "битый хвост — свойства не применяются");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scan_variableWithoutLengthByte_stops() {
|
||||
byte[] buf = {0x10, (byte) 0xC0}; // spra 6, а байта длины нет
|
||||
int[] count = {0};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||
assertEquals(0, count[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void operandInt_widths() {
|
||||
byte[] buf = {0x34, 0x12, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};
|
||||
assertEquals(0x1234, Grpprl.operandInt(buf, 0, 2));
|
||||
assertEquals(0xCDAB1234, Grpprl.operandInt(buf, 0, 5), "длиннее 4 — обрезается");
|
||||
}
|
||||
|
||||
@Test
|
||||
void toggleOn_parity() {
|
||||
assertTrue(Grpprl.toggleOn(new byte[] {1}, 0));
|
||||
assertFalse(Grpprl.toggleOn(new byte[] {2}, 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/** Юниты {@link Headers} ([MS-DOC] §2.8.22, §2.4.4). */
|
||||
class HeadersTest {
|
||||
|
||||
/** aCP: 6 разделителей + 6 историй секции 0 + хвост (13 значений). */
|
||||
private static byte[] plcf(int... cps) {
|
||||
byte[] t = new byte[cps.length * 4];
|
||||
for (int i = 0; i < cps.length; i++) {
|
||||
put32(t, i * 4, cps[i]);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyPlcf_noStories() {
|
||||
Headers h = Headers.read(new byte[0], 0, 0, 100);
|
||||
assertFalse(h.oddHeader(0).hasContent());
|
||||
assertFalse(h.oddFooter(0).hasContent());
|
||||
assertEquals(0, h.oddHeader(0).cpStart());
|
||||
}
|
||||
|
||||
@Test
|
||||
void outOfRange_rejected() {
|
||||
byte[] t = plcf(0, 1);
|
||||
assertThrows(ValidationException.class, () -> Headers.read(t, 0, 12, 0));
|
||||
assertThrows(ValidationException.class, () -> Headers.read(t, 0, 6, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decreasingAcp_rejected() {
|
||||
assertThrows(ValidationException.class,
|
||||
() -> Headers.read(plcf(0, 5, 3), 0, 12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stories_absoluteCpAndGuards() {
|
||||
int[] cps = new int[13];
|
||||
for (int i = 0; i < 13; i++) {
|
||||
cps[i] = 2 * i;
|
||||
}
|
||||
byte[] t = plcf(cps);
|
||||
Headers h = Headers.read(t, 0, t.length, 1000); // baseCp = ccpText+ccpFtn
|
||||
// история 7 = odd header секции 0: [1000+14, 1000+16)
|
||||
Headers.Story hdr = h.oddHeader(0);
|
||||
assertEquals(1014, hdr.cpStart());
|
||||
assertEquals(1016, hdr.cpEnd());
|
||||
assertTrue(hdr.hasContent());
|
||||
assertEquals(1015, hdr.contentEnd(), "последний ¶ — guard, вне контента");
|
||||
// история 9 = odd footer: [1018, 1020)
|
||||
Headers.Story ftr = h.oddFooter(0);
|
||||
assertEquals(1018, ftr.cpStart());
|
||||
assertEquals(1019, ftr.contentEnd());
|
||||
assertTrue(ftr.hasContent());
|
||||
// одна guard-¶ — содержимого нет
|
||||
assertFalse(new Headers.Story(5, 6).hasContent());
|
||||
// секции 1 нет (aCp короче) → пустая история
|
||||
assertEquals(0, h.oddHeader(1).cpEnd());
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Юниты {@link OfficeArt}: крафтовые PICF+BLIP-области ([MS-DOC] §2.9.192,
|
||||
* [MS-ODRAW] §2.2.23–.31) — отбор по сигнатуре, UID-чётность, размеры,
|
||||
* DIB→PNG, деградация на метафайлах и мусоре. Фикстуры-документы
|
||||
* (samples/ru-table-image.doc и др.) покрывает WordPdfConverterTest.
|
||||
*/
|
||||
class OfficeArtTest {
|
||||
|
||||
private static final byte[] PNG_TINY = pngBytes();
|
||||
|
||||
@Test
|
||||
void pngBlip_extractedWithScaledSize() {
|
||||
byte[] region = region(picf(1800, 900, 1000, 1000),
|
||||
blip(0x6E0, 0xF01E, 16, PNG_TINY));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic);
|
||||
assertEquals("png", pic.extension());
|
||||
assertEquals("image/png", pic.contentType());
|
||||
assertArrayEquals(PNG_TINY, pic.data());
|
||||
assertEquals(1800 * 635, pic.cxEmu());
|
||||
assertEquals(900 * 635, pic.cyEmu());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oddInstance_secondUidSkipped() {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x6E1, 0xF01E, 32, PNG_TINY));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic, "нечётный recInstance — два UID, данные после 32+1");
|
||||
assertArrayEquals(PNG_TINY, pic.data());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jpegBlip_extracted() {
|
||||
byte[] jpeg = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 1, 2, 3};
|
||||
byte[] region = region(picf(100, 100, 1000, 1000), blip(0x46B, 0xF01D, 16, jpeg));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic);
|
||||
assertEquals("jpg", pic.extension());
|
||||
assertEquals("image/jpeg", pic.contentType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jpegAltRecType_accepted() {
|
||||
// [MS-ODRAW] A.1: 0xF02A трактуется как 0xF01D
|
||||
byte[] jpeg = {(byte) 0xFF, (byte) 0xD8, 1, 2};
|
||||
byte[] region = region(picf(100, 100, 1000, 1000), blip(0x46B, 0xF02A, 16, jpeg));
|
||||
assertNotNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void metafileBlips_skipped() {
|
||||
for (int type : new int[] {0xF01A, 0xF01B, 0xF01C}) {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x2FC, type, 16, PNG_TINY));
|
||||
assertNull(OfficeArt.read(region, 0),
|
||||
"метафайл 0x" + Integer.toHexString(type) + " не рендерится");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pngSignatureRequired() {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x6E0, 0xF01E, 16, new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}));
|
||||
assertNull(OfficeArt.read(region, 0), "recType=PNG без сигнатуры — ложное срабатывание");
|
||||
}
|
||||
|
||||
@Test
|
||||
void badPicfHeader_rejected() {
|
||||
byte[] good = region(picf(100, 100, 1000, 1000), blip(0x6E0, 0xF01E, 16, PNG_TINY));
|
||||
byte[] badCb = good.clone();
|
||||
badCb[4] = 0x40; // cbHeader ≠ 0x44 (NilPICFAndBinData — OLE-бинарник)
|
||||
assertNull(OfficeArt.read(badCb, 0));
|
||||
|
||||
byte[] badLcb = good.clone();
|
||||
put32(badLcb, 0, 40); // lcb < PICF_SIZE
|
||||
assertNull(OfficeArt.read(badLcb, 0));
|
||||
|
||||
assertNull(OfficeArt.read(good, -1), "отрицательный picLocation");
|
||||
assertNull(OfficeArt.read(good, good.length - 10), "PICF не влезает в поток");
|
||||
|
||||
byte[] truncated = new byte[good.length - 1];
|
||||
System.arraycopy(good, 0, truncated, 0, truncated.length);
|
||||
assertNull(OfficeArt.read(truncated, 0), "off + lcb за концом потока");
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageRegion_null() {
|
||||
byte[] region = new byte[256];
|
||||
for (int i = 0; i < region.length; i++) {
|
||||
region[i] = (byte) (i * 31 + 7);
|
||||
}
|
||||
put32(region, 0, region.length);
|
||||
put16(region, 4, 0x44);
|
||||
assertNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shapefilePrefix_skipped() {
|
||||
// mm=0x0066: после PICF идёт cchPicName + stPicName ([MS-DOC] §2.9.190)
|
||||
byte[] picf = picf(100, 100, 1000, 1000);
|
||||
put16(picf, 6, 0x0066);
|
||||
byte[] name = {3, 'b', 'm', 'p'};
|
||||
byte[] blip = blip(0x6E0, 0xF01E, 16, PNG_TINY);
|
||||
byte[] region = new byte[picf.length + name.length + blip.length];
|
||||
System.arraycopy(picf, 0, region, 0, picf.length);
|
||||
System.arraycopy(name, 0, region, picf.length, name.length);
|
||||
System.arraycopy(blip, 0, region, picf.length + name.length, blip.length);
|
||||
put32(region, 0, region.length);
|
||||
assertNotNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pngSizeFallsBackToIhdr() {
|
||||
// dxaGoal=0 → размер из IHDR @96 dpi: 100×50 px → 1500×750 twips
|
||||
byte[] region = region(picf(0, 0, 1000, 1000), blip(0x6E0, 0xF01E, 16, PNG_TINY));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic);
|
||||
assertEquals(1500 * 635, pic.cxEmu());
|
||||
assertEquals(750 * 635, pic.cyEmu());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dibReencodedToPng() {
|
||||
byte[] dib = dib24();
|
||||
byte[] region = region(picf(100, 100, 1000, 1000), blip(0x6E4, 0xF01F, 16, dib));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic, "DIB обязан перекодироваться в PNG");
|
||||
assertEquals("png", pic.extension());
|
||||
assertEquals((byte) 0x89, pic.data()[0]);
|
||||
assertEquals('P', pic.data()[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatedDib_null() {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x6E4, 0xF01F, 16, new byte[20]));
|
||||
assertNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blipBeyondLcb_rejected() {
|
||||
byte[] picf = picf(100, 100, 1000, 1000);
|
||||
byte[] blip = blip(0x6E0, 0xF01E, 16, PNG_TINY);
|
||||
byte[] region = new byte[picf.length + blip.length];
|
||||
System.arraycopy(picf, 0, region, 0, picf.length);
|
||||
System.arraycopy(blip, 0, region, picf.length, blip.length);
|
||||
put32(region, 0, picf.length + 4); // lcb обрезает BLIP-область
|
||||
assertNull(OfficeArt.read(region, 0), "cb за пределами lcb — не картинка");
|
||||
}
|
||||
|
||||
// --- конструкторы крафтовых областей -------------------------------
|
||||
|
||||
/** PICF (68 байт) с заданными dxaGoal/dyaGoal/mx/my. */
|
||||
private static byte[] picf(int dxaGoal, int dyaGoal, int mx, int my) {
|
||||
byte[] picf = new byte[68];
|
||||
put16(picf, 4, 0x44);
|
||||
put16(picf, 0x1C, dxaGoal);
|
||||
put16(picf, 0x1E, dyaGoal);
|
||||
put16(picf, 0x20, mx);
|
||||
put16(picf, 0x22, my);
|
||||
return picf;
|
||||
}
|
||||
|
||||
/** OfficeArtRecord: verInstance/type/cb + uid(16|32) + tag + данные. */
|
||||
private static byte[] blip(int verInstance, int type, int uidSize, byte[] data) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(8 + uidSize + 1 + data.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buf.putShort((short) verInstance);
|
||||
buf.putShort((short) type);
|
||||
buf.putInt(uidSize + 1 + data.length);
|
||||
buf.position(8 + uidSize);
|
||||
buf.put((byte) 0xFF); // tag
|
||||
buf.put(data);
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
/** PICF + записи, lcb = вся область. */
|
||||
private static byte[] region(byte[] picf, byte[]... records) {
|
||||
int len = picf.length;
|
||||
for (byte[] r : records) {
|
||||
len += r.length;
|
||||
}
|
||||
byte[] out = new byte[len];
|
||||
System.arraycopy(picf, 0, out, 0, picf.length);
|
||||
int at = picf.length;
|
||||
for (byte[] r : records) {
|
||||
System.arraycopy(r, 0, out, at, r.length);
|
||||
at += r.length;
|
||||
}
|
||||
put32(out, 0, len);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Минимальный PNG 100×50 (сигнатура + IHDR + усечённое тело). */
|
||||
private static byte[] pngBytes() {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
byte[] sig = {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
out.writeBytes(sig);
|
||||
ByteBuffer ihdr = ByteBuffer.allocate(21).order(ByteOrder.BIG_ENDIAN);
|
||||
ihdr.putInt(13).put(new byte[] {'I', 'H', 'D', 'R'})
|
||||
.putInt(100).putInt(50).put((byte) 8).put((byte) 2)
|
||||
.put((byte) 0).put((byte) 0).put((byte) 0);
|
||||
out.writeBytes(ihdr.array());
|
||||
out.writeBytes(new byte[8]); // хвост: pngDxa читает IHDR до +24
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/** DIB 24 bpp 2×2 (BITMAPINFOHEADER + 2 ряда по 8 байт). */
|
||||
private static byte[] dib24() {
|
||||
ByteBuffer buf = ByteBuffer.allocate(40 + 16).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buf.putInt(40).putInt(2).putInt(2).putShort((short) 1).putShort((short) 24)
|
||||
.putInt(0).putInt(0).putInt(0).putInt(0).putInt(0).putInt(0);
|
||||
for (int i = 0; i < 16; i++) {
|
||||
buf.put((byte) (i * 40));
|
||||
}
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
private static void put16(byte[] data, int off, int value) {
|
||||
data[off] = (byte) value;
|
||||
data[off + 1] = (byte) (value >>> 8);
|
||||
}
|
||||
|
||||
private static void put32(byte[] data, int off, int value) {
|
||||
data[off] = (byte) value;
|
||||
data[off + 1] = (byte) (value >>> 8);
|
||||
data[off + 2] = (byte) (value >>> 16);
|
||||
data[off + 3] = (byte) (value >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link PapxIndex} ([MS-DOC] §2.4.6.1, §2.9.16/.175): крафтовый
|
||||
* PlcfBtePapx + PapxFkp — обе формы PapxInFkp (cb≠0 и cb=0→cb'), пропуски
|
||||
* и {@code countPageBreakBefore}.
|
||||
*/
|
||||
class PapxIndexTest {
|
||||
|
||||
/** sprmPFPageBreakBefore=0x2407 toggle, on. */
|
||||
private static final byte[] GRPRL_PB = {0x07, 0x24, 0x01};
|
||||
|
||||
private static byte[] table(int pn) {
|
||||
byte[] t = new byte[12];
|
||||
put32(t, 0, 2048);
|
||||
put32(t, 4, 2100);
|
||||
put32(t, 8, pn);
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* WordDocument с PapxFkp на странице pn: cpara=1, rgfc [2048, 2100],
|
||||
* BxPap.bOffset=bx; PapxInFkp: cb≠0 → istd(2)+grpprl (2cb−1 всего),
|
||||
* cb=0 → cb'-байт и 2cb' всего.
|
||||
*/
|
||||
private static byte[] wordDocument(int bx, boolean shortForm, int cb,
|
||||
byte[] grpprl) {
|
||||
byte[] wd = new byte[1536];
|
||||
int page = 2 * 512;
|
||||
put32(wd, page, 2048);
|
||||
put32(wd, page + 4, 2100);
|
||||
wd[page + 8] = (byte) bx; // rgbx[0].bOffset (BxPap 13 байт, первый)
|
||||
wd[page + 511] = 1; // cpara
|
||||
int infkp = page + bx * 2;
|
||||
if (shortForm) { // cb=0: следующий байт — cb'
|
||||
wd[infkp] = 0;
|
||||
wd[infkp + 1] = (byte) cb;
|
||||
wd[infkp + 2] = 0; // istd
|
||||
wd[infkp + 3] = 0;
|
||||
System.arraycopy(grpprl, 0, wd, infkp + 4, grpprl.length);
|
||||
} else {
|
||||
wd[infkp] = (byte) cb;
|
||||
wd[infkp + 1] = 0; // istd
|
||||
wd[infkp + 2] = 0;
|
||||
System.arraycopy(grpprl, 0, wd, infkp + 3, grpprl.length);
|
||||
}
|
||||
return wd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyBte_defaults() {
|
||||
PapxIndex idx = PapxIndex.read(new byte[0], 0, 0, new byte[0]);
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2048));
|
||||
assertEquals(0, idx.countPageBreakBefore());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badBte_rejected() {
|
||||
byte[] t = table(2);
|
||||
byte[] wd = wordDocument(11, false, 3, GRPRL_PB);
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(t, 0, 11, wd));
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(t, 0, 13, wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageBeyondWordDocument_rejected() {
|
||||
assertThrows(ValidationException.class,
|
||||
() -> PapxIndex.read(table(100), 0, 12, new byte[1536]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badCpara_rejected() {
|
||||
byte[] wd = wordDocument(11, false, 3, GRPRL_PB);
|
||||
wd[2 * 512 + 511] = 0;
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(table(2), 0, 12, wd));
|
||||
wd[2 * 512 + 511] = 0x61;
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(table(2), 0, 12, wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void longForm_extractsGrpprl() {
|
||||
// cb=3 → stdSize=5 = istd(2)+grpprl(3)
|
||||
PapxIndex idx = PapxIndex.read(table(2), 0, 12, wordDocument(11, false, 3, GRPRL_PB));
|
||||
assertArrayEquals(GRPRL_PB, idx.grpprlFor(2048));
|
||||
assertEquals(1, idx.countPageBreakBefore());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortForm_extractsGrpprl() {
|
||||
// cb=0, cb'=3 → stdSize=6 = istd(2)+grpprl(4)… берём grpprl 4 байта
|
||||
byte[] grpprl = {0x07, 0x24, 0x01, 0x00};
|
||||
PapxIndex idx = PapxIndex.read(table(2), 0, 12, wordDocument(11, true, 3, grpprl));
|
||||
assertArrayEquals(grpprl, idx.grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroOffsetAndTinyStd_skipped() {
|
||||
assertArrayEquals(new byte[0],
|
||||
PapxIndex.read(table(2), 0, 12, wordDocument(0, false, 3, GRPRL_PB))
|
||||
.grpprlFor(2048), "bOffset=0 — дефолт");
|
||||
// cb=1 → stdSize=1 → grpprlLen=-1 — слишком мелко, пропуск
|
||||
assertArrayEquals(new byte[0],
|
||||
PapxIndex.read(table(2), 0, 12, wordDocument(11, false, 1, GRPRL_PB))
|
||||
.grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stdBeyondPage_skipped() {
|
||||
// bx=250: infkp=page+500, std за границу 512-байтовой страницы
|
||||
assertArrayEquals(new byte[0],
|
||||
PapxIndex.read(table(2), 0, 12, wordDocument(250, false, 60, GRPRL_PB))
|
||||
.grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void countPageBreakBefore_countsOnlyOn() {
|
||||
byte[] wd = wordDocument(11, false, 3, GRPRL_PB);
|
||||
wd[2 * 512 + 27] = 0; // toggle off (grpprl по infkp+3=+25, operand +2)
|
||||
assertEquals(0, PapxIndex.read(table(2), 0, 12, wd).countPageBreakBefore());
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты guard'а {@link PieceTable}: FC-диапазон куска обязан лежать внутри
|
||||
* WordDocument-потока ([MS-DOC] §2.9.177) — иначе charAt/fcOf читали бы за
|
||||
* массивом (IOOBE вместо 400).
|
||||
*/
|
||||
class PieceTableTest {
|
||||
|
||||
/** Clx = Pcdt с одним Pcd: aCp=[0, cpEnd], fc с флагом сжатия. */
|
||||
private static byte[] clxOnePiece(int cpEnd, long fc, boolean compressed) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(0x02); // clxt Pcdt
|
||||
out.write(le32(4 + 12)); // lcb PlcPcd: 2 aCP + 1 Pcd
|
||||
out.write(le32(0));
|
||||
out.write(le32(cpEnd));
|
||||
out.write(new byte[] {0, 0}); // Pcd.flags
|
||||
long fcw = (fc & 0x3FFF_FFFFL) | (compressed ? 0x4000_0000L : 0);
|
||||
out.write(le32((int) fcw));
|
||||
out.write(new byte[] {0, 0}); // Pcd.prm
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] le32(int v) {
|
||||
return new byte[] {(byte) v, (byte) (v >>> 8), (byte) (v >>> 16), (byte) (v >>> 24)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncompressedPieceBeyondWordDocument_rejected() throws Exception {
|
||||
byte[] table = clxOnePiece(10, 0, false); // 10 CP × 2 байта = 20
|
||||
byte[] wordDocument = new byte[8];
|
||||
ValidationException e = assertThrows(ValidationException.class,
|
||||
() -> PieceTable.read(table, 0, table.length, wordDocument));
|
||||
assertTrue(e.getMessage().contains("WordDocument"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void compressedPieceBeyondWordDocument_rejected() throws Exception {
|
||||
byte[] table = clxOnePiece(10, 2 * 8, true); // сжатый: fc/2=8, span=10 > 8
|
||||
byte[] wordDocument = new byte[8];
|
||||
assertThrows(ValidationException.class,
|
||||
() -> PieceTable.read(table, 0, table.length, wordDocument));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pieceWithinWordDocument_reads() throws Exception {
|
||||
byte[] table = clxOnePiece(2, 0, false);
|
||||
byte[] wordDocument = {'H', 0, 'i', 0};
|
||||
PieceTable pt = PieceTable.read(table, 0, table.length, wordDocument);
|
||||
assertEquals('H', pt.charAt(0));
|
||||
assertEquals('i', pt.charAt(1));
|
||||
assertEquals(2, pt.fcOf(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link Sections} ([MS-DOC] §2.6.3, PlcfSed/Sepx): геометрия
|
||||
* последней секции, continuous-оценки предыдущих, пропуски битых Sepx.
|
||||
*/
|
||||
class SectionsTest {
|
||||
|
||||
/** PlcfSed из n секций; fcSepx[i] — по wordDocument-адресам. */
|
||||
private static byte[] plcfSed(int... fcSepxs) {
|
||||
int n = fcSepxs.length;
|
||||
byte[] t = new byte[(n + 1) * 4 + n * 12]; // aFc(n+1) + SED(n×12)
|
||||
for (int i = 0; i <= n; i++) {
|
||||
put32(t, i * 4, i * 100);
|
||||
}
|
||||
int sedBase = (n + 1) * 4;
|
||||
for (int i = 0; i < n; i++) {
|
||||
put32(t, sedBase + i * 12 + 2, fcSepxs[i]);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Sepx в wordDocument: cb(2) + grpprl. */
|
||||
private static void sepx(byte[] wd, int fc, byte[] grpprl) {
|
||||
wd[fc] = (byte) grpprl.length;
|
||||
wd[fc + 1] = 0;
|
||||
System.arraycopy(grpprl, 0, wd, fc + 2, grpprl.length);
|
||||
}
|
||||
|
||||
/** Prl: sprm LE + 2-байтовый операнд. */
|
||||
private static byte[] prl2(int sprm, int v) {
|
||||
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptySed_defaults() {
|
||||
Sections s = Sections.read(new byte[0], 0, 0, new byte[0]);
|
||||
assertEquals(12240, s.pageWidth());
|
||||
assertEquals(15840, s.pageHeight());
|
||||
assertEquals(1440, s.marginLeft());
|
||||
assertEquals(720, s.header());
|
||||
assertEquals(0, s.continuousSectionEnds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badSed_rejected() {
|
||||
byte[] t = plcfSed(0);
|
||||
assertThrows(ValidationException.class, () -> Sections.read(t, 0, 21, new byte[0]));
|
||||
assertThrows(ValidationException.class, () -> Sections.read(t, 0, t.length + 1, new byte[0]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroAndBrokenSepx_skipped() {
|
||||
byte[] wd = new byte[4096];
|
||||
// fcSepx=0 — нет разрыва; fcSepx у конца wd (4095+2 > 4096) — пропуск
|
||||
Sections s = Sections.read(plcfSed(0, 4095), 0, plcfSed(0, 4095).length, wd);
|
||||
assertEquals(12240, s.pageWidth());
|
||||
// cb=0
|
||||
byte[] wd2 = new byte[4096];
|
||||
wd2[64] = 0;
|
||||
Sections s2 = Sections.read(plcfSed(64), 0, plcfSed(64).length, wd2);
|
||||
assertEquals(12240, s2.pageWidth());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastSection_geometryApplied() {
|
||||
byte[] wd = new byte[4096];
|
||||
byte[] gpr = concat(prl2(Grpprl.SPRM_S_XA_PAGE, 16838),
|
||||
prl2(Grpprl.SPRM_S_YA_PAGE, 11906),
|
||||
prl2(Grpprl.SPRM_S_DXA_LEFT, 1080),
|
||||
prl2(Grpprl.SPRM_S_DXA_RIGHT, 1081),
|
||||
prl2(Grpprl.SPRM_S_DYA_TOP, 1440),
|
||||
prl2(Grpprl.SPRM_S_DYA_BOTTOM, 1441),
|
||||
prl2(Grpprl.SPRM_S_DYA_HDR_TOP, 850),
|
||||
prl2(Grpprl.SPRM_S_DYA_HDR_BOTTOM, 992));
|
||||
sepx(wd, 64, gpr);
|
||||
byte[] t = plcfSed(64);
|
||||
Sections s = Sections.read(t, 0, t.length, wd);
|
||||
assertEquals(16838, s.pageWidth());
|
||||
assertEquals(11906, s.pageHeight());
|
||||
assertEquals(1080, s.marginLeft());
|
||||
assertEquals(1081, s.marginRight());
|
||||
assertEquals(1440, s.marginTop());
|
||||
assertEquals(1441, s.marginBottom());
|
||||
assertEquals(850, s.header());
|
||||
assertEquals(992, s.footer());
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuousEnds_countedForNonLastOnly() {
|
||||
byte[] wd = new byte[4096];
|
||||
byte[] cont = {0x09, 0x30, 0x00}; // sprmSBkc=0x3009, bkcContinuous
|
||||
byte[] newPage = {0x09, 0x30, 0x02}; // bkcNewPage
|
||||
sepx(wd, 64, cont);
|
||||
sepx(wd, 128, cont);
|
||||
sepx(wd, 192, newPage);
|
||||
byte[] t = plcfSed(64, 128, 192);
|
||||
Sections s = Sections.read(t, 0, t.length, wd);
|
||||
// секции 0 и 1 — не последние: обе continuous считаются;
|
||||
// секция 2 — последняя: bkc в оценку не идёт
|
||||
assertEquals(2, s.continuousSectionEnds());
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
int len = 0;
|
||||
for (byte[] p : parts) {
|
||||
len += p.length;
|
||||
}
|
||||
byte[] out = new byte[len];
|
||||
int at = 0;
|
||||
for (byte[] p : parts) {
|
||||
System.arraycopy(p, 0, out, at, p.length);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Юниты {@link SummaryInfo} на крафтовом PropertySetStream ([MS-OLEPS] §2.21):
|
||||
* реальные фикстуры смещение offset свойства (относительное vs абсолютное) не
|
||||
* различают — max(кэш, разрывы) маскирует, поэтому поток собирается вручную.
|
||||
*/
|
||||
class SummaryInfoTest {
|
||||
|
||||
/**
|
||||
* PropertySetStream: заголовок 0x30 (ByteOrder/Version/SysId/CLSID(16)/
|
||||
* NumPropertySets/FMTID0(16)/Offset0) + PropertySet (cb, NumProperties,
|
||||
* массив (pid, offset), VT_I4 + значение); offset свойства — относительно
|
||||
* начала PropertySet (§2.20).
|
||||
*/
|
||||
private static byte[] propertySet(int pagecount) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(new byte[] {(byte) 0xFF, (byte) 0xFE, 1, 0}); // ByteOrder, Version
|
||||
out.write(new byte[4]); // SystemIdentifier
|
||||
out.write(new byte[16]); // CLSID
|
||||
out.write(le32(1)); // NumPropertySets
|
||||
out.write(new byte[16]); // FMTID0 (SummaryInformation)
|
||||
out.write(le32(0x30)); // Offset0
|
||||
out.write(le32(8 + 8 + 8)); // cbPropertySet
|
||||
out.write(le32(1)); // NumProperties
|
||||
out.write(le32(0x0000000E)); // PIDSI_PAGECOUNT
|
||||
out.write(le32(8 + 8)); // offset — относительно начала PropertySet
|
||||
out.write(le32(3)); // VT_I4
|
||||
out.write(le32(pagecount));
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] le32(int v) {
|
||||
return new byte[] {(byte) v, (byte) (v >>> 8), (byte) (v >>> 16), (byte) (v >>> 24)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_readFromRelativeOffset() throws Exception {
|
||||
assertEquals(42, SummaryInfo.pageCount(propertySet(42)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_shortStream_returnsZero() {
|
||||
assertEquals(0, SummaryInfo.pageCount(new byte[4]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_offsetBeyondStream_returnsZero() throws Exception {
|
||||
byte[] s = propertySet(42);
|
||||
s[0x2C] = 0x7F; // Offset0 за концом потока
|
||||
s[0x2D] = 0x7F;
|
||||
assertEquals(0, SummaryInfo.pageCount(s));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_truncatedProperty_returnsZero() throws Exception {
|
||||
byte[] s = propertySet(42);
|
||||
byte[] cut = new byte[s.length - 4];
|
||||
System.arraycopy(s, 0, cut, 0, cut.length);
|
||||
assertEquals(0, SummaryInfo.pageCount(cut));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user