Мост .doc → .docx: конвертация бинарного Word 97-2003 #76
@@ -29,6 +29,9 @@ Thumbs.db
|
|||||||
# Рабочие материалы и эталоны разработки (вне git)
|
# Рабочие материалы и эталоны разработки (вне git)
|
||||||
/develop/
|
/develop/
|
||||||
|
|
||||||
|
# Исходный dated-.docx [MS-DOC] — скачивается по команде из docs/standards/doc/README.md
|
||||||
|
docs/standards/doc/ms-doc.docx
|
||||||
|
|
||||||
# Секреты деплоя
|
# Секреты деплоя
|
||||||
.env
|
.env
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -1,7 +1,10 @@
|
|||||||
# Dev-стенд без ключа доступа: WORDPDF_API_KEY не задан → wordpdf.api-key пуст
|
# Dev-стенд без ключа доступа: WORDPDF_API_KEY не задан → wordpdf.api-key пуст
|
||||||
# → ApiKeyFilter прозрачен, springdoc включён. Проект wordpdf-dev — собственные
|
# → ApiKeyFilter прозрачен, springdoc включён. Проект wordpdf-dev — собственные
|
||||||
# образы/контейнеры, с прод-запуском (wordpdf-prod, :9010) не конфликтует.
|
# образы/контейнеры, с прод-запуском (wordpdf-prod, :9010) не конфликтует.
|
||||||
# Запуск: podman-compose -f compose.dev.yml up -d --build
|
# Запуск: podman-compose -f compose.dev.yml up -d --build --force-recreate
|
||||||
|
# (--force-recreate обязателен: без него podman-compose пересоберёт
|
||||||
|
# образ, но контейнеры оставит на старом — будет крутиться jar
|
||||||
|
# прошлой сборки)
|
||||||
# Вход: http://<LAN-IP хоста>:9011 (доступен из локальной сети; hostname -I на хосте)
|
# Вход: http://<LAN-IP хоста>:9011 (доступен из локальной сети; hostname -I на хосте)
|
||||||
name: wordpdf-dev
|
name: wordpdf-dev
|
||||||
# podman-compose по умолчанию разделяет имя проекта/сервиса/номера подчёркиванием
|
# podman-compose по умолчанию разделяет имя проекта/сервиса/номера подчёркиванием
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ SHA-256 `.md`-файлов — справочные: они производны
|
|||||||
|Файл|Документ|Редакция/дата|URL|SHA-256|
|
|Файл|Документ|Редакция/дата|URL|SHA-256|
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
|`ms-doc.md`|[MS-DOC] «Word (.doc) Binary File Format» — бинарный формат .doc Word 97–2003 (WordDocument/1Table-потоки, FIB, CHPX/PAPX, Clx/PlcPcd/Pcd — «piece table»)|12.5 (260217, февраль 2026)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-DOC/%5bMS-DOC%5d-260217.docx|`c2886120e92aa2790a5603156fb0ca8b23151d58476592fef3ede7fb6841ee7d`|
|
|`ms-doc.md`|[MS-DOC] «Word (.doc) Binary File Format» — бинарный формат .doc Word 97–2003 (WordDocument/1Table-потоки, FIB, CHPX/PAPX, Clx/PlcPcd/Pcd — «piece table»)|12.5 (260217, февраль 2026)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-DOC/%5bMS-DOC%5d-260217.docx|`c2886120e92aa2790a5603156fb0ca8b23151d58476592fef3ede7fb6841ee7d`|
|
||||||
|
|`ms-doc-full.md`|Тот же [MS-DOC] 12.5, полный конверт **с** HTML-packet-diagram'ами (`-t gfm`, raw_html включён): битовые макеты §2.4/§2.6/§2.9 и таблицы sprm §2.6.1–2.6.3 — то, что в `ms-doc.md` свёрнуто в `[TABLE]`|12.5 (260217, февраль 2026)|тот же dated-.docx, что `ms-doc.md`|`35cbcd5b5228cf02200008c2145d941e66dbf8a9e296305745d2bdc099c8a5ad`|
|
||||||
|`ms-cfb.md`|[MS-CFB] «Compound File Binary File Format» — OLE2-контейнер .doc (заголовок, FAT/MiniFAT, directory entries, потоки)|13.0 (261026, октябрь 2026)|https://winprotocoldocs-bhdugrdyduf5h2e4.b02.azurefd.net/MS-CFB/%5bMS-CFB%5d-261026.docx|`84d0f9f282aa00dac631a575514264b6bc1f3cec1b9c8fed095e12f7cc042913`|
|
|`ms-cfb.md`|[MS-CFB] «Compound File Binary File Format» — OLE2-контейнер .doc (заголовок, FAT/MiniFAT, directory entries, потоки)|13.0 (261026, октябрь 2026)|https://winprotocoldocs-bhdugrdyduf5h2e4.b02.azurefd.net/MS-CFB/%5bMS-CFB%5d-261026.docx|`84d0f9f282aa00dac631a575514264b6bc1f3cec1b9c8fed095e12f7cc042913`|
|
||||||
|`ms-oshared.md`|[MS-OSHARED] «Office Common Data Types and Objects Structures» — общие типы MS-DOC/MS-PPT/MS-XLS (MSONFC/FilePointer/FixedPoint, тулбары TBC, property sets, RefEdit, VBA-подпись)|11.1 (251113, ноябрь 2025)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-OSHARED/%5bMS-OSHARED%5d-251113.docx|`ccac510af0266a0804f6a242b08bc4df2f6d1f5b27935c113609b4faf198cb57`|
|
|`ms-oshared.md`|[MS-OSHARED] «Office Common Data Types and Objects Structures» — общие типы MS-DOC/MS-PPT/MS-XLS (MSONFC/FilePointer/FixedPoint, тулбары TBC, property sets, RefEdit, VBA-подпись)|11.1 (251113, ноябрь 2025)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-OSHARED/%5bMS-OSHARED%5d-251113.docx|`ccac510af0266a0804f6a242b08bc4df2f6d1f5b27935c113609b4faf198cb57`|
|
||||||
|`ms-odraw.md`|[MS-ODRAW] «Office Drawing Binary File Format» — бинарные рисунки OfficeArt (картинки/фигуры внутри .doc)|12.4 (250819, август 2025)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-ODRAW/%5bMS-ODRAW%5d-250819.docx|`f7b9b19222ca8b22ab773846a0c7ff4fa1898e391fff1b3ce41ca3b528f36cf6`|
|
|`ms-odraw.md`|[MS-ODRAW] «Office Drawing Binary File Format» — бинарные рисунки OfficeArt (картинки/фигуры внутри .doc)|12.4 (250819, август 2025)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-ODRAW/%5bMS-ODRAW%5d-250819.docx|`f7b9b19222ca8b22ab773846a0c7ff4fa1898e391fff1b3ce41ca3b528f36cf6`|
|
||||||
@@ -39,6 +40,10 @@ SHA-256 `.md`-файлов — справочные: они производны
|
|||||||
curl -sSL -o /tmp/msdoc.docx "https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-DOC/%5bMS-DOC%5d-260217.docx"
|
curl -sSL -o /tmp/msdoc.docx "https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-DOC/%5bMS-DOC%5d-260217.docx"
|
||||||
pandoc /tmp/msdoc.docx -t gfm-raw_html --wrap=none -o docs/standards/doc/ms-doc.md
|
pandoc /tmp/msdoc.docx -t gfm-raw_html --wrap=none -o docs/standards/doc/ms-doc.md
|
||||||
|
|
||||||
|
# ms-doc-full.md — тот же dated-.docx, но raw_html ВКЛЮЧЁН: packet diagram'ы и
|
||||||
|
# таблицы sprm (§2.6.1–2.6.3) остаются HTML-таблицами вместо [TABLE]-плейсхолдеров.
|
||||||
|
pandoc /tmp/msdoc.docx -t gfm --wrap=none -o docs/standards/doc/ms-doc-full.md
|
||||||
|
|
||||||
# Окружение MS-DOC — те же dated-.docx (при 404 — самый свежий с лендингов ниже).
|
# Окружение MS-DOC — те же dated-.docx (при 404 — самый свежий с лендингов ниже).
|
||||||
# Два CDN: у windows_protocols-документов (CFB, OLEPS, WMF, EMF) путь БЕЗ сегмента /files/.
|
# Два CDN: у windows_protocols-документов (CFB, OLEPS, WMF, EMF) путь БЕЗ сегмента /files/.
|
||||||
O="https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files"
|
O="https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files"
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -90,6 +90,21 @@ def test_convert_returns_pdf(url, samples, key_header):
|
|||||||
assert "filename*=UTF-8''en-plain.pdf" in disp
|
assert "filename*=UTF-8''en-plain.pdf" in disp
|
||||||
|
|
||||||
|
|
||||||
|
@needs_key
|
||||||
|
def test_convert_binary_doc(url, samples, key_header):
|
||||||
|
"""Бинарный .doc (Word 97-2003) → PDF: мост internal.doc на проде."""
|
||||||
|
r = requests.post(
|
||||||
|
url(CONVERT),
|
||||||
|
headers=key_header,
|
||||||
|
files={"file": ("ru-plain.doc", (samples / "ru-plain.doc").read_bytes())},
|
||||||
|
timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "application/pdf" in r.headers["content-type"]
|
||||||
|
assert r.content[:4] == b"%PDF"
|
||||||
|
assert "filename*=UTF-8''doc-ru.pdf" in r.headers["content-disposition"]
|
||||||
|
|
||||||
|
|
||||||
@needs_key
|
@needs_key
|
||||||
def test_convert_cyrillic_filename_rfc5987(url, samples, key_header):
|
def test_convert_cyrillic_filename_rfc5987(url, samples, key_header):
|
||||||
"""Кириллическое имя части → RFC 5987 filename* (safeBaseName), заголовок не режется наружным nginx.
|
"""Кириллическое имя части → RFC 5987 filename* (safeBaseName), заголовок не режется наружным nginx.
|
||||||
|
|||||||
@@ -70,7 +70,14 @@ final class ConversionService {
|
|||||||
* {@code null} не допускается (контроллер строит всегда).</p>
|
* {@code null} не допускается (контроллер строит всегда).</p>
|
||||||
*/
|
*/
|
||||||
byte[] convert(byte[] docxBytes, String originalFilename, ConvertOptions options) {
|
byte[] convert(byte[] docxBytes, String originalFilename, ConvertOptions options) {
|
||||||
|
// Бинарный .doc — не zip: .docx-валидация к нему неприменима, размер
|
||||||
|
// проверяется общим checkInput, страницы — мостом по чистому .doc
|
||||||
|
// (ядро бросит ValidationException → 400 тем же обработчиком).
|
||||||
|
if (WordPdfValidator.isBinaryDoc(docxBytes)) {
|
||||||
|
WordPdfValidator.checkInput(docxBytes, options.maxMb());
|
||||||
|
} else {
|
||||||
WordPdfValidator.validate(docxBytes, options);
|
WordPdfValidator.validate(docxBytes, options);
|
||||||
|
}
|
||||||
Future<byte[]> future;
|
Future<byte[]> future;
|
||||||
try {
|
try {
|
||||||
future = workers.submit(() -> doConvert(docxBytes, originalFilename, options));
|
future = workers.submit(() -> doConvert(docxBytes, originalFilename, options));
|
||||||
@@ -139,7 +146,7 @@ final class ConversionService {
|
|||||||
/**
|
/**
|
||||||
* Санитизация имени (единый источник для имени файла и Content-Disposition):
|
* Санитизация имени (единый источник для имени файла и Content-Disposition):
|
||||||
* без каталога, только буквы/цифры/пробел/ {@code . _ -}, без суффикса
|
* без каталога, только буквы/цифры/пробел/ {@code . _ -}, без суффикса
|
||||||
* .docx; пустое после очистки → {@code document}. Кириллица разрешена —
|
* .docx/.doc; пустое после очистки → {@code document}. Кириллица разрешена —
|
||||||
* на Linux это валидное имя файла, и заголовок PDF остаётся читаемым.
|
* на Linux это валидное имя файла, и заголовок PDF остаётся читаемым.
|
||||||
*/
|
*/
|
||||||
static String safeBaseName(String original) {
|
static String safeBaseName(String original) {
|
||||||
@@ -147,8 +154,11 @@ final class ConversionService {
|
|||||||
: original.substring(Math.max(original.lastIndexOf('/'),
|
: original.substring(Math.max(original.lastIndexOf('/'),
|
||||||
original.lastIndexOf('\\')) + 1);
|
original.lastIndexOf('\\')) + 1);
|
||||||
base = base.replaceAll("[^\\p{L}\\p{N} ._-]", "");
|
base = base.replaceAll("[^\\p{L}\\p{N} ._-]", "");
|
||||||
if (base.toLowerCase(Locale.ROOT).endsWith(".docx")) {
|
String lower = base.toLowerCase(Locale.ROOT);
|
||||||
|
if (lower.endsWith(".docx")) {
|
||||||
base = base.substring(0, base.length() - ".docx".length());
|
base = base.substring(0, base.length() - ".docx".length());
|
||||||
|
} else if (lower.endsWith(".doc")) {
|
||||||
|
base = base.substring(0, base.length() - ".doc".length());
|
||||||
}
|
}
|
||||||
if (base.isBlank()) {
|
if (base.isBlank()) {
|
||||||
base = "document";
|
base = "document";
|
||||||
|
|||||||
@@ -58,8 +58,9 @@ final class ConvertController {
|
|||||||
this.maxPages = maxPages;
|
this.maxPages = maxPages;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Конвертировать .docx в PDF",
|
@Operation(summary = "Конвертировать .docx/.doc в PDF",
|
||||||
description = "errorOnCharts/errorOnSmartArt/errorOnOle — факультативно, по умолчанию "
|
description = "Принимаются .docx (OOXML) и .doc (Word 97–2003, переносится в .docx "
|
||||||
|
+ "мостом: текст и прямое форматирование). errorOnCharts/errorOnSmartArt/errorOnOle — факультативно, по умолчанию "
|
||||||
+ "настройки ядра (ошибка не выбрасывается); диаграммы/SmartArt "
|
+ "настройки ядра (ошибка не выбрасывается); диаграммы/SmartArt "
|
||||||
+ "конвертируются всегда, OLE-объекты при выключенном флаге тихо удаляются. "
|
+ "конвертируются всегда, OLE-объекты при выключенном флаге тихо удаляются. "
|
||||||
+ "Лимиты входа (размер/страницы) задаёт только конфигурация сервера "
|
+ "Лимиты входа (размер/страницы) задаёт только конфигурация сервера "
|
||||||
@@ -78,9 +79,11 @@ final class ConvertController {
|
|||||||
throw new ValidationException("Файл не передан (multipart-поле «file» обязательно)");
|
throw new ValidationException("Файл не передан (multipart-поле «file» обязательно)");
|
||||||
}
|
}
|
||||||
String name = file.getOriginalFilename();
|
String name = file.getOriginalFilename();
|
||||||
if (name == null || !name.toLowerCase(Locale.ROOT).endsWith(".docx")) {
|
String lower = name == null ? "" : name.toLowerCase(Locale.ROOT);
|
||||||
// расширение проверяется здесь: ядро с байтов его не видит
|
if (!lower.endsWith(".docx") && !lower.endsWith(".doc")) {
|
||||||
throw new ValidationException("Поддерживается только .docx (без .doc): " + name);
|
// расширение проверяется здесь: ядро с байтов его не видит;
|
||||||
|
// .doc (Word 97–2003) переносится в .docx мостом internal.doc
|
||||||
|
throw new ValidationException("Поддерживаются только .docx и .doc: " + name);
|
||||||
}
|
}
|
||||||
byte[] docxBytes;
|
byte[] docxBytes;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -131,6 +131,9 @@ class ConversionServiceTest {
|
|||||||
assertEquals("evil", ConversionService.safeBaseName("a/../../evil.docx"));
|
assertEquals("evil", ConversionService.safeBaseName("a/../../evil.docx"));
|
||||||
assertEquals("evil", ConversionService.safeBaseName("C:\\tmp\\evil.docx"));
|
assertEquals("evil", ConversionService.safeBaseName("C:\\tmp\\evil.docx"));
|
||||||
assertEquals("отчёт", ConversionService.safeBaseName("отчёт.DOCX"));
|
assertEquals("отчёт", ConversionService.safeBaseName("отчёт.DOCX"));
|
||||||
|
assertEquals("отчёт", ConversionService.safeBaseName("отчёт.DOC"));
|
||||||
|
assertEquals("doc", ConversionService.safeBaseName("doc.doc"));
|
||||||
|
assertEquals("файл", ConversionService.safeBaseName("каталог\\файл.doc"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -280,6 +280,20 @@ class ConvertControllerTest {
|
|||||||
org.hamcrest.Matchers.containsString(".docx")));
|
org.hamcrest.Matchers.containsString(".docx")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Бинарный .doc принимается расширением и конвертируется мостом internal.doc. */
|
||||||
|
@Test
|
||||||
|
void docFile_convertsToPdf() throws Exception {
|
||||||
|
MvcResult result = mockMvc.perform(multipart("/api/v1/convert")
|
||||||
|
.file(docx("report.doc", bytes("/samples/ru-plain.doc"))))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(content().contentType(MediaType.APPLICATION_PDF))
|
||||||
|
.andReturn();
|
||||||
|
byte[] pdf = result.getResponse().getContentAsByteArray();
|
||||||
|
assertTrue("%PDF".equals(new String(pdf, 0, 4, StandardCharsets.US_ASCII)),
|
||||||
|
"тело не начинается с %PDF");
|
||||||
|
assertTrue(norm(pdfText(pdf)).contains("Привет, мир!"), "текст .doc не доехал");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void missingPart_rejected() throws Exception {
|
void missingPart_rejected() throws Exception {
|
||||||
mockMvc.perform(multipart("/api/v1/convert"))
|
mockMvc.perform(multipart("/api/v1/convert"))
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import ru.pjandro.wordpdf.internal.chart.DrawingPreRenderer;
|
|||||||
import ru.pjandro.wordpdf.internal.DependencyGuard;
|
import ru.pjandro.wordpdf.internal.DependencyGuard;
|
||||||
import ru.pjandro.wordpdf.internal.DocxNormalizer;
|
import ru.pjandro.wordpdf.internal.DocxNormalizer;
|
||||||
import ru.pjandro.wordpdf.internal.DocxRewritePipeline;
|
import ru.pjandro.wordpdf.internal.DocxRewritePipeline;
|
||||||
|
import ru.pjandro.wordpdf.internal.doc.DocToDocx;
|
||||||
import ru.pjandro.wordpdf.internal.OleObjectNormalizer;
|
import ru.pjandro.wordpdf.internal.OleObjectNormalizer;
|
||||||
import ru.pjandro.wordpdf.internal.FopFallbackFonts;
|
import ru.pjandro.wordpdf.internal.FopFallbackFonts;
|
||||||
import ru.pjandro.wordpdf.internal.LayoutPostRenderer;
|
import ru.pjandro.wordpdf.internal.LayoutPostRenderer;
|
||||||
@@ -61,20 +62,26 @@ public final class WordPdfConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Конвертирует байты .docx в PDF. Работа с файлами — забота вызывающего
|
* Конвертирует байты .docx (или бинарного .doc Word 97–2003 — формат
|
||||||
* (файловое API было здесь раньше; ядро пути не принимает).
|
* определяется по сигнатуре байтов) в 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-подпись /
|
* {@code null} / размер больше {@link WordPdfSettings#MAX_INPUT_MB} (МБ) / zip-подпись /
|
||||||
* число страниц больше {@link WordPdfSettings#MAX_PAGES} — при отказе байтов результата нет;
|
* число страниц больше {@link WordPdfSettings#MAX_PAGES} — при отказе байтов результата нет;
|
||||||
* страницы дополнительно перепроверяются по нормализованным байтам (шаг 2.5).
|
* страницы дополнительно перепроверяются по нормализованным байтам (шаг 2.5).
|
||||||
*
|
*
|
||||||
* @param docxBytes байты .docx
|
* @param docxBytes байты .docx или бинарного .doc
|
||||||
* @param title заголовок PDF (метаданные); {@code null}/пустая — заголовок не задаётся
|
* @param title заголовок PDF (метаданные); {@code null}/пустая — заголовок не задаётся
|
||||||
* @return байты готового PDF
|
* @return байты готового PDF
|
||||||
* @throws ValidationException некорректный вход: {@code null}, размер больше
|
* @throws ValidationException некорректный вход: {@code null}, размер больше
|
||||||
* {@link WordPdfSettings#MAX_INPUT_MB} (МБ), не zip-архив, документ длиннее
|
* {@link WordPdfSettings#MAX_INPUT_MB} (МБ), не .docx/.doc, зашифрованный .doc,
|
||||||
* {@link WordPdfSettings#MAX_PAGES} страниц
|
* документ длиннее {@link WordPdfSettings#MAX_PAGES} страниц
|
||||||
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
||||||
*/
|
*/
|
||||||
public static byte[] convert(byte[] docxBytes, String title) throws ConversionException {
|
public static byte[] convert(byte[] docxBytes, String title) throws ConversionException {
|
||||||
@@ -82,30 +89,43 @@ public final class WordPdfConverter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Конвертирует байты .docx в PDF с настройками на вызов: error-флаги
|
* Конвертирует байты .docx (или бинарного .doc Word 97–2003 — формат
|
||||||
* диаграмм/SmartArt и лимиты входа.
|
* определяется по сигнатуре байтов, см. перегрузку выше) в PDF с
|
||||||
|
* настройками на вызов: error-флаги диаграмм/SmartArt и лимиты входа.
|
||||||
*
|
*
|
||||||
* <p>Вход проверяется {@link WordPdfValidator#validate(byte[], ConvertOptions)} до рендера:
|
* <p>Вход проверяется {@link WordPdfValidator#validate(byte[], ConvertOptions)}
|
||||||
* {@code null} / размер больше {@code options.maxMb()} (МБ) / zip-подпись / число страниц
|
* до рендера — одна проверка на оба формата: {@code null} / размер больше
|
||||||
* больше {@code options.maxPages()} — при отказе байтов результата нет; страницы
|
* {@code options.maxMb()} (МБ) / не .docx и не .doc / число страниц больше
|
||||||
* дополнительно перепроверяются по нормализованным байтам (шаг 2.5).
|
* {@code options.maxPages()} — при отказе байтов результата нет. Для .docx
|
||||||
|
* страницы дополнительно перепроверяются по нормализованным байтам (шаг 2.5);
|
||||||
|
* для .doc страницы считаются по чистому бинарному документу до конвертации,
|
||||||
|
* конвертат не перепроверяется.
|
||||||
*
|
*
|
||||||
* @param docxBytes байты .docx
|
* @param docxBytes байты .docx или бинарного .doc
|
||||||
* @param title заголовок PDF (метаданные); {@code null}/пустая — заголовок не задаётся
|
* @param title заголовок PDF (метаданные); {@code null}/пустая — заголовок не задаётся
|
||||||
* @param options error-флаги и лимиты входа на этот вызов; {@code null} —
|
* @param options error-флаги и лимиты входа на этот вызов; {@code null} —
|
||||||
* дефолты (константы {@link WordPdfSettings})
|
* дефолты (константы {@link WordPdfSettings})
|
||||||
* @return байты готового PDF
|
* @return байты готового PDF
|
||||||
* @throws ValidationException некорректный вход: {@code null}, размер больше
|
* @throws ValidationException некорректный вход: {@code null}, размер больше
|
||||||
* {@code options.maxMb()} (МБ), не zip-архив, документ длиннее
|
* {@code options.maxMb()} (МБ), не .docx/.doc, зашифрованный .doc,
|
||||||
* {@code options.maxPages()} страниц
|
* документ длиннее {@code options.maxPages()} страниц
|
||||||
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
* @throws ConversionException прочие ошибки (битый .docx, ошибка рендера)
|
||||||
*/
|
*/
|
||||||
public static byte[] convert(byte[] docxBytes, String title, ConvertOptions options) throws ConversionException {
|
public static byte[] convert(byte[] docxBytes, String title, ConvertOptions options) throws ConversionException {
|
||||||
ConvertOptions opts = options == null ? ConvertOptions.defaults() : options;
|
ConvertOptions opts = options == null ? ConvertOptions.defaults() : options;
|
||||||
|
// Полная проверка входа — одна на оба формата: размер до
|
||||||
|
// классификации (враждебный вход без подписи обязан получить ошибку
|
||||||
|
// лимита), затем для .docx — zip/контейнер/страницы, для .doc —
|
||||||
|
// страницы по чистому бинарному документу (до конвертации).
|
||||||
WordPdfValidator.validate(docxBytes, opts);
|
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 {
|
try {
|
||||||
convertToStream(docxBytes, title, opts, bos);
|
convertToStream(docx, title, opts, bos, fromDoc);
|
||||||
} catch (ConversionException e) {
|
} catch (ConversionException e) {
|
||||||
// ValidationException (отказ валидации входа) — подтип, уходит
|
// ValidationException (отказ валидации входа) — подтип, уходит
|
||||||
// вызывающему без обёртки
|
// вызывающему без обёртки
|
||||||
@@ -122,7 +142,7 @@ public final class WordPdfConverter {
|
|||||||
* без неё старая версия библиотеки дала бы мутный NoSuchMethodError внутри docx4j.
|
* без неё старая версия библиотеки дала бы мутный NoSuchMethodError внутри docx4j.
|
||||||
*/
|
*/
|
||||||
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
private static void convertToStream(byte[] rawDocxBytes, String title, ConvertOptions options,
|
||||||
OutputStream os) throws Exception {
|
OutputStream os, boolean skipPageRecheck) throws Exception {
|
||||||
// 0. Совместимость commons-compress: docx4j требует ковариантный
|
// 0. Совместимость commons-compress: docx4j требует ковариантный
|
||||||
// ZipArchiveInputStream.getNextEntry() (>= 1.25.0); ниже — понятный
|
// ZipArchiveInputStream.getNextEntry() (>= 1.25.0); ниже — понятный
|
||||||
// ConversionException с инструкцией вместо NoSuchMethodError.
|
// ConversionException с инструкцией вместо NoSuchMethodError.
|
||||||
@@ -153,7 +173,12 @@ public final class WordPdfConverter {
|
|||||||
// Делается до рендера, чтобы не тратить время на заведомо
|
// Делается до рендера, чтобы не тратить время на заведомо
|
||||||
// длинный документ; внутри try — чтобы и на отказе отработал
|
// длинный документ; внутри try — чтобы и на отказе отработал
|
||||||
// finally с чисткой temp-файлов встроенных шрифтов.
|
// finally с чисткой temp-файлов встроенных шрифтов.
|
||||||
|
// Для .doc пропущена: страницы уже посчитаны мостом по чистому
|
||||||
|
// бинарному документу, перепроверять собственный конвертат —
|
||||||
|
// значит проверять не вход.
|
||||||
|
if (!skipPageRecheck) {
|
||||||
WordPdfValidator.checkPageCount(docxBytes, options.maxPages());
|
WordPdfValidator.checkPageCount(docxBytes, options.maxPages());
|
||||||
|
}
|
||||||
// после этой строки docxBytes больше не читается — HotSpot с точными
|
// после этой строки docxBytes больше не читается — HotSpot с точными
|
||||||
// картами liveness считает его недостижимым, нормализованная копия
|
// картами liveness считает его недостижимым, нормализованная копия
|
||||||
// освобождается до FOP-рендера (пик: JAXB-модель + FOP + PDF-буфер)
|
// освобождается до FOP-рендера (пик: JAXB-модель + FOP + PDF-буфер)
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package ru.pjandro.wordpdf;
|
package ru.pjandro.wordpdf;
|
||||||
|
|
||||||
|
import ru.pjandro.wordpdf.internal.doc.DocToDocx;
|
||||||
|
|
||||||
import javax.xml.stream.XMLInputFactory;
|
import javax.xml.stream.XMLInputFactory;
|
||||||
import javax.xml.stream.XMLStreamException;
|
import javax.xml.stream.XMLStreamException;
|
||||||
import javax.xml.stream.XMLStreamReader;
|
import javax.xml.stream.XMLStreamReader;
|
||||||
@@ -16,9 +18,10 @@ import java.util.zip.ZipEntry;
|
|||||||
import java.util.zip.ZipInputStream;
|
import java.util.zip.ZipInputStream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Валидатор ограничений на входной .docx:
|
* Валидатор ограничений на вход: .docx и бинарный .doc (Word 97–2003) —
|
||||||
* размер входа, корректность контейнера (.docx-манифест, защита от
|
* размер входа, корректность контейнера (.docx-манифест, защита от
|
||||||
* zip-бомбы) и число страниц.
|
* zip-бомбы; для .doc — CFB/Word-разбор {@code internal.doc}) и число
|
||||||
|
* страниц для обоих форматов.
|
||||||
*
|
*
|
||||||
* <p>Вход валидатора — только {@code byte[]}: файловых проверок нет,
|
* <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
|
* Проверяет число страниц без загрузки документа в docx4j: .docx
|
||||||
* читается как zip напрямую (StAX по {@code word/document.xml},
|
* читается как zip напрямую (StAX по {@code word/document.xml},
|
||||||
@@ -183,8 +206,42 @@ public final class WordPdfValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Полная проверка входа: размер → zip-подпись → контейнер (.docx +
|
* Число страниц бинарного .doc (Word 97–2003) — по чистому бинарному
|
||||||
* zip-бомба) → число страниц. Порядок
|
* документу, <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 без подписи бессмысленен. Лимиты
|
* значим: размер — дешёвая, разбор zip без подписи бессмысленен. Лимиты
|
||||||
* берутся из {@link ConvertOptions} (переопределение на вызов, см.
|
* берутся из {@link ConvertOptions} (переопределение на вызов, см.
|
||||||
* {@link ConvertOptions#maxMb()}, {@link ConvertOptions#maxPages()}).
|
* {@link ConvertOptions#maxMb()}, {@link ConvertOptions#maxPages()}).
|
||||||
@@ -212,9 +269,15 @@ public final class WordPdfValidator {
|
|||||||
*/
|
*/
|
||||||
public static void validate(byte[] docxBytes, ConvertOptions options) throws ValidationException {
|
public static void validate(byte[] docxBytes, ConvertOptions options) throws ValidationException {
|
||||||
checkInput(docxBytes, options.maxMb());
|
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'
|
if (docxBytes.length < 4 || docxBytes[0] != 'P' || docxBytes[1] != 'K'
|
||||||
|| (docxBytes[2] & 0xFF) != 0x03 || (docxBytes[3] & 0xFF) != 0x04) {
|
|| (docxBytes[2] & 0xFF) != 0x03 || (docxBytes[3] & 0xFF) != 0x04) {
|
||||||
throw new ValidationException("Содержимое не похоже на .docx (не zip-архив)");
|
throw new ValidationException("Содержимое не похоже на .docx или .doc (не zip-архив)");
|
||||||
}
|
}
|
||||||
checkDocxContainer(docxBytes);
|
checkDocxContainer(docxBytes);
|
||||||
checkPageCount(docxBytes, options.maxPages());
|
checkPageCount(docxBytes, options.maxPages());
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
|
|||||||
* (TableIndent читает transitional-атрибуты {@code w:}); GlyphCoverage
|
* (TableIndent читает transitional-атрибуты {@code w:}); GlyphCoverage
|
||||||
* режет раны по финальному тексту рана (после Symbol/Invisible). Каждый
|
* режет раны по финальному тексту рана (после Symbol/Invisible). Каждый
|
||||||
* рерайт работает только содержимым одной части, поэтому по-частная
|
* рерайт работает только содержимым одной части, поэтому по-частная
|
||||||
* цепочка эквивалентна последовательным полным проходам.
|
* цепочка эквивалентна последовательным полным проходам. Правило 7
|
||||||
|
* (TableIndent) — исключение из «по-частности»: у header/footer-частей
|
||||||
|
* своей sectPr нет, ширина полосы передаётся из document.xml (один
|
||||||
|
* дополнительный inflate до цикла; многосекционный документ — полоса
|
||||||
|
* неоднозначна, header/footer пропускаются).
|
||||||
*
|
*
|
||||||
* <p>Неизменённые записи (медиа, rels, прочее) переносятся raw-копией
|
* <p>Неизменённые записи (медиа, rels, прочее) переносятся raw-копией
|
||||||
* сжатых байтов — без inflate/deflate; прочие (редкие методы сжатия,
|
* сжатых байтов — без inflate/deflate; прочие (редкие методы сжатия,
|
||||||
@@ -55,6 +59,19 @@ public final class DocxRewritePipeline {
|
|||||||
boolean changed = false;
|
boolean changed = false;
|
||||||
try (ZipFile zf = new ZipFile(new SeekableInMemoryByteChannel(docx));
|
try (ZipFile zf = new ZipFile(new SeekableInMemoryByteChannel(docx));
|
||||||
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(out)) {
|
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(out)) {
|
||||||
|
// Ширина полосы набора для правила 7 (таблицы в header/footer-
|
||||||
|
// частях своей sectPr не содержат): из сырого document.xml —
|
||||||
|
// геометрия инвариантна к рерайтам цепочки (Strict не трогает
|
||||||
|
// w:pgSz/@w:w, а pgMar-чередование left|start покрывает strict).
|
||||||
|
// Записи нет/несколько секций → −1, header/footer консервативно
|
||||||
|
// пропускаются (та же неоднозначность полосы, что для body).
|
||||||
|
int band = -1;
|
||||||
|
ZipArchiveEntry docEntry = zf.getEntry("word/document.xml");
|
||||||
|
if (docEntry != null) {
|
||||||
|
band = TableIndentNormalizer.bandOf(
|
||||||
|
new String(zf.getInputStream(docEntry).readAllBytes(),
|
||||||
|
StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
for (ZipArchiveEntry entry : Collections.list(zf.getEntries())) {
|
for (ZipArchiveEntry entry : Collections.list(zf.getEntries())) {
|
||||||
String name = entry.getName();
|
String name = entry.getName();
|
||||||
byte[] rewritten = null;
|
byte[] rewritten = null;
|
||||||
@@ -86,7 +103,7 @@ public final class DocxRewritePipeline {
|
|||||||
if (next != null) {
|
if (next != null) {
|
||||||
cur = next;
|
cur = next;
|
||||||
}
|
}
|
||||||
next = TableIndentNormalizer.rewrite(cur);
|
next = TableIndentNormalizer.rewritePart(name, cur, band);
|
||||||
if (next != null) {
|
if (next != null) {
|
||||||
cur = next;
|
cur = next;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,20 +20,31 @@ import java.util.zip.ZipOutputStream;
|
|||||||
* (аудит раскладки ECMA-376, матрица B3) — таблица рендерилась без учёта
|
* (аудит раскладки ECMA-376, матрица B3) — таблица рендерилась без учёта
|
||||||
* tblInd. Нормализатор вычисляет итоговый отступ сам и записывает его в
|
* tblInd. Нормализатор вычисляет итоговый отступ сам и записывает его в
|
||||||
* {@code w:tblInd}, удалив {@code w:jc}: center → (W−T)/2+X, right → (W−T)+X,
|
* {@code w:tblInd}, удалив {@code w:jc}: center → (W−T)/2+X, right → (W−T)+X,
|
||||||
* где W — ширина полосы набора (pgSz−pgMar left/right), T — Σ gridCol.
|
* где W — ширина полосы набора (pgSz−pgMar left/right), T — Σ gridCol,
|
||||||
|
* X — прямой {@code w:tblInd} (отсутствующий или нулевой — 0). Свёртка
|
||||||
|
* обязательна и при X=0: docx4j пишет центрированию абсолютный
|
||||||
|
* {@code start-indent=(W−T)/2} БЕЗ вычета левого cellMar, а padding-
|
||||||
|
* компенсация {@code LayoutPostRenderer} (шаг 4.25, рассчитана на tblInd-ветку,
|
||||||
|
* где docx4j padding вычитает) прибавляет padding поверх — текст уезжает на
|
||||||
|
* +padding от Word (замер: 165.57pt вместо 160.15pt).
|
||||||
*
|
*
|
||||||
* <p>Пропускается (не ломая существующее поведение): документы без
|
* <p>Пропускается (не ломая существующее поведение): документы без
|
||||||
* единственного body-level {@code w:sectPr} (несколько секций — полоса
|
* единственного body-level {@code w:sectPr} (несколько секций — полоса
|
||||||
* неоднозначна), таблицы без {@code w:tblInd} (jc docx4j обрабатывает
|
* неоднозначна), {@code w:tblW type="pct"} и таблицы с gridCol без целого
|
||||||
* корректно — аудит PASS), {@code w:tblW type="pct"} и таблицы с gridCol без
|
* {@code w:w} (фактическая ширина неизвестна), {@code w:tblInd} не-dxa и
|
||||||
* целого {@code w:w} (фактическая ширина неизвестна). Дефолты при отсутствии
|
* {@code w:tblPr} с {@code w:tblCellSpacing} без {@code w:tblInd} (вставить
|
||||||
|
* тег в корректную позицию CT_TblPrBase некуда). Дефолты при отсутствии
|
||||||
* pgSz/pgMar — 11906 и 1440/1440: измеренное поведение docx4j при отсутствующем
|
* pgSz/pgMar — 11906 и 1440/1440: измеренное поведение docx4j при отсутствующем
|
||||||
* {@code w:pgMar} (левый край текста = 72pt = 1440 twips), а не ECMA-дефолт
|
* {@code w:pgMar} (левый край текста = 72pt = 1440 twips), а не ECMA-дефолт
|
||||||
* 1800 — нормализатор обязан считать ту же полосу, что рендерит стек.
|
* 1800 — нормализатор обязан считать ту же полосу, что рендерит стек.
|
||||||
*
|
*
|
||||||
* <p>Трогает только {@code word/document.xml} (признак — {@code <w:body});
|
* <p>{@link #normalize} трогает только {@code word/document.xml} (признак —
|
||||||
* нечего менять → тот же массив. Регрессия —
|
* {@code <w:body}); нечего менять → тот же массив. {@link #rewritePart} —
|
||||||
* WordPdfConverterTest#tableIndentCentered_shiftedLikeWord.
|
* хук общего прохода {@code DocxRewritePipeline}: сворачивает и таблицы в
|
||||||
|
* {@code word/headerN.xml}/{@code word/footerN.xml} (полоса — из
|
||||||
|
* document.xml, своей sectPr у частей нет). Регрессии —
|
||||||
|
* WordPdfConverterTest#tableIndentCentered_shiftedLikeWord,
|
||||||
|
* #headerTableIndent_centeredInHeader.
|
||||||
*/
|
*/
|
||||||
public final class TableIndentNormalizer {
|
public final class TableIndentNormalizer {
|
||||||
|
|
||||||
@@ -46,8 +57,13 @@ public final class TableIndentNormalizer {
|
|||||||
private static final String DOCUMENT_ENTRY = "word/document.xml";
|
private static final String DOCUMENT_ENTRY = "word/document.xml";
|
||||||
|
|
||||||
private static final Pattern PG_SZ_W = Pattern.compile("<w:pgSz\\b[^>]*w:w=\"(\\d+)\"");
|
private static final Pattern PG_SZ_W = Pattern.compile("<w:pgSz\\b[^>]*w:w=\"(\\d+)\"");
|
||||||
private static final Pattern PG_MAR_LEFT = Pattern.compile("<w:pgMar\\b[^>]*w:left=\"(\\d+)\"");
|
// strict-OOXML пишет поля как w:start/w:end; band считается из СЫРОГО
|
||||||
private static final Pattern PG_MAR_RIGHT = Pattern.compile("<w:pgMar\\b[^>]*w:right=\"(\\d+)\"");
|
// document.xml (до rule 1, которая их переименует) — чередование
|
||||||
|
// обязательно, иначе полоса строгого документа молча возьмётся из дефолтов
|
||||||
|
private static final Pattern PG_MAR_LEFT =
|
||||||
|
Pattern.compile("<w:pgMar\\b[^>]*w:(?:left|start)=\"(\\d+)\"");
|
||||||
|
private static final Pattern PG_MAR_RIGHT =
|
||||||
|
Pattern.compile("<w:pgMar\\b[^>]*w:(?:right|end)=\"(\\d+)\"");
|
||||||
private static final Pattern JC =
|
private static final Pattern JC =
|
||||||
Pattern.compile("<w:jc\\b[^>]*w:val=\"(center|right)\"[^>]*/>");
|
Pattern.compile("<w:jc\\b[^>]*w:val=\"(center|right)\"[^>]*/>");
|
||||||
private static final Pattern TBL_IND = Pattern.compile("<w:tblInd\\b[^>]*/>");
|
private static final Pattern TBL_IND = Pattern.compile("<w:tblInd\\b[^>]*/>");
|
||||||
@@ -91,6 +107,9 @@ public final class TableIndentNormalizer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Переписывает jc+tblInd в абсолютный tblInd в {@code word/document.xml}
|
||||||
|
* (полоса — из его единственной body-level sectPr).
|
||||||
|
*
|
||||||
* @return новая строка либо null, если менять нечего
|
* @return новая строка либо null, если менять нечего
|
||||||
*/
|
*/
|
||||||
static String rewrite(String xml) {
|
static String rewrite(String xml) {
|
||||||
@@ -101,6 +120,47 @@ public final class TableIndentNormalizer {
|
|||||||
if (band < 0) {
|
if (band < 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
return rewriteBand(xml, band);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Рерайт одной zip-записи с известной шириной полосы набора: части
|
||||||
|
* {@code word/headerN.xml}/{@code word/footerN.xml} не содержат своей
|
||||||
|
* sectPr — полосу передаёт вызывающий из {@code word/document.xml}
|
||||||
|
* (геометрия инвариантна к рерайтам цепочки: Strict не трогает
|
||||||
|
* {@code w:pgSz/@w:w} и {@code w:pgMar/@w:left|right}). Многосекционный
|
||||||
|
* документ ({@code band < 0} — полоса неоднозначна) консервативно
|
||||||
|
* пропускается, как и body. Хук общего прохода DocxRewritePipeline.
|
||||||
|
*
|
||||||
|
* @param name имя zip-записи (правятся только document/header/footer-части)
|
||||||
|
* @param band ширина полосы в twips, <0 — неоднозначна
|
||||||
|
* @return новая строка либо null, если менять нечего
|
||||||
|
*/
|
||||||
|
static String rewritePart(String name, String xml, int band) {
|
||||||
|
if (DOCUMENT_ENTRY.equals(name)) {
|
||||||
|
return rewrite(xml);
|
||||||
|
}
|
||||||
|
if (!name.startsWith("word/header") && !name.startsWith("word/footer")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (xml.indexOf("<w:tbl") < 0 || band < 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return rewriteBand(xml, band);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ширина полосы по единственному body-level sectPr (хук DocxRewritePipeline). */
|
||||||
|
static int bandOf(String xml) {
|
||||||
|
return bandWidth(xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ядро свёртки: jc(center/right)+tblInd → абсолютный tblInd при заданной
|
||||||
|
* полосе {@code band}.
|
||||||
|
*
|
||||||
|
* @return новая строка либо null, если менять нечего
|
||||||
|
*/
|
||||||
|
private static String rewriteBand(String xml, int band) {
|
||||||
StringBuilder sb = null;
|
StringBuilder sb = null;
|
||||||
int mark = 0;
|
int mark = 0;
|
||||||
int scan = 0;
|
int scan = 0;
|
||||||
@@ -121,13 +181,18 @@ public final class TableIndentNormalizer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Matcher ind = TBL_IND.matcher(pr);
|
Matcher ind = TBL_IND.matcher(pr);
|
||||||
if (!ind.find()) {
|
boolean hasInd = ind.find();
|
||||||
continue;
|
int x = 0;
|
||||||
}
|
if (hasInd) {
|
||||||
String indTag = ind.group();
|
String indTag = ind.group();
|
||||||
Matcher indW = TBL_IND_W.matcher(indTag);
|
Matcher indW = TBL_IND_W.matcher(indTag);
|
||||||
if (!indW.find() || "0".equals(indW.group(1))
|
if (!indW.find() || !indTag.contains("w:type=\"dxa\"")) {
|
||||||
|| !indTag.contains("w:type=\"dxa\"")) {
|
continue; // не-dxa — величина сдвига неизвестна
|
||||||
|
}
|
||||||
|
x = Integer.parseInt(indW.group(1));
|
||||||
|
} else if (pr.contains("<w:tblCellSpacing")) {
|
||||||
|
// tblInd по CT_TblPrBase идёт ПОСЛЕ tblCellSpacing — вставить
|
||||||
|
// тег в корректную позицию некуда, консервативно пропускаем
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (pr.contains("<w:tblW") && pr.contains("w:type=\"pct\"")) {
|
if (pr.contains("<w:tblW") && pr.contains("w:type=\"pct\"")) {
|
||||||
@@ -137,11 +202,11 @@ public final class TableIndentNormalizer {
|
|||||||
if (width < 0) {
|
if (width < 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
int x = Integer.parseInt(indW.group(1));
|
|
||||||
int newInd = "center".equals(jc.group(1))
|
int newInd = "center".equals(jc.group(1))
|
||||||
? (int) Math.round((band - width) / 2.0) + x
|
? (int) Math.round((band - width) / 2.0) + x
|
||||||
: band - width + x;
|
: band - width + x;
|
||||||
String fixedPr = pr.substring(0, jc.start()) + pr.substring(jc.end());
|
String fixedPr = pr.substring(0, jc.start()) + pr.substring(jc.end());
|
||||||
|
if (hasInd) {
|
||||||
Matcher indInFixed = TBL_IND.matcher(fixedPr);
|
Matcher indInFixed = TBL_IND.matcher(fixedPr);
|
||||||
indInFixed.find();
|
indInFixed.find();
|
||||||
String indTagFixed = indInFixed.group();
|
String indTagFixed = indInFixed.group();
|
||||||
@@ -149,6 +214,15 @@ public final class TableIndentNormalizer {
|
|||||||
Matcher.quoteReplacement("w:w=\"" + newInd + "\""));
|
Matcher.quoteReplacement("w:w=\"" + newInd + "\""));
|
||||||
fixedPr = fixedPr.substring(0, indInFixed.start()) + newTag
|
fixedPr = fixedPr.substring(0, indInFixed.start()) + newTag
|
||||||
+ fixedPr.substring(indInFixed.end());
|
+ fixedPr.substring(indInFixed.end());
|
||||||
|
} else {
|
||||||
|
// X=0: tblInd на место удалённого jc — правый сосед либо
|
||||||
|
// tblBorders, либо конец tblPr (tblCellSpacing отсеян выше),
|
||||||
|
// порядок CT_TblPrBase (tblW → jc → tblCellSpacing → tblInd →
|
||||||
|
// tblBorders, wml.xsd) сохранён
|
||||||
|
fixedPr = fixedPr.substring(0, jc.start())
|
||||||
|
+ "<w:tblInd w:w=\"" + newInd + "\" w:type=\"dxa\"/>"
|
||||||
|
+ fixedPr.substring(jc.start());
|
||||||
|
}
|
||||||
if (sb == null) {
|
if (sb == null) {
|
||||||
sb = new StringBuilder(xml.length());
|
sb = new StringBuilder(xml.length());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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, fib.ccpText());
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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,253 @@
|
|||||||
|
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_STSHF = 1;
|
||||||
|
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 static final int PAIR_PLF_LST = 73;
|
||||||
|
private static final int PAIR_PLF_LFO = 74;
|
||||||
|
|
||||||
|
private final int ccpText;
|
||||||
|
private final int ccpFtn;
|
||||||
|
private final int ccpHdd;
|
||||||
|
private final int cbMac;
|
||||||
|
private final boolean use1Table;
|
||||||
|
private final long fcStshf;
|
||||||
|
private final long lcbStshf;
|
||||||
|
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 final long fcPlfLst;
|
||||||
|
private final long lcbPlfLst;
|
||||||
|
private final long fcPlfLfo;
|
||||||
|
private final long lcbPlfLfo;
|
||||||
|
|
||||||
|
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[] stshf = pair(wd, PAIR_STSHF);
|
||||||
|
fcStshf = stshf[0];
|
||||||
|
lcbStshf = stshf[1];
|
||||||
|
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];
|
||||||
|
long[] lst = pair(wd, PAIR_PLF_LST);
|
||||||
|
fcPlfLst = lst[0];
|
||||||
|
lcbPlfLst = lst[1];
|
||||||
|
long[] lfo = pair(wd, PAIR_PLF_LFO);
|
||||||
|
fcPlfLfo = lfo[0];
|
||||||
|
lcbPlfLfo = lfo[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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Смещение STSH в табличном потоке (§2.5.6 fcStshf); lcb=0 — стилей нет. */
|
||||||
|
long fcStshf() {
|
||||||
|
return fcStshf;
|
||||||
|
}
|
||||||
|
|
||||||
|
long lcbStshf() {
|
||||||
|
return lcbStshf;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Смещение PlfLst в табличном потоке (§2.5.6 fcPlfLst); lcb=0 — списков нет. */
|
||||||
|
long fcPlfLst() {
|
||||||
|
return fcPlfLst;
|
||||||
|
}
|
||||||
|
|
||||||
|
long lcbPlfLst() {
|
||||||
|
return lcbPlfLst;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Смещение PlfLfo (§2.5.6 fcPlfLfo); lcb=0 — fcPlfLfo не определён (§2.5.6). */
|
||||||
|
long fcPlfLfo() {
|
||||||
|
return fcPlfLfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
long lcbPlfLfo() {
|
||||||
|
return lcbPlfLfo;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,287 @@
|
|||||||
|
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_ISTD = 0x4600;
|
||||||
|
static final int SPRM_P_JC80 = 0x2403;
|
||||||
|
static final int SPRM_P_F_PAGE_BREAK_BEFORE = 0x2407;
|
||||||
|
static final int SPRM_P_F_IN_TABLE = 0x2416;
|
||||||
|
static final int SPRM_P_F_TTP = 0x2417;
|
||||||
|
static final int SPRM_P_DYA_LINE = 0x6412;
|
||||||
|
static final int SPRM_P_DYA_BEFORE = 0xA413;
|
||||||
|
static final int SPRM_P_DYA_AFTER = 0xA414;
|
||||||
|
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;
|
||||||
|
/**
|
||||||
|
* 80-варианты отступов (§2.6.2, все XAS 2 Б): sprmPDxaRight80,
|
||||||
|
* sprmPDxaLeft80, sprmPNest80, sprmPDxaLeft180 и современный sprmPNest —
|
||||||
|
* документы со старым происхождением несут только их; накопление —
|
||||||
|
* {@link Indents}.
|
||||||
|
*/
|
||||||
|
static final int SPRM_P_DXA_RIGHT80 = 0x840E;
|
||||||
|
static final int SPRM_P_DXA_LEFT80 = 0x840F;
|
||||||
|
static final int SPRM_P_NEST80 = 0x4610;
|
||||||
|
static final int SPRM_P_DXA_LEFT180 = 0x8411;
|
||||||
|
static final int SPRM_P_NEST = 0x465F;
|
||||||
|
/**
|
||||||
|
* sprmPChgTabsPapx (§2.6.2, переменный): PChgTabsPapxOperand (§2.9.183) —
|
||||||
|
* кастомные табы абзаца. Значение 0xC60D — по таблице §2.6.2
|
||||||
|
* (sgc 1 = PAP); 0xD60D был бы sgc 5.
|
||||||
|
*/
|
||||||
|
static final int SPRM_P_CHG_TABS_PAPX = 0xC60D;
|
||||||
|
/**
|
||||||
|
* sprmPChgTabs (§2.6.2, переменный): PChgTabsOperand (§2.9.182) — тот же
|
||||||
|
* смысл, но с спец-семантикой cb=0xFF; в PAPX Word пишет 0xC60D, здесь
|
||||||
|
* только корректный пропуск (в §2.9.182 длина при cb=0xFF считается по
|
||||||
|
* формуле — операнд помечен как «MAY be ignored», разбор обрывается).
|
||||||
|
*/
|
||||||
|
static final int SPRM_P_CHG_TABS = 0xC615;
|
||||||
|
/**
|
||||||
|
* sprmPIlvl (§2.6.2, 1 байт): уровень списка 0..8; 0x0C — «пропустить,
|
||||||
|
* не нумеровать». Игнорируется, если абзац не в списке (sprmPIlfo=0).
|
||||||
|
*/
|
||||||
|
static final int SPRM_P_ILVL = 0x260A;
|
||||||
|
/**
|
||||||
|
* sprmPIlfo (§2.6.2, 2 байта, i16): 0/0xF801 — абзац не в списке;
|
||||||
|
* 1..0x07FE — 1-базированный индекс в PlfLfo.rgLfo; 0xF802..0xFFFF —
|
||||||
|
* отрицание индекса (список тот же, отступы абзаца сохраняются).
|
||||||
|
*/
|
||||||
|
static final int SPRM_P_ILFO = 0x460B;
|
||||||
|
|
||||||
|
// Table Properties (§2.6.3, sgc 5)
|
||||||
|
static final int SPRM_T_TABLE_BORDERS_80 = 0xD605;
|
||||||
|
static final int SPRM_T_DEF_TABLE = 0xD608;
|
||||||
|
static final int SPRM_T_TABLE_BORDERS = 0xD613;
|
||||||
|
/**
|
||||||
|
* sprmTJc (§2.6.3, 2 байта, u16): логическое выравнивание таблицы
|
||||||
|
* 0 = logical left, 1 = center, 2 = logical right (по умолчанию left).
|
||||||
|
* В LTR совпадает с физическим sprmTJc90; FOP complex-script не
|
||||||
|
* поддерживает (RTL вне контура репозитория) → единый маппинг.
|
||||||
|
*/
|
||||||
|
static final int SPRM_T_JC = 0x548A;
|
||||||
|
/**
|
||||||
|
* sprmTJc90 (§2.6.3, 2 байта, u16): физическое выравнивание таблицы
|
||||||
|
* (Word 6/95): 0 = physical left, 1 = center, 2 = physical right.
|
||||||
|
* Отличается от логического sprmTJc только в RTL/bidi (вне контура) →
|
||||||
|
* единый маппинг.
|
||||||
|
*/
|
||||||
|
static final int SPRM_T_JC90 = 0x5400;
|
||||||
|
|
||||||
|
// Section Properties (§2.6.4, 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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Накопитель абзацных отступов PAPX (§2.6.2) — общий для
|
||||||
|
* {@code DocxBody.paraProps} и {@code Lists.indXml} (grpprlPapx уровня).
|
||||||
|
*
|
||||||
|
* <p>Два семейства: современное (sprmPDxaLeft + sprmPNest) и 80-е
|
||||||
|
* (sprmPDxaLeft80 + sprmPNest80); nest прибавляется к СВОЕМУ dxaLeft.
|
||||||
|
* Если в grpprl встретился хоть один современный sprm левого отступа,
|
||||||
|
* 80-е семейство вытесняется целиком (защитный tie-break для смешанных
|
||||||
|
* PAPX: реальные документы несут одно семейство, sprmPNest supersede'ит
|
||||||
|
* sprmPNest80 внутри этого правила). right и left1 — слияние last-wins:
|
||||||
|
* 80-й и современный варианты имеют одинаковый смысл (правое поле;
|
||||||
|
* отступ первой строки относительно абзаца), побеждает последний Prl.</p>
|
||||||
|
*/
|
||||||
|
static final class Indents {
|
||||||
|
private int left;
|
||||||
|
private int nest;
|
||||||
|
private boolean modern;
|
||||||
|
private int left80;
|
||||||
|
private int nest80;
|
||||||
|
private int right = -1;
|
||||||
|
private int left1 = Integer.MIN_VALUE;
|
||||||
|
|
||||||
|
/** Кормить каждым Prl скана PAPX; не-отступные sprm игнорируются. */
|
||||||
|
void prl(int sprm, byte[] buf, int off, int len) {
|
||||||
|
switch (sprm) {
|
||||||
|
case SPRM_P_DXA_LEFT -> {
|
||||||
|
modern = true;
|
||||||
|
left = operandInt(buf, off, len);
|
||||||
|
}
|
||||||
|
case SPRM_P_NEST -> {
|
||||||
|
modern = true;
|
||||||
|
nest = operandInt(buf, off, len);
|
||||||
|
}
|
||||||
|
case SPRM_P_DXA_LEFT80 -> left80 = operandInt(buf, off, len);
|
||||||
|
case SPRM_P_NEST80 -> nest80 = operandInt(buf, off, len);
|
||||||
|
case SPRM_P_DXA_RIGHT, SPRM_P_DXA_RIGHT80 ->
|
||||||
|
right = operandInt(buf, off, len);
|
||||||
|
case SPRM_P_DXA_LEFT1, SPRM_P_DXA_LEFT180 ->
|
||||||
|
left1 = signedXas(buf, off, len);
|
||||||
|
default -> { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Итоговый w:left: dxaLeft + nest победившего семейства. */
|
||||||
|
int left() {
|
||||||
|
return modern ? left + nest : left80 + nest80;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** w:right; −1 — не задан. */
|
||||||
|
int right() {
|
||||||
|
return right;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** XAS со знаком; {@code Integer.MIN_VALUE} — не задан. */
|
||||||
|
int left1() {
|
||||||
|
return left1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** XAS-операнд со знаком (§2.6.2), приём DocxBody/Tables. */
|
||||||
|
private static int signedXas(byte[] buf, int off, int len) {
|
||||||
|
int v = operandInt(buf, off, len);
|
||||||
|
if (len == 2 && (v & 0x8000) != 0) {
|
||||||
|
v -= 0x10000;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Вызывается на каждый 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;
|
||||||
|
}
|
||||||
|
if (sprm == SPRM_T_DEF_TABLE) {
|
||||||
|
// TDefTableOperand (§2.9.321): cb (2 байта) = «размер
|
||||||
|
// остатка + 1» → весь операнд = cb + 1. Формула
|
||||||
|
// «1 + первый байт» совпадает только при cb < 256.
|
||||||
|
if (p + 2 > end) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int cb = (buf[p] & 0xFF) | ((buf[p + 1] & 0xFF) << 8);
|
||||||
|
if (cb < 2 || p + cb + 1 > end) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return cb + 1;
|
||||||
|
}
|
||||||
|
if (sprm == SPRM_P_CHG_TABS && (buf[p] & 0xFF) == 0xFF) {
|
||||||
|
// PChgTabsOperand (§2.9.182): cb=0xFF — длина по раскладке
|
||||||
|
// cb(1) + cTabsDel(1) + rgdxaDel(2n) + rgdxaClose(2n)
|
||||||
|
// + cTabsAdd(1) + rgdxaAdd(2m) + rgtbdAdd(m) = 3 + 4n + 3m.
|
||||||
|
// Обрыв (−1) — только если cTabsAdd не читается: иначе
|
||||||
|
// смещение разбора съедало бы следующие Prl.
|
||||||
|
if (p + 2 > end) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int n = buf[p + 1] & 0xFF;
|
||||||
|
if (p + 2 + 4 * n + 1 > end) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int m = buf[p + 2 + 4 * n] & 0xFF;
|
||||||
|
return 3 + 4 * n + 3 * m;
|
||||||
|
}
|
||||||
|
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,103 @@
|
|||||||
|
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 каждой секции как {@code type="default"}
|
||||||
|
* — FOP не различает чётные/нечётные страницы, а {@code titlePg} (первая
|
||||||
|
* страница) не поддерживается. История с {@code cpStart == cpEnd} не
|
||||||
|
* определена — часть и ссылка не эмитятся, docx4j наследует полосы
|
||||||
|
* предыдущей секции (§2.4.4 «Same as Previous»).</p>
|
||||||
|
*/
|
||||||
|
final class Headers {
|
||||||
|
|
||||||
|
/** CP-диапазон одной истории [cpStart, cpEnd); последний ¶ — guard-абзац. */
|
||||||
|
record Story(int cpStart, int cpEnd) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* История НЕ определена (§2.4.4: «Stories are considered empty if
|
||||||
|
* they have no contents and no guard paragraph mark … the beginning
|
||||||
|
* CP being the same as the next CP») — Word показывает полосы
|
||||||
|
* предыдущей секции (Same as Previous). Пустая часть с guard-¶ при
|
||||||
|
* этом НЕ empty(): это явно пустой колонтитул, обрывающий
|
||||||
|
* наследование.
|
||||||
|
*/
|
||||||
|
boolean empty() {
|
||||||
|
return cpStart == 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,437 @@
|
|||||||
|
package ru.pjandro.wordpdf.internal.doc;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Списки [MS-DOC]: PlfLst (§2.9.201) с приложенным массивом LVL (§2.9.149) →
|
||||||
|
* {@code w:abstractNum}, PlfLfo (§2.9.200) с LFO (§2.9.131)/LFOData
|
||||||
|
* (§2.9.132)/LFOLVL (§2.9.133) → {@code w:num} с {@code w:lvlOverride}.
|
||||||
|
* Результат — {@code word/numbering.xml} формы Word (эталон —
|
||||||
|
* samples/symbol-bullets.docx); порядок дочерних {@code w:lvl} — CT_Lvl
|
||||||
|
* (ECMA-376 Part 1, wml.xsd): start, numFmt, suff, lvlText, lvlJc, pPr, rPr.
|
||||||
|
*
|
||||||
|
* <p>Раскладки (выверены по §3 «Example of a List»): PlfLst — cLst SHORT
|
||||||
|
* (2 Б) при {@code fcPlfLst}, rgLstf начинается с {@code fcPlfLst+2}
|
||||||
|
* (§2.9.201, Figure 56); LSTF (28 Б, §2.9.147) —
|
||||||
|
* lsid(4)+tplc(4)+rgistdPara(18)+флаги(1: bit0 fSimpleList)+grfhic(1);
|
||||||
|
* LVL = LVLF (28 Б, §2.9.150: iStartAt u32, nfc u8, jc 2 бита+флаги,
|
||||||
|
* rgbxchNums 9, ixchFollow u8@15, cbGrpprlChpx u8@24, cbGrpprlPapx u8@25) +
|
||||||
|
* grpprlPapx + grpprlChpx + Xst (§2.9.353: cch u16 + cch×u16, символы
|
||||||
|
* 0x0000–0x0008 — плейсхолдеры уровней 0–8). Массив LVL приложен прямо за
|
||||||
|
* {@code fcPlfLst+lcbPlfLst} (lcb его НЕ включает); каждому LSTF достаётся
|
||||||
|
* 1 LVL при fSimpleList=1, иначе 9, порядок LSTF. LFO (16 Б) —
|
||||||
|
* lsid(4)+unused(8)+clfolvl u8@12+…; rgLfoData — параллельный массив
|
||||||
|
* LFOData{cp(4)+clfolvl×LFOLVL}; LFOLVL = iStartAt(4) + битполе (iLvl
|
||||||
|
* биты 0–3, fStartAt бит 4, fFormatting бит 5) + LVL при fFormatting=1.</p>
|
||||||
|
*
|
||||||
|
* <p>MSONFC (§2.9.150 nfc) → ST_NumberFormat (§17.18.59) по [MS-OSHARED]
|
||||||
|
* §2.2.1.3; экзотика (CJK, тайские и т.п.) → {@code decimal}: в бандле нет
|
||||||
|
* шрифтов с такими глифами, формат всё равно не отрисовать. Семантика
|
||||||
|
* рестартов (fNoRestart/ilvlRestartLim → {@code w:lvlRestart}), fLegal,
|
||||||
|
* dxaIndentSav и LfoData.cp не переносятся — осознанный остаток моста.</p>
|
||||||
|
*
|
||||||
|
* <p>Разбор снисходительный (образец {@link Styles}): битая/отсутствующая
|
||||||
|
* таблица или обрыв LVL — пустой/неполный результат без
|
||||||
|
* {@link ru.pjandro.wordpdf.ValidationException}; абзацы со ссылкой на
|
||||||
|
* несуществующий список деградируют в плоские.</p>
|
||||||
|
*/
|
||||||
|
final class Lists {
|
||||||
|
|
||||||
|
/** LSTF: lsid(4)+tplc(4)+rgistdPara(18)+флаги(1)+grfhic(1), §2.9.147. */
|
||||||
|
private static final int LSTF_SIZE = 28;
|
||||||
|
/** LVLF, §2.9.150. */
|
||||||
|
private static final int LVLF_SIZE = 28;
|
||||||
|
/** LFO, §2.9.131. */
|
||||||
|
private static final int LFO_SIZE = 16;
|
||||||
|
/** Число LVL у многоуровневого LSTF (§2.5.6 fcPlfLst). */
|
||||||
|
private static final int LEVEL_COUNT = 9;
|
||||||
|
/** Защита от враждебного cch в Xst (реальные xst — единицы символов). */
|
||||||
|
private static final int MAX_XST_CHARS = 1024;
|
||||||
|
/** Верхняя граница значения плейсхолдера уровня в xst (уровни 0–8, §2.9.149). */
|
||||||
|
private static final char PLACEHOLDER_MAX = 0x08;
|
||||||
|
/** Литеральный «%» в lvlText удваивается (lvlText, §17.9.11). */
|
||||||
|
private static final char PERCENT = '%';
|
||||||
|
/** Защита от враждебного lstfMac/lfoMac. */
|
||||||
|
private static final int MAX_ENTRIES = 65536;
|
||||||
|
|
||||||
|
/** Один LVL (§2.9.149): поля LVLF + сырые grpprl + строка xst. */
|
||||||
|
private record Level(int startAt, int nfc, int jc, int follow, byte[] papx, byte[] chpx,
|
||||||
|
String xst) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LSTF (§2.9.147) с его LVL (1 или 9; null-элемент — обрыв разбора). */
|
||||||
|
private record Lstf(int lsid, Level[] levels) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LFOLVL (§2.9.133): переопределение start-at и/или полный LVL. */
|
||||||
|
private record LfoLvl(int ilvl, int startAt, boolean startAtOverride, Level formatting) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LFO (§2.9.131) + rgLfoLvl параллельного LFOData (§2.9.132). */
|
||||||
|
private record Lfo(int lsid, LfoLvl[] overrides) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Lstf[] lstfs;
|
||||||
|
/** Индекс = ilfo−1 (sprmPIlfo — 1-базированный индекс в rgLfo). */
|
||||||
|
private final Lfo[] lfos;
|
||||||
|
/** lsid → индекс ПЕРВОГО LSTF с таким lsid. */
|
||||||
|
private final Map<Integer, Integer> lstfByLsid = new HashMap<>();
|
||||||
|
private final FontTable fonts;
|
||||||
|
|
||||||
|
private Lists(Lstf[] lstfs, Lfo[] lfos, FontTable fonts) {
|
||||||
|
this.lstfs = lstfs;
|
||||||
|
this.lfos = lfos;
|
||||||
|
this.fonts = fonts;
|
||||||
|
for (int i = 0; i < lstfs.length; i++) {
|
||||||
|
if (lstfs[i] != null) {
|
||||||
|
lstfByLsid.putIfAbsent(lstfs[i].lsid(), i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Таблицы списков из табличного потока; битые/нулевые lcb → пустой результат. */
|
||||||
|
static Lists read(byte[] table, long fcPlfLst, long lcbPlfLst, long fcPlfLfo,
|
||||||
|
long lcbPlfLfo, FontTable fonts) {
|
||||||
|
return new Lists(readPlfLst(table, fcPlfLst, lcbPlfLst),
|
||||||
|
readPlfLfo(table, fcPlfLfo, lcbPlfLfo), fonts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Есть ≥1 валидный abstractNum → есть смысл писать numbering-часть. */
|
||||||
|
boolean hasNumbering() {
|
||||||
|
for (Lstf lstf : lstfs) {
|
||||||
|
if (isValid(lstf)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** numId (1-базированный ilfo) разрешается в валидный abstractNum. */
|
||||||
|
boolean hasNum(int numId) {
|
||||||
|
return numId >= 1 && numId <= lfos.length && abstractIdOf(numId - 1) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** numbering.xml целиком (с XML-декларацией), форма Word. */
|
||||||
|
String numberingXml() {
|
||||||
|
StringBuilder xml = new StringBuilder(
|
||||||
|
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
|
||||||
|
.append("<w:numbering xmlns:w=\"http://schemas.openxmlformats.org")
|
||||||
|
.append("/wordprocessingml/2006/main\">");
|
||||||
|
for (int i = 0; i < lstfs.length; i++) {
|
||||||
|
if (!isValid(lstfs[i])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
xml.append("<w:abstractNum w:abstractNumId=\"").append(i + 1).append("\">");
|
||||||
|
Level[] levels = lstfs[i].levels();
|
||||||
|
for (int j = 0; j < levels.length; j++) {
|
||||||
|
if (levels[j] != null) {
|
||||||
|
xml.append(lvlXml(j, levels[j]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xml.append("</w:abstractNum>");
|
||||||
|
}
|
||||||
|
for (int i = 0; i < lfos.length; i++) {
|
||||||
|
int abstractId = abstractIdOf(i);
|
||||||
|
if (abstractId < 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
xml.append("<w:num w:numId=\"").append(i + 1).append("\">")
|
||||||
|
.append("<w:abstractNumId w:val=\"").append(abstractId).append("\"/>");
|
||||||
|
for (LfoLvl o : lfos[i].overrides()) {
|
||||||
|
if (o == null || o.ilvl() > 8) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
xml.append("<w:lvlOverride w:ilvl=\"").append(o.ilvl()).append("\">");
|
||||||
|
if (o.formatting() != null) {
|
||||||
|
xml.append(lvlXml(o.ilvl(), o.formatting()));
|
||||||
|
} else if (o.startAtOverride()) {
|
||||||
|
xml.append("<w:startOverride w:val=\"").append(o.startAt()).append("\"/>");
|
||||||
|
}
|
||||||
|
xml.append("</w:lvlOverride>");
|
||||||
|
}
|
||||||
|
xml.append("</w:num>");
|
||||||
|
}
|
||||||
|
return xml.append("</w:numbering>").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** abstractNumId (1-базированный индекс LSTF) для LFO; −1 — нет валидного. */
|
||||||
|
private int abstractIdOf(int lfoIndex) {
|
||||||
|
// lfos[·] всегда непустой: readPlfLfo присваивает out[i] до обхода LFOData
|
||||||
|
Integer lstfIndex = lstfByLsid.get(lfos[lfoIndex].lsid());
|
||||||
|
if (lstfIndex == null || !isValid(lstfs[lstfIndex])) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return lstfIndex + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isValid(Lstf lstf) {
|
||||||
|
return lstf != null && lstf.levels().length > 0 && lstf.levels()[0] != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- разбор PlfLst ---------------------------------------------------
|
||||||
|
|
||||||
|
private static Lstf[] readPlfLst(byte[] table, long fc, long lcb) {
|
||||||
|
if (lcb <= 0 || fc < 0 || fc + 4 > table.length) {
|
||||||
|
return new Lstf[0];
|
||||||
|
}
|
||||||
|
long end = Math.min(fc + lcb, table.length);
|
||||||
|
// cLst — SHORT (§2.9.201): знаковое прочтение; ≥ 0x8000 → отрицательное
|
||||||
|
// (битое) → ветка mac <= 0
|
||||||
|
int mac = (short) CfbReader.u16(table, (int) fc);
|
||||||
|
if (mac <= 0) {
|
||||||
|
return new Lstf[0];
|
||||||
|
}
|
||||||
|
int fit = (int) ((end - fc - 2) / LSTF_SIZE);
|
||||||
|
mac = Math.min(Math.min(mac, fit), MAX_ENTRIES);
|
||||||
|
Lstf[] out = new Lstf[mac];
|
||||||
|
// массив LVL приложен за PlfLst (lcb его не включает, §2.5.6)
|
||||||
|
int cursor = (int) Math.min(fc + lcb, (long) table.length);
|
||||||
|
for (int i = 0; i < mac; i++) {
|
||||||
|
int rec = (int) fc + 2 + i * LSTF_SIZE;
|
||||||
|
int lsid = (int) CfbReader.u32(table, rec);
|
||||||
|
boolean simple = (table[rec + 26] & 1) != 0;
|
||||||
|
Level[] levels = new Level[simple ? 1 : LEVEL_COUNT];
|
||||||
|
for (int j = 0; j < levels.length; j++) {
|
||||||
|
Level lv = readLevel(table, cursor);
|
||||||
|
if (lv == null) {
|
||||||
|
// обрыв: этот LSTF — с разобранными уровнями, остальные — без
|
||||||
|
out[i] = new Lstf(lsid, levels);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
levels[j] = lv;
|
||||||
|
cursor += levelSize(lv);
|
||||||
|
}
|
||||||
|
out[i] = new Lstf(lsid, levels);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LVL по {@code at}; null — поля за пределами потока. */
|
||||||
|
private static Level readLevel(byte[] table, int at) {
|
||||||
|
if (at < 0 || at + LVLF_SIZE > table.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int startAt = (int) CfbReader.u32(table, at);
|
||||||
|
int nfc = table[at + 4] & 0xFF;
|
||||||
|
int jc = table[at + 5] & 0x03;
|
||||||
|
int follow = table[at + 15] & 0xFF;
|
||||||
|
int cbChpx = table[at + 24] & 0xFF;
|
||||||
|
int cbPapx = table[at + 25] & 0xFF;
|
||||||
|
int p = at + LVLF_SIZE;
|
||||||
|
if (p + cbPapx + cbChpx > table.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
byte[] papx = slice(table, p, cbPapx);
|
||||||
|
p += cbPapx;
|
||||||
|
byte[] chpx = slice(table, p, cbChpx);
|
||||||
|
p += cbChpx;
|
||||||
|
if (p + 2 > table.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int cch = CfbReader.u16(table, p);
|
||||||
|
p += 2;
|
||||||
|
if (cch > MAX_XST_CHARS || p + 2 * cch > table.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String xst = new String(table, p, 2 * cch, StandardCharsets.UTF_16LE);
|
||||||
|
return new Level(startAt, nfc, jc, follow, papx, chpx, xst);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Полный размер LVL: LVLF + grpprl'ы + Xst (cch + символы). */
|
||||||
|
private static int levelSize(Level lv) {
|
||||||
|
return LVLF_SIZE + lv.papx().length + lv.chpx().length + 2 + lv.xst().length() * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- разбор PlfLfo ---------------------------------------------------
|
||||||
|
|
||||||
|
private static Lfo[] readPlfLfo(byte[] table, long fc, long lcb) {
|
||||||
|
// lcbPlfLfo=0 → fcPlfLfo не определён и MUST быть проигнорирован (§2.5.6)
|
||||||
|
if (lcb <= 0 || fc < 0 || fc + 4 > table.length) {
|
||||||
|
return new Lfo[0];
|
||||||
|
}
|
||||||
|
long end = Math.min(fc + lcb, table.length);
|
||||||
|
int mac = (int) CfbReader.u32(table, (int) fc);
|
||||||
|
if (mac <= 0) {
|
||||||
|
return new Lfo[0];
|
||||||
|
}
|
||||||
|
int fit = (int) ((end - fc - 4) / LFO_SIZE);
|
||||||
|
mac = Math.min(Math.min(mac, fit), MAX_ENTRIES);
|
||||||
|
Lfo[] out = new Lfo[mac];
|
||||||
|
int cursor = (int) (fc + 4) + mac * LFO_SIZE;
|
||||||
|
for (int i = 0; i < mac; i++) {
|
||||||
|
int rec = (int) fc + 4 + i * LFO_SIZE;
|
||||||
|
int lsid = (int) CfbReader.u32(table, rec);
|
||||||
|
int clfolvl = table[rec + 12] & 0xFF;
|
||||||
|
LfoLvl[] overrides = new LfoLvl[clfolvl];
|
||||||
|
out[i] = new Lfo(lsid, overrides);
|
||||||
|
if (cursor + 4 > table.length) {
|
||||||
|
return out; // обрыв LFOData — остаток без переопределений
|
||||||
|
}
|
||||||
|
cursor += 4; // cp — не переносится (осознанный остаток)
|
||||||
|
for (int j = 0; j < clfolvl; j++) {
|
||||||
|
if (cursor + 8 > table.length) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
int startAt = (int) CfbReader.u32(table, cursor);
|
||||||
|
int bits = (int) CfbReader.u32(table, cursor + 4);
|
||||||
|
cursor += 8;
|
||||||
|
int ilvl = bits & 0xF;
|
||||||
|
boolean fStartAt = (bits >>> 4 & 1) != 0;
|
||||||
|
boolean fFormatting = (bits >>> 5 & 1) != 0;
|
||||||
|
Level formatting = null;
|
||||||
|
if (fFormatting) {
|
||||||
|
formatting = readLevel(table, cursor);
|
||||||
|
if (formatting == null) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
cursor += levelSize(formatting);
|
||||||
|
}
|
||||||
|
overrides[j] = new LfoLvl(ilvl, startAt, fStartAt, formatting);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- эмит numbering.xml ------------------------------------------------
|
||||||
|
|
||||||
|
/** w:lvl по CT_Lvl: start, numFmt, suff, lvlText, lvlJc, pPr, rPr. */
|
||||||
|
private String lvlXml(int ilvl, Level lv) {
|
||||||
|
StringBuilder xml = new StringBuilder("<w:lvl w:ilvl=\"").append(ilvl).append("\">");
|
||||||
|
xml.append("<w:start w:val=\"").append(Math.max(lv.startAt(), 0)).append("\"/>");
|
||||||
|
xml.append("<w:numFmt w:val=\"").append(numFmt(lv.nfc())).append("\"/>");
|
||||||
|
String suff = switch (lv.follow()) {
|
||||||
|
case 1 -> "space";
|
||||||
|
case 2 -> "nothing";
|
||||||
|
default -> null; // 0 = tab — дефолт ST_LvlSuff, не эмитится
|
||||||
|
};
|
||||||
|
if (suff != null) {
|
||||||
|
xml.append("<w:suff w:val=\"").append(suff).append("\"/>");
|
||||||
|
}
|
||||||
|
xml.append("<w:lvlText w:val=\"").append(escapeAttr(lvlText(lv.xst()))).append("\"/>");
|
||||||
|
String jc = switch (lv.jc()) {
|
||||||
|
case 1 -> "center";
|
||||||
|
case 2 -> "right";
|
||||||
|
default -> "left";
|
||||||
|
};
|
||||||
|
xml.append("<w:lvlJc w:val=\"").append(jc).append("\"/>");
|
||||||
|
String ind = indXml(lv.papx());
|
||||||
|
if (!ind.isEmpty()) {
|
||||||
|
xml.append("<w:pPr>").append(ind).append("</w:pPr>");
|
||||||
|
}
|
||||||
|
String rPr = rPrXml(lv.chpx());
|
||||||
|
if (!rPr.isEmpty()) {
|
||||||
|
xml.append("<w:rPr>").append(rPr).append("</w:rPr>");
|
||||||
|
}
|
||||||
|
return xml.append("</w:lvl>").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** xst → ST_NumberText: плейсхолдеры 0x00–0x08 → %{n+1}, «%» → «%%». */
|
||||||
|
private static String lvlText(String xst) {
|
||||||
|
StringBuilder out = new StringBuilder(xst.length() + 8);
|
||||||
|
for (int i = 0; i < xst.length(); i++) {
|
||||||
|
char ch = xst.charAt(i);
|
||||||
|
if (ch <= PLACEHOLDER_MAX) {
|
||||||
|
out.append(PERCENT).append(ch + 1);
|
||||||
|
} else if (ch == PERCENT) {
|
||||||
|
out.append("%%");
|
||||||
|
} else {
|
||||||
|
out.append(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** MSONFC ([MS-OSHARED] §2.2.1.3) → ST_NumberFormat (§17.18.59). */
|
||||||
|
private static String numFmt(int nfc) {
|
||||||
|
return switch (nfc) {
|
||||||
|
case 0x00 -> "decimal";
|
||||||
|
case 0x01 -> "upperRoman";
|
||||||
|
case 0x02 -> "lowerRoman";
|
||||||
|
case 0x03 -> "upperLetter";
|
||||||
|
case 0x04 -> "lowerLetter";
|
||||||
|
case 0x05 -> "ordinal";
|
||||||
|
case 0x06 -> "cardinalText";
|
||||||
|
case 0x07 -> "ordinalText";
|
||||||
|
case 0x16 -> "decimalZero";
|
||||||
|
case 0x17 -> "bullet";
|
||||||
|
case 0x39 -> "numberInDash";
|
||||||
|
case 0x3A -> "russianLower";
|
||||||
|
case 0x3B -> "russianUpper";
|
||||||
|
case 0xFF -> "none";
|
||||||
|
// экзотика (CJK/тайские/индийские…): в бандле нет шрифтов с такими
|
||||||
|
// глифами — decimal хотя бы читается
|
||||||
|
default -> "decimal";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** w:ind уровня из grpprlPapx (общий накопитель {@link Grpprl.Indents},
|
||||||
|
* те же XAS-семантики и 80-варианты, что paraProps). */
|
||||||
|
private static String indXml(byte[] papx) {
|
||||||
|
Grpprl.Indents ind = new Grpprl.Indents();
|
||||||
|
Grpprl.scan(papx, 0, papx.length, ind::prl);
|
||||||
|
int left = ind.left();
|
||||||
|
int left1 = ind.left1();
|
||||||
|
StringBuilder xml = new StringBuilder();
|
||||||
|
if (left > 0) {
|
||||||
|
xml.append(" w:left=\"").append(left).append('"');
|
||||||
|
}
|
||||||
|
if (left1 != Integer.MIN_VALUE && left1 != 0) {
|
||||||
|
if (left1 > 0) {
|
||||||
|
xml.append(" w:firstLine=\"").append(left1).append('"');
|
||||||
|
} else {
|
||||||
|
xml.append(" w:hanging=\"").append(-left1).append('"');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return xml.length() == 0 ? "" : "<w:ind" + xml + "/>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** w:rPr метки уровня из grpprlChpx: rFonts (Symbol/Wingdings-буллеты), b, sz. */
|
||||||
|
private String rPrXml(byte[] chpx) {
|
||||||
|
int[] ftc0 = {-1};
|
||||||
|
boolean[] bold = {false};
|
||||||
|
int[] hps = {0};
|
||||||
|
Grpprl.scan(chpx, 0, chpx.length, (sprm, buf, off, len) -> {
|
||||||
|
switch (sprm) {
|
||||||
|
case Grpprl.SPRM_C_RG_FTC0 -> ftc0[0] = Grpprl.operandInt(buf, off, len);
|
||||||
|
case Grpprl.SPRM_C_F_BOLD -> bold[0] = Grpprl.toggleOn(buf, off);
|
||||||
|
case Grpprl.SPRM_C_HPS -> hps[0] = Grpprl.operandInt(buf, off, len);
|
||||||
|
default -> { }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
StringBuilder xml = new StringBuilder();
|
||||||
|
String family = ftc0[0] >= 0 ? fonts.font(ftc0[0]) : null;
|
||||||
|
if (family != null) {
|
||||||
|
xml.append("<w:rFonts w:ascii=\"").append(escapeAttr(family))
|
||||||
|
.append("\" w:hAnsi=\"").append(escapeAttr(family)).append("\"/>");
|
||||||
|
}
|
||||||
|
if (bold[0]) {
|
||||||
|
xml.append("<w:b/>");
|
||||||
|
}
|
||||||
|
if (hps[0] > 0) {
|
||||||
|
xml.append("<w:sz w:val=\"").append(hps[0]).append("\"/>");
|
||||||
|
}
|
||||||
|
return xml.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();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] slice(byte[] src, int from, int len) {
|
||||||
|
byte[] out = new byte[len];
|
||||||
|
System.arraycopy(src, from, out, 0, len);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,115 @@
|
|||||||
|
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 сохраняется ({@link #istdFor}) — по нему {@link DocxBody} применяет
|
||||||
|
* цепочку стилей {@link Styles}.</p>
|
||||||
|
*/
|
||||||
|
final class PapxIndex {
|
||||||
|
|
||||||
|
private static final int FKP_PAGE_SIZE = 512;
|
||||||
|
|
||||||
|
private record Range(long fcStart, long fcEnd, byte[] grpprl, int istd) {
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
// grpprlLen==0 допустим: istd без прямых Prl (стиль — единственное свойство)
|
||||||
|
if (grpprlLen < 0 || stdStart + 2 + grpprlLen > pageOff + FKP_PAGE_SIZE) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
byte[] grpprl = new byte[grpprlLen];
|
||||||
|
System.arraycopy(wordDocument, stdStart + 2, grpprl, 0, grpprlLen);
|
||||||
|
int istd = CfbReader.u16(wordDocument, stdStart);
|
||||||
|
ranges.add(new Range(Math.max(rgfcStart, fcStart), Math.min(rgfcEnd, fcEnd),
|
||||||
|
grpprl, istd));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** istd абзаца, содержащего FC (§2.9.175 GrpPrlAndIstd); -1 — диапазона нет. */
|
||||||
|
int istdFor(long fc) {
|
||||||
|
for (Range r : ranges) {
|
||||||
|
if (fc >= r.fcStart() && fc < r.fcEnd()) {
|
||||||
|
return r.istd();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Число абзацев с 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,210 @@
|
|||||||
|
package ru.pjandro.wordpdf.internal.doc;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
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;
|
||||||
|
* Sed секции i описывает секцию от aCP[i] до aCP[i+1] (§3, Figure 13: «The
|
||||||
|
* last character in the first section is at position 10, and has a value of
|
||||||
|
* 0x0C»). Дубликаты aCP запрещены (§2.8.26 «MUST NOT contain duplicate
|
||||||
|
* CPs»); финальный aCP в реальных файлах Word лежит за ccpText (PLC
|
||||||
|
* покрывает весь текстовый поток), поэтому конец последней секции
|
||||||
|
* клампится к ccpText. Свойств в Sepx нет (или Sepx битый) — дефолты
|
||||||
|
* Word 97: Letter 12240×15840, поля 1440, колонтитуки
|
||||||
|
* 720 (значения §2.6.3 «By default» для sprmSXaPage/sprmSYaPage).</p>
|
||||||
|
*
|
||||||
|
* <p>{@link Section#continuous()} — sprmSBkc секции со значением
|
||||||
|
* bkcContinuous/bkcNewColumn (§2.6.3, SBkcOperand: «the type of the section
|
||||||
|
* break that terminates the section»), т.е. разрыв, ЗАКАНЧИВАЮЩИЙ эту
|
||||||
|
* секцию. В OOXML {@code w:type} описывает разрыв ПЕРЕД секцией (§17.6.22),
|
||||||
|
* поэтому {@code w:type} секции i берётся из {@code continuous()} секции
|
||||||
|
* i−1 — см. {@code DocxBody#sectPrXml}.</p>
|
||||||
|
*
|
||||||
|
* <p>{@link #continuousSectionEnds()} — число межсекционных разрывов, не
|
||||||
|
* начинающих новую страницу (дефолт — bkcNewPage, поэтому отсутствие
|
||||||
|
* sprmSBkc не вычитается).</p>
|
||||||
|
*/
|
||||||
|
final class Sections {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Одна секция: CP-диапазон [cpStart, cpEnd) (у всех, кроме последней,
|
||||||
|
* финальный символ — 0x0C, §2.8.26) + геометрия из её Sepx + признак
|
||||||
|
* «разрыв, заканчивающий секцию, не начинает новую страницу».
|
||||||
|
*/
|
||||||
|
record Section(int cpStart, int cpEnd, int pageWidth, int pageHeight,
|
||||||
|
int marginLeft, int marginRight, int marginTop, int marginBottom,
|
||||||
|
int header, int footer, boolean continuous) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Дефолты 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 final List<Section> sections;
|
||||||
|
private final int continuousEnds;
|
||||||
|
|
||||||
|
/** Геометрия одной секции в процессе разбора Sepx (дефолты Word 97). */
|
||||||
|
private static final class SedGeom {
|
||||||
|
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 boolean continuous;
|
||||||
|
|
||||||
|
private void apply(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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Sections(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument,
|
||||||
|
int ccpText) {
|
||||||
|
if (lcbSed <= 0) {
|
||||||
|
// нет PlcfSed — одна неявная секция [0, ccpText) с дефолтами
|
||||||
|
sections = List.of(defaultSection(0, ccpText));
|
||||||
|
continuousEnds = 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[] aCp = new int[n + 1];
|
||||||
|
for (int i = 0; i <= n; i++) {
|
||||||
|
long cp = CfbReader.u32(tableStream, (int) fcSed + i * 4);
|
||||||
|
if (i > 0 && cp <= aCp[i - 1]) {
|
||||||
|
throw new ValidationException("Невозрастающие aCP в PlcfSed .doc");
|
||||||
|
}
|
||||||
|
aCp[i] = (int) cp;
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
sections = List.of(defaultSection(0, ccpText));
|
||||||
|
continuousEnds = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int sedBase = (int) fcSed + (n + 1) * 4;
|
||||||
|
List<Section> list = new ArrayList<>(n);
|
||||||
|
int cont = 0;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
SedGeom g = new SedGeom();
|
||||||
|
long fcSepx = CfbReader.u32(tableStream, sedBase + i * SED_SIZE + SED_OFF_FC_SEPX);
|
||||||
|
if (fcSepx != 0 && fcSepx + 2 <= wordDocument.length) {
|
||||||
|
int cb = (int) (CfbReader.u32(wordDocument, (int) fcSepx) & 0xFFFF);
|
||||||
|
if (cb > 0 && fcSepx + 2 + cb <= wordDocument.length) {
|
||||||
|
Grpprl.scan(wordDocument, (int) fcSepx + 2, cb, (sprm, buf, off, len) -> {
|
||||||
|
int v = Grpprl.operandInt(buf, off, len);
|
||||||
|
g.apply(sprm, v);
|
||||||
|
// bkcContinuous=0 / bkcNewColumn=1 (§2.6.3 SBkcOperand):
|
||||||
|
// разрыв, заканчивающий секцию, не начинает страницу
|
||||||
|
if (sprm == Grpprl.SPRM_S_BKC && v <= 1) {
|
||||||
|
g.continuous = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (i < n - 1 && g.continuous) {
|
||||||
|
cont++;
|
||||||
|
}
|
||||||
|
// финальный aCP реальные файлы Word пишут за ccpText (page-numbers.doc:
|
||||||
|
// aCp[1]=108 при ccpText=33 — PLC покрывает весь текстовый поток),
|
||||||
|
// верхний guard невозможен; конец последней секции — ccpText
|
||||||
|
int cpEnd = i == n - 1 ? Math.min(aCp[i + 1], ccpText) : aCp[i + 1];
|
||||||
|
list.add(new Section(aCp[i], cpEnd, g.pageWidth, g.pageHeight,
|
||||||
|
g.marginLeft, g.marginRight, g.marginTop, g.marginBottom,
|
||||||
|
g.header, g.footer, g.continuous));
|
||||||
|
}
|
||||||
|
sections = List.copyOf(list);
|
||||||
|
continuousEnds = cont;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Section defaultSection(int cpStart, int cpEnd) {
|
||||||
|
return new Section(cpStart, cpEnd, DEFAULT_PAGE_WIDTH, DEFAULT_PAGE_HEIGHT,
|
||||||
|
DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN,
|
||||||
|
DEFAULT_HEADER_FOOTER, DEFAULT_HEADER_FOOTER, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Sections read(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument,
|
||||||
|
int ccpText) {
|
||||||
|
return new Sections(tableStream, fcSed, lcbSed, wordDocument, ccpText);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Все секции по aCP PlcfSed; при отсутствии PlcfSed — одна неявная. */
|
||||||
|
List<Section> list() {
|
||||||
|
return sections;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Одиночные аксессоры — геометрия ПОСЛЕДНЕЙ секции (подсчёт страниц).
|
||||||
|
|
||||||
|
int pageWidth() {
|
||||||
|
return last().pageWidth();
|
||||||
|
}
|
||||||
|
|
||||||
|
int pageHeight() {
|
||||||
|
return last().pageHeight();
|
||||||
|
}
|
||||||
|
|
||||||
|
int marginLeft() {
|
||||||
|
return last().marginLeft();
|
||||||
|
}
|
||||||
|
|
||||||
|
int marginRight() {
|
||||||
|
return last().marginRight();
|
||||||
|
}
|
||||||
|
|
||||||
|
int marginTop() {
|
||||||
|
return last().marginTop();
|
||||||
|
}
|
||||||
|
|
||||||
|
int marginBottom() {
|
||||||
|
return last().marginBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
int header() {
|
||||||
|
return last().header();
|
||||||
|
}
|
||||||
|
|
||||||
|
int footer() {
|
||||||
|
return last().footer();
|
||||||
|
}
|
||||||
|
|
||||||
|
int continuousSectionEnds() {
|
||||||
|
return continuousEnds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Section last() {
|
||||||
|
return sections.get(sections.size() - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package ru.pjandro.wordpdf.internal.doc;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Таблица стилей STSH ([MS-DOC] §2.9.271) и цепочки наследования
|
||||||
|
* (§2.4.6.5 «Determining Properties of a Style»).
|
||||||
|
*
|
||||||
|
* <p>Разбор: LPStshi (cbStshi(2) + STSHI: cstd(2) + cbSTDBaseInFile(2),
|
||||||
|
* §2.9.272/.274) → rglpstd со смещения {@code fc + 2 + cbStshi} (LPStd
|
||||||
|
* хранятся на чётных границах, §2.9.207). Каждая LPStd: cbStd(2) + Std
|
||||||
|
* (cbStd байт): stdf (cbSTDBaseInFile байт: StdfBase §2.9.260 — в первых
|
||||||
|
* 4 байтах sti(12)|A–D(4)|stk(4)|istdBase(12), cupx — младший нибл байта 4)
|
||||||
|
* + xstzName (cch(2)+2·cch+терминатор(2), §2.9.348) + cupx × LPUpx
|
||||||
|
* (cbUpx(2) + данные, шаг 2+cbUpx с выравниванием на чёт). Для stk=1
|
||||||
|
* (абзацный стиль) UPX[0] = UpxPapx (istd(2) + grpprlPapx), UPX[1] =
|
||||||
|
* UpxChpx (grpprlChpx целиком), §2.9.267/.308/.309.</p>
|
||||||
|
*
|
||||||
|
* <p>Цепочка свойств стиля — base-first: сначала grpprl предка по
|
||||||
|
* istdBase (0x0FFF — без предка), затем собственный grpprl (шаг 8
|
||||||
|
* «Determining Properties of a Style» в порядке применения last-wins:
|
||||||
|
* производный стиль перекрывает базовый). istdBase обязан ссылаться на
|
||||||
|
* непустой стиль и не создавать циклов (§2.9.260); глубина > 16 — обрыв
|
||||||
|
* цепочки (защита от битого файла).</p>
|
||||||
|
*
|
||||||
|
* <p>Разбор снисходительный (образец {@link FontTable}): битый/отсутствующий
|
||||||
|
* STSH не роняет конвертацию — документ рендерится на прямых свойствах,
|
||||||
|
* {@link ValidationException} не бросается.</p>
|
||||||
|
*/
|
||||||
|
final class Styles {
|
||||||
|
|
||||||
|
/** stk абзацного стиля (§2.9.260). */
|
||||||
|
private static final int STK_PARAGRAPH = 1;
|
||||||
|
/** Индекс UpxPapx в Std абзацного стиля (§2.9.308). */
|
||||||
|
private static final int UPX_PAPX = 0;
|
||||||
|
/** Индекс UpxChpx в Std абзацного стиля (§2.9.309). */
|
||||||
|
private static final int UPX_CHPX = 1;
|
||||||
|
/** istdBase без предка (§2.9.260). */
|
||||||
|
private static final int NO_BASE = 0x0FFF;
|
||||||
|
/** Защита от цикла в istdBase. */
|
||||||
|
private static final int MAX_CHAIN = 16;
|
||||||
|
|
||||||
|
/** Один стиль: предка + собственные grpprl'ы (пустые массивы — нет). */
|
||||||
|
private record Style(int istdBase, byte[] papx, byte[] chpx) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Style[] styles;
|
||||||
|
|
||||||
|
private Styles(byte[] table, long fc, long lcb) {
|
||||||
|
Style[] parsed;
|
||||||
|
try {
|
||||||
|
parsed = readAll(table, fc, lcb);
|
||||||
|
} catch (RuntimeException broken) {
|
||||||
|
parsed = new Style[0];
|
||||||
|
}
|
||||||
|
styles = parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Style[] readAll(byte[] table, long fc, long lcb) {
|
||||||
|
if (lcb <= 0 || fc < 0 || fc + 6 > table.length) {
|
||||||
|
return new Style[0];
|
||||||
|
}
|
||||||
|
int cbStshi = CfbReader.u16(table, (int) fc);
|
||||||
|
int cstd = CfbReader.u16(table, (int) fc + 2);
|
||||||
|
int cbStdf = CfbReader.u16(table, (int) fc + 4);
|
||||||
|
if (cstd <= 0 || cstd >= 0x0FFE || cbStdf < 5 || cbStshi < 4) {
|
||||||
|
return new Style[0];
|
||||||
|
}
|
||||||
|
int pos = (int) (fc + 2 + cbStshi);
|
||||||
|
if ((pos & 1) != 0) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
int end = (int) (fc + lcb);
|
||||||
|
Style[] out = new Style[cstd];
|
||||||
|
for (int istd = 0; istd < cstd; istd++) {
|
||||||
|
if (pos + 2 > end) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
int cbStd = CfbReader.u16(table, pos);
|
||||||
|
pos += 2;
|
||||||
|
if (cbStd <= 0) {
|
||||||
|
continue; // пустой стиль (§2.9.271)
|
||||||
|
}
|
||||||
|
if (pos + cbStd > end) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out[istd] = readStd(table, pos, cbStd, cbStdf);
|
||||||
|
pos += cbStd;
|
||||||
|
if ((pos & 1) != 0) {
|
||||||
|
pos++; // LPStd на чётной границе, padding в cbStd не входит
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Std по {@code std}: stdf + xstzName + cupx × LPUpx. */
|
||||||
|
private static Style readStd(byte[] table, int std, int cbStd, int cbStdf) {
|
||||||
|
int stdEnd = std + cbStd;
|
||||||
|
long base = CfbReader.u32(table, std);
|
||||||
|
int stk = (int) ((base >>> 16) & 0xF);
|
||||||
|
int istdBase = (int) ((base >>> 20) & 0xFFF);
|
||||||
|
int cupx = table[std + 4] & 0xF;
|
||||||
|
int p = std + cbStdf;
|
||||||
|
if (p + 2 > stdEnd) {
|
||||||
|
return new Style(NO_BASE, new byte[0], new byte[0]);
|
||||||
|
}
|
||||||
|
int cch = CfbReader.u16(table, p);
|
||||||
|
p += 2 + 2 * cch + 2; // xstzName: cch + строка + chTerm (§2.9.348)
|
||||||
|
byte[] papx = new byte[0];
|
||||||
|
byte[] chpx = new byte[0];
|
||||||
|
for (int i = 0; i < cupx && p + 2 <= stdEnd; i++) {
|
||||||
|
int cbUpx = CfbReader.u16(table, p);
|
||||||
|
p += 2;
|
||||||
|
if (p + cbUpx > stdEnd) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (stk == STK_PARAGRAPH) {
|
||||||
|
if (i == UPX_PAPX && cbUpx >= 2) {
|
||||||
|
// UpxPapx: istd(2) + grpprlPapx (§2.9.345)
|
||||||
|
papx = slice(table, p + 2, cbUpx - 2);
|
||||||
|
} else if (i == UPX_CHPX) {
|
||||||
|
chpx = slice(table, p, cbUpx); // UpxChpx (§2.9.343)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p += cbUpx;
|
||||||
|
if ((p & 1) != 0) {
|
||||||
|
p++; // LPUpx выровнены на чёт, padding в cbUpx не входит
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Style(istdBase, papx, chpx);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] slice(byte[] src, int from, int len) {
|
||||||
|
byte[] out = new byte[len];
|
||||||
|
System.arraycopy(src, from, out, 0, len);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Таблица по {@code fcStshf} из табличного потока; битый STSH → пустая. */
|
||||||
|
static Styles read(byte[] tableStream, long fc, long lcb) {
|
||||||
|
return new Styles(tableStream, fc, lcb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Число стилей (для проверки границ istd из sprmPIstd). */
|
||||||
|
int count() {
|
||||||
|
return styles.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Grpprl абзацных свойств стиля со всей цепочкой предков (base-first). */
|
||||||
|
byte[] papxChain(int istd) {
|
||||||
|
return chain(istd, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Grpprl символьных свойств стиля со всей цепочкой предков (base-first). */
|
||||||
|
byte[] chpxChain(int istd) {
|
||||||
|
return chain(istd, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] chain(int istd, boolean papx) {
|
||||||
|
byte[] own = new byte[0];
|
||||||
|
int depth = 0;
|
||||||
|
while (istd >= 0 && istd < styles.length && styles[istd] != null && depth++ < MAX_CHAIN) {
|
||||||
|
Style s = styles[istd];
|
||||||
|
own = concat(papx ? s.papx() : s.chpx(), own);
|
||||||
|
if (s.istdBase() == NO_BASE) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
istd = s.istdBase();
|
||||||
|
}
|
||||||
|
return own;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] concat(byte[] a, byte[] b) {
|
||||||
|
if (a.length == 0) {
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
if (b.length == 0) {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
byte[] out = new byte[a.length + b.length];
|
||||||
|
System.arraycopy(a, 0, out, 0, a.length);
|
||||||
|
System.arraycopy(b, 0, out, a.length, b.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
package ru.pjandro.wordpdf.internal.doc;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Разбор TAP (Table Properties) TTP-абзаца строки → сетка и границы таблицы.
|
||||||
|
*
|
||||||
|
* <p>[MS-DOC] §2.6.3: {@code sprmTDefTable} (0xD608) — TDefTableOperand
|
||||||
|
* (§2.9.321): cb(2, «остаток+1») + NumberOfColumns(1, ≤63) + rgdxaCenter
|
||||||
|
* ((ncols+1) × XAS со знаком: первый — левый край таблицы от поля, далее
|
||||||
|
* правые края колонок) + rgTc80. Ширина колонки i = center[i+1] − center[i].
|
||||||
|
* Границы строки: {@code sprmTTableBorders} (0xD613) — TableBordersOperand
|
||||||
|
* (§2.9.302, cb=0x30, 6 × Brc по 8 байт: cv COLORREF + dptLineWidth +
|
||||||
|
* brcType + флаги), иначе {@code sprmTTableBorders80} (0xD605) —
|
||||||
|
* TableBordersOperand80 (§2.9.303, cb=0x18, 6 × Brc80 по 4 байта:
|
||||||
|
* dptLineWidth + brcType + ico + флаги). Порядок Brc: top, left, bottom,
|
||||||
|
* right, horizontalInside, verticalInside → w:top/w:left/w:bottom/w:right/
|
||||||
|
* w:insideH/w:insideV (CT_TblBorders, ECMA-376 §17.4.40).</p>
|
||||||
|
*
|
||||||
|
* <p>brcType → ST_Border (§17.18.2) по таблице BrcType ([MS-DOC] §2.9.39,
|
||||||
|
* колонка Reference); 0x00 — элемент не эмитится, нераспознанный — single.
|
||||||
|
* w:sz = dptLineWidth (1/8 пункта, ECMA-376 §17.18.15; минимум 2; при
|
||||||
|
* brcType ≥ 0x40 ширина в целых пунктах → ×8). Цвет: Brc.cv fAuto
|
||||||
|
* (байт 3 = 0xFF) не эмитится, иначе RRGGBB; Brc80.ico — по таблице Ico
|
||||||
|
* (§2.9.171); 0 = auto, > 0x10 — не эмитится.</p>
|
||||||
|
*
|
||||||
|
* <p>Вне контура (деградация {@code null} / молчаливый пропуск): вложенные
|
||||||
|
* таблицы (sprmPFInnerTtp), объединённые ячейки (vertMerge, sprmTInsert),
|
||||||
|
* отступы между ячейками (sprmTDxaCellSpacing), бордюры уровня ячейки
|
||||||
|
* (TC80/sprmTCellBorders) — только строковые границы 0xD613/0xD605.</p>
|
||||||
|
*/
|
||||||
|
final class Tables {
|
||||||
|
|
||||||
|
/** brcType ≥ этого порога: dptLineWidth задан в целых пунктах (§2.9.38). */
|
||||||
|
private static final int BRC_TYPE_POINT_UNITS = 0x40;
|
||||||
|
/** Минимальный w:sz границы; значения Brc80 меньше эквивалентны 2 (§2.9.37). */
|
||||||
|
private static final int MIN_BORDER_SZ = 2;
|
||||||
|
|
||||||
|
/** Минимум центров в TDefTable: ncols≥1 → centers[ncols+1]≥2 (§2.9.321). */
|
||||||
|
private static final int MIN_CENTERS = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сетка строки: ширины колонок, сдвиг от поля, XML границ (может быть
|
||||||
|
* пустым), выравнивание таблицы ("center"/"right"; null = left → элемент
|
||||||
|
* не эмитится).
|
||||||
|
*/
|
||||||
|
record Grid(int[] colWidths, int indent, String bordersXml, String tblJc) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ico → RRGGBB ([MS-DOC] §2.9.171). Индекс = ico. 0 — auto (не эмитится).
|
||||||
|
* В таблице спецификации строка 0x0D дублирует 0x0C (800080) — очевидная
|
||||||
|
* опечатка документа: icoRedDark в палитре Word = 800000, взято значение
|
||||||
|
* Word (иначе 0x0C и 0x0D неразличимы).
|
||||||
|
*/
|
||||||
|
private static final String[] ICO_COLORS = {
|
||||||
|
null, // 0x00 auto
|
||||||
|
"000000", // 1 black
|
||||||
|
"0000FF", // 2 blue
|
||||||
|
"00FFFF", // 3 teal
|
||||||
|
"00FF00", // 4 green
|
||||||
|
"FF00FF", // 5 magenta
|
||||||
|
"FF0000", // 6 red
|
||||||
|
"FFFF00", // 7 yellow
|
||||||
|
"FFFFFF", // 8 white
|
||||||
|
"000080", // 9 dark blue
|
||||||
|
"008080", // 10 dark teal
|
||||||
|
"008000", // 11 dark green
|
||||||
|
"800080", // 12 dark magenta
|
||||||
|
"800000", // 13 dark red
|
||||||
|
"808000", // 14 dark yellow
|
||||||
|
"808080", // 15 gray 50%
|
||||||
|
"C0C0C0", // 16 gray 25%
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Имена ST_Border по brcType (§2.9.39, колонка Reference); 0 — none.
|
||||||
|
* package-private хук для юнита полного покрытия таблицы.
|
||||||
|
*/
|
||||||
|
static String borderVal(int brcType) {
|
||||||
|
return switch (brcType) {
|
||||||
|
case 0x01 -> "single";
|
||||||
|
case 0x03 -> "double";
|
||||||
|
case 0x06 -> "dotted";
|
||||||
|
case 0x07 -> "dashed";
|
||||||
|
case 0x08 -> "dotDash";
|
||||||
|
case 0x09 -> "dotDotDash";
|
||||||
|
case 0x0A -> "triple";
|
||||||
|
case 0x0B -> "thinThickSmallGap";
|
||||||
|
case 0x0C -> "thickThinSmallGap";
|
||||||
|
case 0x0D -> "thinThickThinSmallGap";
|
||||||
|
case 0x0E -> "thinThickMediumGap";
|
||||||
|
case 0x0F -> "thickThinMediumGap";
|
||||||
|
case 0x10 -> "thinThickThinMediumGap";
|
||||||
|
case 0x11 -> "thinThickLargeGap";
|
||||||
|
case 0x12 -> "thickThinLargeGap";
|
||||||
|
case 0x13 -> "thinThickThinLargeGap";
|
||||||
|
case 0x14 -> "wave";
|
||||||
|
case 0x15 -> "doubleWave";
|
||||||
|
case 0x16 -> "dashSmallGap";
|
||||||
|
case 0x17 -> "dashDotStroked";
|
||||||
|
case 0x18 -> "threeDEmboss";
|
||||||
|
case 0x19 -> "threeDEngrave";
|
||||||
|
case 0x1A, 0x1B -> "outset";
|
||||||
|
default -> "single";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Tables() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сетка строки по TAP TTP-абзаца; {@code null} — сетку построить нельзя
|
||||||
|
* (нет/битый sprmTDefTable, нулевая или неположительная ширина колонки) →
|
||||||
|
* вызывающий деградирует в плоские абзацы.
|
||||||
|
*/
|
||||||
|
static Grid parse(byte[] tap) {
|
||||||
|
int[][] centers = {new int[0]};
|
||||||
|
String[] borders = {""};
|
||||||
|
boolean[] d613Seen = {false};
|
||||||
|
String[] jc = {null};
|
||||||
|
boolean[] jcSeen = {false};
|
||||||
|
Grpprl.scan(tap, 0, tap.length, (sprm, buf, off, len) -> {
|
||||||
|
if (sprm == Grpprl.SPRM_T_DEF_TABLE && len >= 3) {
|
||||||
|
centers[0] = readDefTable(buf, off, len);
|
||||||
|
} else if (sprm == Grpprl.SPRM_T_TABLE_BORDERS && len == 0x31) {
|
||||||
|
borders[0] = readBorders(buf, off);
|
||||||
|
d613Seen[0] = true;
|
||||||
|
} else if (sprm == Grpprl.SPRM_T_TABLE_BORDERS_80 && len == 0x19
|
||||||
|
&& !d613Seen[0]) {
|
||||||
|
borders[0] = readBorders80(buf, off);
|
||||||
|
} else if (sprm == Grpprl.SPRM_T_JC && len >= 2) {
|
||||||
|
jc[0] = jcVal(Grpprl.operandInt(buf, off, len));
|
||||||
|
jcSeen[0] = true;
|
||||||
|
} else if (sprm == Grpprl.SPRM_T_JC90 && len >= 2 && !jcSeen[0]) {
|
||||||
|
// тот же приоритет современного над 90-вариантом, что у границ
|
||||||
|
jc[0] = jcVal(Grpprl.operandInt(buf, off, len));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
int[] c = centers[0];
|
||||||
|
if (c.length < MIN_CENTERS) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int[] colWidths = new int[c.length - 1];
|
||||||
|
for (int i = 0; i < colWidths.length; i++) {
|
||||||
|
colWidths[i] = c[i + 1] - c[i];
|
||||||
|
if (colWidths[i] <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Grid(colWidths, c[0], borders[0], jc[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** sprmTJc/sprmTJc90 (§2.6.3): 1 → "center", 2 → "right", прочее (0/left) → null. */
|
||||||
|
private static String jcVal(int v) {
|
||||||
|
return v == 1 ? "center" : v == 2 ? "right" : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TDefTableOperand → centers[ncols+1] (XAS со знаком) или пустой массив. */
|
||||||
|
private static int[] readDefTable(byte[] buf, int off, int len) {
|
||||||
|
int ncols = buf[off + 2] & 0xFF;
|
||||||
|
if (ncols < 1 || ncols > 63 || len < 3 + 2 * (ncols + 1)) {
|
||||||
|
return new int[0];
|
||||||
|
}
|
||||||
|
int[] centers = new int[ncols + 1];
|
||||||
|
for (int i = 0; i <= ncols; i++) {
|
||||||
|
centers[i] = signedXas(buf, off + 3 + 2 * i);
|
||||||
|
}
|
||||||
|
return centers;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int signedXas(byte[] buf, int off) {
|
||||||
|
int v = CfbReader.u16(buf, off);
|
||||||
|
return (v & 0x8000) != 0 ? v - 0x10000 : v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 6 × Brc (8 байт, cv(4)+dptLineWidth+brcType+флаги(2)) → w:tblBorders. */
|
||||||
|
private static String readBorders(byte[] buf, int off) {
|
||||||
|
StringBuilder xml = new StringBuilder();
|
||||||
|
String[] names = {"top", "left", "bottom", "right", "insideH", "insideV"};
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
int b = off + 1 + i * 8;
|
||||||
|
// Brc (§2.9.36): cv(4: R,G,B,fAuto) + dptLineWidth(1) + brcType(1) + флаги(2)
|
||||||
|
int type = buf[b + 5] & 0xFF;
|
||||||
|
if (type == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String color = (buf[b + 3] & 0xFF) == 0xFF
|
||||||
|
? null
|
||||||
|
: String.format("%02X%02X%02X", buf[b] & 0xFF, buf[b + 1] & 0xFF,
|
||||||
|
buf[b + 2] & 0xFF);
|
||||||
|
appendBorder(xml, names[i], type, buf[b + 4] & 0xFF, color);
|
||||||
|
}
|
||||||
|
return xml.length() == 0 ? "" : "<w:tblBorders>" + xml + "</w:tblBorders>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 6 × Brc80 (4 байта: dptLineWidth+brcType+ico+флаги) → w:tblBorders. */
|
||||||
|
private static String readBorders80(byte[] buf, int off) {
|
||||||
|
StringBuilder xml = new StringBuilder();
|
||||||
|
String[] names = {"top", "left", "bottom", "right", "insideH", "insideV"};
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
int b = off + 1 + i * 4;
|
||||||
|
int type = buf[b + 1] & 0xFF;
|
||||||
|
if (type == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int ico = buf[b + 2] & 0xFF;
|
||||||
|
String color = ico < ICO_COLORS.length ? ICO_COLORS[ico] : null;
|
||||||
|
appendBorder(xml, names[i], type, buf[b] & 0xFF, color);
|
||||||
|
}
|
||||||
|
return xml.length() == 0 ? "" : "<w:tblBorders>" + xml + "</w:tblBorders>";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void appendBorder(StringBuilder xml, String name, int type,
|
||||||
|
int dptLineWidth, String color) {
|
||||||
|
int sz = dptLineWidth;
|
||||||
|
if (type >= BRC_TYPE_POINT_UNITS) {
|
||||||
|
sz *= 8; // ширина в целых пунктах (§2.9.38, таблица dptLineWidth)
|
||||||
|
}
|
||||||
|
if (sz < MIN_BORDER_SZ) {
|
||||||
|
sz = MIN_BORDER_SZ; // Brc80: значения < 2 эквивалентны 2 (§2.9.37)
|
||||||
|
}
|
||||||
|
xml.append("<w:").append(name).append(" w:val=\"").append(borderVal(type))
|
||||||
|
.append("\" w:sz=\"").append(sz).append('"');
|
||||||
|
if (color != null) {
|
||||||
|
xml.append(" w:color=\"").append(color).append('"');
|
||||||
|
}
|
||||||
|
xml.append("/>");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,8 +9,10 @@ import org.apache.pdfbox.pdmodel.PDResources;
|
|||||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||||
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
||||||
import org.apache.pdfbox.text.PDFTextStripper;
|
import org.apache.pdfbox.text.PDFTextStripper;
|
||||||
|
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -161,7 +163,20 @@ class WordPdfConverterTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
void chartsSmartArt_drawingsBecomeImages() throws Exception {
|
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));
|
String text = norm(pdfText(pdf));
|
||||||
assertTrue(text.contains("Диаграммы"), "пропал текст вокруг диаграмм: " + text);
|
assertTrue(text.contains("Диаграммы"), "пропал текст вокруг диаграмм: " + text);
|
||||||
@@ -236,7 +251,21 @@ class WordPdfConverterTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
void oleObjects_removedAndConverted() throws Exception {
|
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));
|
String text = norm(pdfText(pdf));
|
||||||
assertTrue(text.contains("OLE object test before"),
|
assertTrue(text.contains("OLE object test before"),
|
||||||
@@ -251,6 +280,10 @@ class WordPdfConverterTest {
|
|||||||
/**
|
/**
|
||||||
* errorOnOle=true — {@link DrawingFoundException} с {@code Kind.OLE},
|
* errorOnOle=true — {@link DrawingFoundException} с {@code Kind.OLE},
|
||||||
* документ отвергается. Фикстура samples/ole-embedded.docx.
|
* документ отвергается. Фикстура samples/ole-embedded.docx.
|
||||||
|
*
|
||||||
|
* <p>Флаг действует только на .docx: в бинарном .doc OLE-объект —
|
||||||
|
* не часть, а форматирование U+0001, и мост деградирует его до
|
||||||
|
* картинки-плейсхолдера (см. {@link #oleObjects_docRemovedAndConverted()}).</p>
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
void drawingErrors_errorFlagRejectsOle() throws Exception {
|
void drawingErrors_errorFlagRejectsOle() throws Exception {
|
||||||
@@ -296,25 +329,30 @@ class WordPdfConverterTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
void exoticGlyphs_drawnNotHash() throws Exception {
|
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));
|
String text = norm(pdfText(pdf));
|
||||||
|
|
||||||
for (String ch : List.of("\u2152", "\u2181", "\u058D", "\u08E1")) {
|
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);
|
+ Integer.toHexString(ch.charAt(0)) + ": " + text);
|
||||||
}
|
}
|
||||||
assertFalse(text.contains("#"),
|
assertFalse(text.contains("#"),
|
||||||
"в PDF остались .notdef-решётки: " + text);
|
fixture + ": в PDF остались .notdef-решётки: " + text);
|
||||||
|
|
||||||
// Римская цифра — вшитым DejaVu Serif, а не базовым Helvetica
|
// Римская цифра — вшитым DejaVu Serif, а не базовым Helvetica
|
||||||
assertTrue(fontNameOf(pdf, '\u2181').contains("DejaVuSerif"),
|
assertTrue(fontNameOf(pdf, '\u2181').contains("DejaVuSerif"),
|
||||||
"римская цифра нарисована не DejaVu Serif");
|
fixture + ": римская цифра нарисована не DejaVu Serif");
|
||||||
// Армянский знак Unicode 16 — Noto Sans Armenian
|
// Армянский знак Unicode 16 — Noto Sans Armenian
|
||||||
assertTrue(fontNameOf(pdf, '\u058D').contains("NotoSansArmenian"),
|
assertTrue(fontNameOf(pdf, '\u058D').contains("NotoSansArmenian"),
|
||||||
"армянский знак нарисован не Noto Sans Armenian");
|
fixture + ": армянский знак нарисован не Noto Sans Armenian");
|
||||||
// Соседний обычный текст не уехал в подставленное семейство
|
// Соседний обычный текст не уехал в подставленное семейство
|
||||||
assertTrue(fontNameOf(pdf, 'ы').contains("Tinos"),
|
assertTrue(fontNameOf(pdf, 'ы').contains("Tinos"),
|
||||||
"кириллица уехала с Tinos");
|
fixture + ": кириллица уехала с Tinos");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -326,26 +364,48 @@ class WordPdfConverterTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
void pageNumbers_recomputedNotCached() throws Exception {
|
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));
|
String text = norm(pdfPageText(pdf, page));
|
||||||
assertTrue(text.contains("Страница " + page),
|
assertTrue(text.contains("Страница " + page),
|
||||||
"страница " + page + " содержит не своё содержимое: " + text);
|
fixture + ": страница " + page + " содержит не своё содержимое: " + text);
|
||||||
assertTrue(text.contains(page + " / 3"),
|
assertTrue(text.contains(page + " / " + pages),
|
||||||
"колонтитул страницы " + page + " не пересчитан: " + text);
|
fixture + ": колонтитул страницы " + page + " не пересчитан: " + text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void ruPlain_cyrillicAndStyles() throws Exception {
|
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("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"),
|
assertTrue(text.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"),
|
||||||
"нет кириллического алфавита: " + text);
|
fixture + ": нет кириллического алфавита: " + text);
|
||||||
assertTrue(text.contains("жирный курсив"), "нет «жирный курсив»: " + text);
|
assertTrue(text.contains("жирный курсив"), fixture + ": нет «жирный курсив»: " + text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Имя фикстуры без расширения — PDF-title и имя temp-файла. */
|
||||||
|
private static String baseName(String fixture) {
|
||||||
|
return fixture.replaceAll("\\.docx?$", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -398,34 +458,63 @@ class WordPdfConverterTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void enPlain_englishText() throws Exception {
|
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);
|
private static void assertEnglishText(String fixture) throws Exception {
|
||||||
assertTrue(text.contains("quick brown fox"), "нет «quick brown fox»: " + text);
|
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
|
@Test
|
||||||
void mixed_headingListTable() throws Exception {
|
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);
|
private static void assertHeadingListTable(String fixture) throws Exception {
|
||||||
assertTrue(text.contains("first item"), "нет пункта списка: " + text);
|
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"),
|
assertTrue(text.contains("Ячейка А") && text.contains("Cell B"),
|
||||||
"нет ячеек таблицы: " + text);
|
fixture + ": нет ячеек таблицы: " + text);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void ruTimes_russianInTimes() throws Exception {
|
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("Съешь ещё этих мягких французских булок"),
|
assertTrue(text.contains("Съешь ещё этих мягких французских булок"),
|
||||||
"нет русского текста: " + text);
|
fixture + ": нет русского текста: " + text);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void tableImage_tableAndImage() throws Exception {
|
void tableImage_tableAndImage() throws Exception {
|
||||||
byte[] docx = sampleBytes("ru-table-image.docx");
|
assertTableImage("ru-table-image.docx");
|
||||||
String text = norm(pdfText(convertPdf(docx, "ru-table-image")));
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 считает ширины
|
// Таблица без tblGrid/tcW (auto-fit): docx4j 17.x считает ширины
|
||||||
// колонок по контенту и вместе с padding'ом ячейки не оставляет
|
// колонок по контенту и вместе с padding'ом ячейки не оставляет
|
||||||
@@ -436,7 +525,7 @@ class WordPdfConverterTest {
|
|||||||
assertTrue(flat.contains("Русский"), "нет «Русский»: " + text);
|
assertTrue(flat.contains("Русский"), "нет «Русский»: " + text);
|
||||||
|
|
||||||
// Изображение: ищем XObject'ы-изображения среди ресурсов страниц
|
// Изображение: ищем XObject'ы-изображения среди ресурсов страниц
|
||||||
Path pdf = convertPdf(docx, "ru-table-image");
|
Path pdf = convertPdf(docx, baseName(fixture));
|
||||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||||
int images = 0;
|
int images = 0;
|
||||||
for (PDPage page : doc.getPages()) {
|
for (PDPage page : doc.getPages()) {
|
||||||
@@ -482,9 +571,9 @@ class WordPdfConverterTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Вход без zip-подписи — отказ как некорректный вход (ValidationException),
|
* Вход без подписи какого-либо поддерживаемого контейнера (ни zip,
|
||||||
* а не ошибка рендера: вход конвертера прогоняет тот же
|
* ни CFB) — отказ как некорректный вход (ValidationException),
|
||||||
* {@link WordPdfValidator#validate(byte[], ConvertOptions)}, что и приложение до очереди.
|
* а не ошибка рендера: сообщение перечисляет оба формата.
|
||||||
* Регрессия — WordPdfValidatorTest#validate_notAZip.
|
* Регрессия — WordPdfValidatorTest#validate_notAZip.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
@@ -492,8 +581,8 @@ class WordPdfConverterTest {
|
|||||||
byte[] junk = {1, 2, 3, 4, 5, 6, 7, 8};
|
byte[] junk = {1, 2, 3, 4, 5, 6, 7, 8};
|
||||||
ValidationException ex = assertThrows(ValidationException.class, () ->
|
ValidationException ex = assertThrows(ValidationException.class, () ->
|
||||||
WordPdfConverter.convert(junk, "junk"));
|
WordPdfConverter.convert(junk, "junk"));
|
||||||
assertTrue(ex.getMessage().contains("не zip-архив"),
|
assertTrue(ex.getMessage().contains("не похоже на .docx или .doc"),
|
||||||
"сообщение должно упоминать zip-подпись: " + ex.getMessage());
|
"сообщение должно перечислять форматы: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -539,12 +628,18 @@ class WordPdfConverterTest {
|
|||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
void tooManyPages() {
|
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, () ->
|
ValidationException ex = assertThrows(ValidationException.class, () ->
|
||||||
WordPdfConverter.convert(
|
WordPdfConverter.convert(
|
||||||
sampleBytes("too-many-pages.docx"), "too-many-pages",
|
sampleBytes(fixture), baseName(fixture),
|
||||||
new ConvertOptions(false, false, false, WordPdfSettings.MAX_INPUT_MB, 100)));
|
new ConvertOptions(false, false, false, WordPdfSettings.MAX_INPUT_MB, 100)));
|
||||||
assertTrue(ex.getMessage().contains("100"),
|
assertTrue(ex.getMessage().contains("100"),
|
||||||
"сообщение должно упоминать лимит: " + ex.getMessage());
|
fixture + ": сообщение должно упоминать лимит: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -563,6 +658,23 @@ class WordPdfConverterTest {
|
|||||||
"сообщение должно упоминать лимит: " + ex.getMessage());
|
"сообщение должно упоминать лимит: " + 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 в ядре нет,
|
* Заголовок PDF — параметр {@code title} (файлового API в ядре нет,
|
||||||
* из имени файла заголовок больше не выводится).
|
* из имени файла заголовок больше не выводится).
|
||||||
@@ -818,6 +930,27 @@ class WordPdfConverterTest {
|
|||||||
assertEquals(196.15, xOfMarker(pdf, 'Q'), 1.0);
|
assertEquals(196.15, xOfMarker(pdf, 'Q'), 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* w:jc="center" БЕЗ w:tblInd: Word центрирует сетку, текст = поле +
|
||||||
|
* (полоса−ΣgridCol)/2 + padding. TableIndentNormalizer сворачивает jc с
|
||||||
|
* X=0 в абсолютный tblInd — иначе docx4j пишет центрированию start-indent
|
||||||
|
* без вычета cellMar и padding-компенсация LayoutPostRenderer уводит
|
||||||
|
* текст на +5.4pt (замер: 165.57). Та же геометрия и та же ожидаемая
|
||||||
|
* точка, что у docFooterTableCentered_shiftedLikeWord.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void tableCenteredNoIndent_shiftedLikeWord() throws Exception {
|
||||||
|
byte[] docx = minimalDocx("<w:tbl><w:tblPr><w:jc w:val=\"center\"/></w:tblPr>"
|
||||||
|
+ "<w:tblGrid><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"3000\"/></w:tblGrid>"
|
||||||
|
+ "<w:tr><w:tc><w:p><w:r><w:t>Q</w:t></w:r></w:p></w:tc></w:tr></w:tbl>",
|
||||||
|
"<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
|
||||||
|
+ "<w:pgMar w:top=\"1134\" w:right=\"850\" w:bottom=\"1134\" w:left=\"1134\""
|
||||||
|
+ " w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/></w:sectPr>");
|
||||||
|
Path pdf = convertPdf(docx, "t");
|
||||||
|
// margin 56.7 + (9922−6000)/2÷20 = 98.05 + cell padding 5.4
|
||||||
|
assertEquals(160.15, xOfMarker(pdf, 'Q'), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* w:suff="space": Word пишет после номера обычный пробел (Part 1
|
* w:suff="space": Word пишет после номера обычный пробел (Part 1
|
||||||
* §17.3.1.28), docx4j разделитель не эмитит вовсе (дамп n4.fo).
|
* §17.3.1.28), docx4j разделитель не эмитит вовсе (дамп n4.fo).
|
||||||
@@ -1165,4 +1298,484 @@ class WordPdfConverterTest {
|
|||||||
&& dfe.kind() == DrawingFoundException.Kind.CHARTS,
|
&& dfe.kind() == DrawingFoundException.Kind.CHARTS,
|
||||||
"ожидался DrawingFoundException(CHARTS), получено: " + ex);
|
"ожидался 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Синтетический .doc со списками (ни одна фикстура заказчика списков не
|
||||||
|
* содержит — крафт POIFS, дубль хелперов DocToDocxFormattingTest):
|
||||||
|
* PlfLst/PlfLfo → numbering.xml + w:numPr — decimal «1.»/«2.», буквенный
|
||||||
|
* подуровень «a)»/«b)», Symbol-буллет (PUA в w:lvl чинит
|
||||||
|
* SymbolFontNormalizer — та же цепочка, что symbol-bullets.docx).
|
||||||
|
* Регрессия — internal.doc.Lists + DocxBody#numPrXml.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void docLists_numberingAndBulletsRendered() throws Exception {
|
||||||
|
Path pdf = convertPdf(listsDoc(), "doc-lists");
|
||||||
|
String text = norm(pdfText(pdf));
|
||||||
|
assertTrue(text.contains("1."), "decimal-номер: " + text);
|
||||||
|
assertTrue(text.contains("2."), "второй пункт: " + text);
|
||||||
|
assertTrue(text.contains("a)"), "буквенный подуровень: " + text);
|
||||||
|
assertTrue(text.contains("b)"), "второй пункт подуровня: " + text);
|
||||||
|
assertTrue(text.contains("\u2022"), "Symbol-буллет: " + text);
|
||||||
|
assertFalse(text.contains("#"), ".notdef-боксы в тексте");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Синтетический .doc с двумя секциями (крафт POIFS, дубль хелперов
|
||||||
|
* DocToDocxFormattingTest): колонтитуки каждой секции — свой sectPr.
|
||||||
|
* Секция 0: odd hdr «ШАПКА-1», odd ftr «ПОДВАЛ-1»; секция 1: odd hdr
|
||||||
|
* «ШАПКА-2», odd ftr не определён ([x,x), §2.4.4) → docx4j наследует
|
||||||
|
* «ПОДВАЛ-1». Страница 1 — ШАПКА-1+ПОДВАЛ-1, страница 2 — ШАПКА-2 +
|
||||||
|
* унаследованный ПОДВАЛ-1 без ШАПКА-1. Регрессия — internal.doc
|
||||||
|
* (Sections/Headers/DocToDocx, многосекционный перенос колонтитуков).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void docMultiSection_perSectionHeaders() throws Exception {
|
||||||
|
Path pdf = convertPdf(multiSectionDoc(), "doc-multi-section");
|
||||||
|
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||||
|
assertEquals(2, doc.getNumberOfPages(), "межсекционный разрыв не дал страницу");
|
||||||
|
}
|
||||||
|
String p1 = norm(pdfPageText(pdf, 1));
|
||||||
|
String p2 = norm(pdfPageText(pdf, 2));
|
||||||
|
assertTrue(p1.contains("ШАПКА-1"), "заголовок секции 1: " + p1);
|
||||||
|
assertTrue(p1.contains("ПОДВАЛ-1"), "футер секции 1: " + p1);
|
||||||
|
assertTrue(p2.contains("ШАПКА-2"), "заголовок секции 2: " + p2);
|
||||||
|
assertFalse(p2.contains("ШАПКА-1"), "колонтитук секции 1 утек во 2-ю: " + p2);
|
||||||
|
assertTrue(p2.contains("ПОДВАЛ-1"),
|
||||||
|
"неопределённый футер секции 2 должен наследоваться: " + p2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Таблица с w:jc=center + w:tblInd в word/header1.xml: полоса набора у
|
||||||
|
* header-части своя отсутствует — TableIndentNormalizer.rewritePart
|
||||||
|
* сворачивает по band из document.xml (9922): (9922−6000)/2+720 = 2681
|
||||||
|
* twips = 134.05pt (без свёртки docx4j игнорирует tblInd при jc≠left —
|
||||||
|
* x был бы 160.15). Регрессия — TableIndentNormalizer#rewritePart +
|
||||||
|
* DocxRewritePipeline (band из document.xml).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void headerTableIndent_centeredInHeader() throws Exception {
|
||||||
|
String w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||||
|
String hdr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||||
|
+ "<w:hdr xmlns:w=\"" + w + "\" xmlns:r=\"http://schemas.openxmlformats.org"
|
||||||
|
+ "/officeDocument/2006/relationships\">"
|
||||||
|
+ "<w:tbl><w:tblPr><w:jc w:val=\"center\"/>"
|
||||||
|
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/></w:tblPr>"
|
||||||
|
+ "<w:tblGrid><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"3000\"/></w:tblGrid>"
|
||||||
|
+ "<w:tr><w:tc><w:p><w:r><w:t>Q</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"
|
||||||
|
+ "</w:hdr>";
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||||
|
putZip(zos, "[Content_Types].xml",
|
||||||
|
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||||
|
+ "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"
|
||||||
|
+ "<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>"
|
||||||
|
+ "<Default Extension=\"xml\" ContentType=\"application/xml\"/>"
|
||||||
|
+ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/>"
|
||||||
|
+ "<Override PartName=\"/word/header1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml\"/>"
|
||||||
|
+ "</Types>");
|
||||||
|
putZip(zos, "_rels/.rels",
|
||||||
|
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||||
|
+ "<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>");
|
||||||
|
putZip(zos, "word/document.xml",
|
||||||
|
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||||
|
+ "<w:document xmlns:w=\"" + w + "\""
|
||||||
|
+ " xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
|
||||||
|
+ "<w:body><w:p><w:r><w:t>МАРКЕР</w:t></w:r></w:p>"
|
||||||
|
+ "<w:sectPr><w:headerReference w:type=\"default\" r:id=\"rId1\"/>"
|
||||||
|
+ "<w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
|
||||||
|
+ "<w:pgMar w:top=\"1134\" w:right=\"850\" w:bottom=\"1134\" w:left=\"1134\""
|
||||||
|
+ " w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/></w:sectPr>"
|
||||||
|
+ "</w:body></w:document>");
|
||||||
|
putZip(zos, "word/_rels/document.xml.rels",
|
||||||
|
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||||
|
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
||||||
|
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header\" Target=\"header1.xml\"/>"
|
||||||
|
+ "</Relationships>");
|
||||||
|
putZip(zos, "word/header1.xml", hdr);
|
||||||
|
}
|
||||||
|
Path pdf = convertPdf(out.toByteArray(), "hdr-table");
|
||||||
|
assertTrue(norm(pdfText(pdf)).contains("МАРКЕР"), "тело пропало");
|
||||||
|
// margin 56.7 + tblInd 134.05 + cell padding 5.4 — та же арифметика,
|
||||||
|
// что у body-регрессии tableIndentCentered_shiftedLikeWord
|
||||||
|
assertEquals(196.15, xOfMarker(pdf, 'Q'), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- крафт .doc с двумя секциями (дубль DocToDocxFormattingTest) -----
|
||||||
|
|
||||||
|
private static final int MULTI_TEXT_FC = 2048;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Две секции: «Текст1⌬Текст2⏎» (0x0C на CP6), PlcfSed aCp [0,7,14]
|
||||||
|
* (fcSepx=0 — дефолты Word 97 у обеих); Header Document: 6 разделителей,
|
||||||
|
* у секции 0 odd hdr «ШАПКА-1» + odd ftr «ПОДВАЛ-1», у секции 1 odd hdr
|
||||||
|
* «ШАПКА-2», odd ftr — пустой диапазон [x,x) (наследование).
|
||||||
|
*/
|
||||||
|
private static byte[] multiSectionDoc() throws IOException {
|
||||||
|
String text = "Текст1" + (char) 0x0C + "Текст2\r"
|
||||||
|
+ "\r\r\r\r\r\r" + "\r" + "ШАПКА-1\r" + "\r" + "ПОДВАЛ-1\r" + "\r" + "\r"
|
||||||
|
+ "\r" + "ШАПКА-2\r" + "\r" + "\r" + "\r";
|
||||||
|
byte[] wd = new byte[MULTI_TEXT_FC + text.length() * 2];
|
||||||
|
put16(wd, 0, 0xA5EC);
|
||||||
|
put16(wd, 2, 0x00C1);
|
||||||
|
put16(wd, 10, 1 << 9);
|
||||||
|
put16(wd, 62, 4);
|
||||||
|
put32(wd, 64, wd.length);
|
||||||
|
put32(wd, 76, 14); // ccpText
|
||||||
|
put32(wd, 80, 0); // ccpFtn
|
||||||
|
put32(wd, 84, text.length() - 14); // ccpHdd
|
||||||
|
put16(wd, 152, 98);
|
||||||
|
pair(wd, 6, 0, 36); // PlcfSed: aCp(3) + SED(2×12)
|
||||||
|
pair(wd, 11, 36, 76); // Plcfhdd: aCp(19)
|
||||||
|
pair(wd, 33, 112, 21); // Clx
|
||||||
|
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
|
||||||
|
System.arraycopy(t, 0, wd, MULTI_TEXT_FC, t.length);
|
||||||
|
byte[] tab = new byte[133];
|
||||||
|
// PlcfSed @0: aCp [0, 7, 14], fcSepx=0/0 (дефолтная геометрия)
|
||||||
|
put32(tab, 0, 0);
|
||||||
|
put32(tab, 4, 7);
|
||||||
|
put32(tab, 8, 14);
|
||||||
|
// Plcfhdd @36: aCp относительные; odd ftr секции 1 — [37,37) (пустая)
|
||||||
|
int[] hdd = {0, 1, 2, 3, 4, 5, 6, 7, 15, 16, 25, 26, 27,
|
||||||
|
28, 36, 37, 37, 38, 39};
|
||||||
|
for (int i = 0; i < hdd.length; i++) {
|
||||||
|
put32(tab, 36 + i * 4, hdd[i]);
|
||||||
|
}
|
||||||
|
// Clx @112: Pcdt, один несжатый кусок
|
||||||
|
tab[112] = 0x02;
|
||||||
|
put32(tab, 113, 16);
|
||||||
|
put32(tab, 117, 0);
|
||||||
|
put32(tab, 121, text.length());
|
||||||
|
put32(tab, 127, MULTI_TEXT_FC);
|
||||||
|
try (POIFSFileSystem fs = new POIFSFileSystem();
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||||
|
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
|
||||||
|
fs.getRoot().createDocument("1Table", new ByteArrayInputStream(tab));
|
||||||
|
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
||||||
|
fs.writeFilesystem(out);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- крафт .doc с таблицей по центру в футере (sprmTJc) -------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Одна секция, A4 11906×16838 с полями 1134/850 (Sepx — та же полоса
|
||||||
|
* набора 9922, что у docx-регрессии tableIndentCentered_shiftedLikeWord):
|
||||||
|
* body «T⏎»; odd footer — табличная строка (ячейка «Q␇» с sprmPFInTable +
|
||||||
|
* TTP-абзац «␇» с TAP: sprmTDefTable 2×3000 + sprmTJc=1 → center) +
|
||||||
|
* guard-¶ (§2.4.4 — отдельный ¶ после последней строки).
|
||||||
|
*/
|
||||||
|
private static byte[] footerCenterTableDoc() throws IOException {
|
||||||
|
String text = "T\r" + "\r\r\r\r\r\r" + "\r\r\r"
|
||||||
|
+ "Q" + (char) 7 + (char) 7 + "\r" + "\r\r";
|
||||||
|
byte[] wd = new byte[MULTI_TEXT_FC + text.length() * 2];
|
||||||
|
put16(wd, 0, 0xA5EC);
|
||||||
|
put16(wd, 2, 0x00C1);
|
||||||
|
put16(wd, 10, 1 << 9);
|
||||||
|
put16(wd, 62, 4);
|
||||||
|
put32(wd, 64, wd.length);
|
||||||
|
put32(wd, 76, 2); // ccpText
|
||||||
|
put32(wd, 80, 0); // ccpFtn
|
||||||
|
put32(wd, 84, text.length() - 2); // ccpHdd
|
||||||
|
put16(wd, 152, 98);
|
||||||
|
pair(wd, 6, 0, 20); // PlcfSed: aCp(2) + SED(1), fcSepx @10
|
||||||
|
pair(wd, 11, 20, 52); // Plcfhdd: aCp(13)
|
||||||
|
pair(wd, 13, 72, 12); // PlcfBtePapx
|
||||||
|
pair(wd, 33, 84, 21); // Clx
|
||||||
|
// Sepx @1024 (WordDocument): cb(2) + grpprl — геометрия секции
|
||||||
|
byte[] sepx = concat(prl2(0xB01F, 11906), prl2(0xB020, 16838),
|
||||||
|
prl2(0xB021, 1134), prl2(0xB022, 850));
|
||||||
|
put16(wd, 1024, sepx.length);
|
||||||
|
System.arraycopy(sepx, 0, wd, 1026, sepx.length);
|
||||||
|
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
|
||||||
|
System.arraycopy(t, 0, wd, MULTI_TEXT_FC, t.length);
|
||||||
|
// PapxFkp pn=3: «Q␇» (InTable) + «␇» (TTP: сетка 2×3000 + sprmTJc=1)
|
||||||
|
int page = 3 * 512;
|
||||||
|
put32(wd, page, MULTI_TEXT_FC + 22);
|
||||||
|
put32(wd, page + 4, MULTI_TEXT_FC + 26);
|
||||||
|
put32(wd, page + 8, MULTI_TEXT_FC + 28);
|
||||||
|
wd[page + 12] = 87;
|
||||||
|
wd[page + 12 + 13] = 94;
|
||||||
|
wd[page + 511] = 2; // cpara
|
||||||
|
byte[] inTable = prl(0x2416, 1);
|
||||||
|
papxEntry(wd, page, 87, inTable);
|
||||||
|
papxEntry(wd, page, 94, concat(inTable, prl(0x2417, 1),
|
||||||
|
tdefTable(2, new int[] {0, 3000, 6000}), prl2(0x548A, 1)));
|
||||||
|
byte[] tab = new byte[105];
|
||||||
|
put32(tab, 0, 0); // PlcfSed aCp [0, 2)
|
||||||
|
put32(tab, 4, 2);
|
||||||
|
put32(tab, 10, 1024); // SED fcSepx (sedBase 8 + 2)
|
||||||
|
// Plcfhdd @20: aCp относительные; odd footer — [9,14) («Q␇␇» + guard-¶)
|
||||||
|
int[] hdd = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15};
|
||||||
|
for (int i = 0; i < hdd.length; i++) {
|
||||||
|
put32(tab, 20 + i * 4, hdd[i]);
|
||||||
|
}
|
||||||
|
put32(tab, 72, MULTI_TEXT_FC + 22); // PlcfBtePapx aFc + pn=3
|
||||||
|
put32(tab, 76, MULTI_TEXT_FC + 28);
|
||||||
|
put32(tab, 80, 3);
|
||||||
|
tab[84] = 0x02; // Clx Pcdt, один несжатый кусок
|
||||||
|
put32(tab, 85, 16);
|
||||||
|
put32(tab, 89, 0);
|
||||||
|
put32(tab, 93, text.length());
|
||||||
|
put32(tab, 99, MULTI_TEXT_FC);
|
||||||
|
try (POIFSFileSystem fs = new POIFSFileSystem();
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||||
|
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
|
||||||
|
fs.getRoot().createDocument("1Table", new ByteArrayInputStream(tab));
|
||||||
|
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
||||||
|
fs.writeFilesystem(out);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TDefTableOperand (§2.9.321): cb(2)=остаток+1, ncols, centers, TC80 по 20 Б. */
|
||||||
|
private static byte[] tdefTable(int ncols, int[] centers) {
|
||||||
|
byte[] op = new byte[3 + 2 * centers.length + 20 * ncols];
|
||||||
|
put16(op, 0, op.length - 2 + 1);
|
||||||
|
op[2] = (byte) ncols;
|
||||||
|
for (int i = 0; i < centers.length; i++) {
|
||||||
|
put16(op, 3 + 2 * i, centers[i]);
|
||||||
|
}
|
||||||
|
return concat(new byte[] {(byte) 0xD608, (byte) (0xD608 >>> 8)}, op);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sprmTJc=1 из TAP футерной строки → w:jc="center" в tblPr (мост),
|
||||||
|
* docx4j+FOP центрируют таблицу как Word: полоса 9922 = 11906−1134−850,
|
||||||
|
* x = margin 56.7 + (9922−6000)/2÷20 = 98.05 + cell padding 5.4
|
||||||
|
* (та же арифметика, что у tableIndentCentered_shiftedLikeWord без
|
||||||
|
* tblInd). Без переноса sprmTJc таблица прижата к левому краю (x≈62.1).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void docFooterTableCentered_shiftedLikeWord() throws Exception {
|
||||||
|
Path pdf = convertPdf(footerCenterTableDoc(), "doc-footer-jc");
|
||||||
|
assertEquals(160.15, xOfMarker(pdf, 'Q'), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- крафт .doc со списками (дубль DocToDocxFormattingTest) ----------
|
||||||
|
|
||||||
|
private static final int LISTS_TEXT_FC = 2048;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 5 абзацев: «one»/«two» (ilfo=1, ilvl=0 — decimal), «sub1»/«sub2»
|
||||||
|
* (ilfo=1, ilvl=1 — lowerLetter), «mark» (ilfo=2 — bullet Symbol).
|
||||||
|
* PlfLst: LSTF lsid=100 (9 уровней) + LSTF lsid=200 (fSimpleList);
|
||||||
|
* PlfLfo: два LFO без переопределений; SttbfFfn: Symbol на ftc0=0.
|
||||||
|
*/
|
||||||
|
private static byte[] listsDoc() throws IOException {
|
||||||
|
String text = "one\r" + "two\r" + "sub1\r" + "sub2\r" + "mark\r";
|
||||||
|
byte[] wd = new byte[LISTS_TEXT_FC + text.length() * 2];
|
||||||
|
put16(wd, 0, 0xA5EC);
|
||||||
|
put16(wd, 2, 0x00C1);
|
||||||
|
put16(wd, 10, 1 << 9);
|
||||||
|
put16(wd, 62, 4);
|
||||||
|
put32(wd, 64, wd.length);
|
||||||
|
put32(wd, 76, text.length());
|
||||||
|
put16(wd, 152, 98);
|
||||||
|
pair(wd, 6, 0, 20); // PlcfSed
|
||||||
|
pair(wd, 13, 20, 12); // PlcfBtePapx
|
||||||
|
pair(wd, 33, 32, 21); // Clx
|
||||||
|
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
|
||||||
|
System.arraycopy(t, 0, wd, LISTS_TEXT_FC, t.length);
|
||||||
|
int page = 3 * 512;
|
||||||
|
// rgfc — FC (UTF-16LE): границы «one|two|sub1|sub2|mark|»
|
||||||
|
int[] rgfc = {LISTS_TEXT_FC, LISTS_TEXT_FC + 8, LISTS_TEXT_FC + 16,
|
||||||
|
LISTS_TEXT_FC + 26, LISTS_TEXT_FC + 36, LISTS_TEXT_FC + 2 * text.length()};
|
||||||
|
for (int i = 0; i < rgfc.length; i++) {
|
||||||
|
put32(wd, page + i * 4, rgfc[i]);
|
||||||
|
}
|
||||||
|
int rgbx = page + rgfc.length * 4;
|
||||||
|
int[] bx = {87, 94, 101, 108, 115};
|
||||||
|
for (int i = 0; i < bx.length; i++) {
|
||||||
|
wd[rgbx + i * 13] = (byte) bx[i];
|
||||||
|
}
|
||||||
|
wd[page + 511] = 5; // cpara
|
||||||
|
papxEntry(wd, page, 87, concat(prl2(0x460B, 1), prl(0x260A, 0)));
|
||||||
|
papxEntry(wd, page, 94, concat(prl2(0x460B, 1), prl(0x260A, 0)));
|
||||||
|
papxEntry(wd, page, 101, concat(prl2(0x460B, 1), prl(0x260A, 1)));
|
||||||
|
papxEntry(wd, page, 108, concat(prl2(0x460B, 1), prl(0x260A, 1)));
|
||||||
|
papxEntry(wd, page, 115, concat(prl2(0x460B, 2), prl(0x260A, 0)));
|
||||||
|
// табличный поток: PlcfSed, PlcfBtePapx, Clx, SttbfFfn, PlfLst+LVL, PlfLfo
|
||||||
|
byte[] fonts = sttbfFfn("Symbol");
|
||||||
|
byte[] lvls = listLevels();
|
||||||
|
byte[] plfLst = concat(u16(2), lstf(100, false), lstf(200, true));
|
||||||
|
byte[] plfLfo = concat(u32(2), lfo(100), lfo(200), u32(0xFFFFFFFF), u32(0xFFFFFFFF));
|
||||||
|
int fontsAt = 54;
|
||||||
|
int lstAt = fontsAt + fonts.length;
|
||||||
|
int lvlAt = lstAt + plfLst.length;
|
||||||
|
int lfoAt = lvlAt + lvls.length;
|
||||||
|
byte[] tab = new byte[lfoAt + plfLfo.length];
|
||||||
|
put32(tab, 0, 0);
|
||||||
|
put32(tab, 4, text.length());
|
||||||
|
put32(tab, 20, LISTS_TEXT_FC);
|
||||||
|
put32(tab, 24, LISTS_TEXT_FC + 2 * text.length());
|
||||||
|
put32(tab, 28, 3);
|
||||||
|
tab[32] = 0x02; // Clx Pcdt, один несжатый кусок
|
||||||
|
put32(tab, 33, 16);
|
||||||
|
put32(tab, 37, 0);
|
||||||
|
put32(tab, 41, text.length());
|
||||||
|
put32(tab, 47, LISTS_TEXT_FC);
|
||||||
|
System.arraycopy(fonts, 0, tab, fontsAt, fonts.length);
|
||||||
|
System.arraycopy(plfLst, 0, tab, lstAt, plfLst.length);
|
||||||
|
System.arraycopy(lvls, 0, tab, lvlAt, lvls.length);
|
||||||
|
System.arraycopy(plfLfo, 0, tab, lfoAt, plfLfo.length);
|
||||||
|
pair(wd, 15, fontsAt, fonts.length); // SttbfFfn
|
||||||
|
pair(wd, 73, lstAt, plfLst.length); // PlfLst
|
||||||
|
pair(wd, 74, lfoAt, plfLfo.length); // PlfLfo
|
||||||
|
try (POIFSFileSystem fs = new POIFSFileSystem();
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||||
|
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
|
||||||
|
fs.getRoot().createDocument("1Table", new ByteArrayInputStream(tab));
|
||||||
|
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
||||||
|
fs.writeFilesystem(out);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GrpPrlAndIstd в форме cb≠0 (grpprl нечётный: istd=0 впереди). */
|
||||||
|
private static void papxEntry(byte[] wd, int page, int bx, byte[] grpprl) {
|
||||||
|
int at = page + bx * 2;
|
||||||
|
wd[at] = (byte) ((grpprl.length + 3) / 2);
|
||||||
|
put16(wd, at + 1, 0);
|
||||||
|
System.arraycopy(grpprl, 0, wd, at + 3, grpprl.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SttbfFfn (§2.9.147): одно семейство на ftc0=0. */
|
||||||
|
private static byte[] sttbfFfn(String family) {
|
||||||
|
byte[] fam = (family + "\0").getBytes(StandardCharsets.UTF_16LE);
|
||||||
|
byte[] t = new byte[4 + 1 + 39 + fam.length];
|
||||||
|
put16(t, 0, 1);
|
||||||
|
t[4] = (byte) (39 + fam.length);
|
||||||
|
System.arraycopy(fam, 0, t, 5 + 39, fam.length);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 9 LVL lsid=100 (decimal «%1.», lowerLetter «%2)») + bullet LVL lsid=200. */
|
||||||
|
private static byte[] listLevels() {
|
||||||
|
byte[][] ls = new byte[10][];
|
||||||
|
ls[0] = listLvl(0x00, 0, new byte[0], new int[] {0, '.'});
|
||||||
|
ls[1] = listLvl(0x04, 0, new byte[0], new int[] {1, ')'});
|
||||||
|
for (int i = 2; i < 9; i++) {
|
||||||
|
ls[i] = listLvl(0x00, 0, new byte[0], new int[] {i, '.'});
|
||||||
|
}
|
||||||
|
ls[9] = listLvl(0x17, 1, prl2(0x4A4F, 0), new int[] {0xF0B7});
|
||||||
|
return concat(ls);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] listLvl(int nfc, int follow, byte[] chpx, int[] xst) {
|
||||||
|
byte[] b = new byte[28];
|
||||||
|
put32(b, 0, 1); // iStartAt
|
||||||
|
b[4] = (byte) nfc;
|
||||||
|
b[15] = (byte) follow;
|
||||||
|
b[24] = (byte) chpx.length;
|
||||||
|
byte[] x = new byte[2 + 2 * xst.length];
|
||||||
|
put16(x, 0, xst.length);
|
||||||
|
for (int i = 0; i < xst.length; i++) {
|
||||||
|
put16(x, 2 + 2 * i, xst[i]);
|
||||||
|
}
|
||||||
|
return concat(b, chpx, x);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] lstf(int lsid, boolean simple) {
|
||||||
|
byte[] b = new byte[28];
|
||||||
|
put32(b, 0, lsid);
|
||||||
|
b[26] = (byte) (simple ? 1 : 0);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] lfo(int lsid) {
|
||||||
|
byte[] b = new byte[16];
|
||||||
|
put32(b, 0, lsid);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] prl(int sprm, int operand) {
|
||||||
|
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) operand};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] prl2(int sprm, int v) {
|
||||||
|
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] u16(int v) {
|
||||||
|
byte[] b = new byte[2];
|
||||||
|
put16(b, 0, v);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] u32(long v) {
|
||||||
|
byte[] b = new byte[4];
|
||||||
|
put32(b, 0, (int) v);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -571,4 +571,46 @@ class WordPdfValidatorTest {
|
|||||||
() -> WordPdfValidator.validate(new byte[]{'P', 'K', 0, 4},
|
() -> WordPdfValidator.validate(new byte[]{'P', 'K', 0, 4},
|
||||||
ConvertOptions.defaults()));
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+108
-5
@@ -78,18 +78,45 @@ class TableIndentNormalizerTest {
|
|||||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** jc без tblInd — аудит PASS (docx4j центрирует), не трогаем. */
|
/**
|
||||||
|
* jc без tblInd — сворачивается в абсолютный tblInd (X=0): docx4j пишет
|
||||||
|
* центрированию start-indent без вычета cellMar, padding-компенсация
|
||||||
|
* LayoutPostRenderer прибавила бы padding поверх (+5.4pt к Word).
|
||||||
|
*/
|
||||||
@Test
|
@Test
|
||||||
void jcWithoutIndent_returnsNull() {
|
void jcWithoutIndent_folded() {
|
||||||
String xml = doc(table("<w:jc w:val=\"center\"/>", GRID_6000));
|
String xml = doc(table("<w:jc w:val=\"center\"/>", GRID_6000));
|
||||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||||
|
assertTrue(fixed.contains("<w:tblInd w:w=\"1961\" w:type=\"dxa\"/>"), fixed);
|
||||||
|
assertFalse(fixed.contains("<w:jc"), fixed);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** tblInd=0 с jc — сдвига нет, не трогаем. */
|
/** right без tblInd: (9922−6000) = 3922. */
|
||||||
@Test
|
@Test
|
||||||
void zeroIndent_returnsNull() {
|
void rightWithoutIndent_folded() {
|
||||||
|
String xml = doc(table("<w:jc w:val=\"right\"/>", GRID_6000));
|
||||||
|
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||||
|
assertTrue(fixed.contains("<w:tblInd w:w=\"3922\" w:type=\"dxa\"/>"), fixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** tblInd=0 с jc — тот же fold (X=0), прежнему поведению не канон. */
|
||||||
|
@Test
|
||||||
|
void zeroIndent_folded() {
|
||||||
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||||
+ "<w:tblInd w:w=\"0\" w:type=\"dxa\"/>", GRID_6000));
|
+ "<w:tblInd w:w=\"0\" w:type=\"dxa\"/>", GRID_6000));
|
||||||
|
String fixed = TableIndentNormalizer.rewrite(xml);
|
||||||
|
assertTrue(fixed.contains("<w:tblInd w:w=\"1961\" w:type=\"dxa\"/>"), fixed);
|
||||||
|
assertFalse(fixed.contains("<w:jc"), fixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* tblCellSpacing без tblInd — tblInd по CT_TblPrBase идёт после
|
||||||
|
* tblCellSpacing, вставить некуда: консервативный пропуск.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void cellSpacingWithoutIndent_returnsNull() {
|
||||||
|
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||||
|
+ "<w:tblCellSpacing w:w=\"20\" w:type=\"dxa\"/>", GRID_6000));
|
||||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,6 +198,82 @@ class TableIndentNormalizerTest {
|
|||||||
assertNull(TableIndentNormalizer.rewrite(xml));
|
assertNull(TableIndentNormalizer.rewrite(xml));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String hdr(String body) {
|
||||||
|
return "<w:hdr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
|
||||||
|
+ body + "</w:hdr>";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** header-часть со своей sectPr не содержит — полоса приходит извне. */
|
||||||
|
@Test
|
||||||
|
void rewritePart_header_foldsWithGivenBand() {
|
||||||
|
String xml = hdr(table("<w:jc w:val=\"center\"/>"
|
||||||
|
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||||
|
String fixed = TableIndentNormalizer.rewritePart("word/header1.xml", xml, 9922);
|
||||||
|
assertTrue(fixed.contains("<w:tblInd w:w=\"2681\" w:type=\"dxa\"/>"), fixed);
|
||||||
|
assertFalse(fixed.contains("<w:jc"), "jc удалён: " + fixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** footer-часть — тот же путь. */
|
||||||
|
@Test
|
||||||
|
void rewritePart_footer_foldsWithGivenBand() {
|
||||||
|
String xml = hdr(table("<w:jc w:val=\"right\"/>"
|
||||||
|
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000))
|
||||||
|
.replace("w:hdr", "w:ftr");
|
||||||
|
String fixed = TableIndentNormalizer.rewritePart("word/footer2.xml", xml, 9922);
|
||||||
|
assertTrue(fixed.contains("<w:tblInd w:w=\"4642\" w:type=\"dxa\"/>"), fixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Многосекционный документ (band = −1) — полоса неоднозначна, пропускаем. */
|
||||||
|
@Test
|
||||||
|
void rewritePart_negativeBand_returnsNull() {
|
||||||
|
String xml = hdr(table("<w:jc w:val=\"center\"/>"
|
||||||
|
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||||
|
assertNull(TableIndentNormalizer.rewritePart("word/header1.xml", xml, -1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Прочие word/*.xml (footnotes и пр.) — не трогаем. */
|
||||||
|
@Test
|
||||||
|
void rewritePart_otherPart_returnsNull() {
|
||||||
|
String xml = hdr(table("<w:jc w:val=\"center\"/>"
|
||||||
|
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||||
|
assertNull(TableIndentNormalizer.rewritePart("word/footnotes.xml", xml, 9922));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Header без таблиц — null (контракт «нечего менять»). */
|
||||||
|
@Test
|
||||||
|
void rewritePart_headerWithoutTables_returnsNull() {
|
||||||
|
assertNull(TableIndentNormalizer.rewritePart("word/header1.xml",
|
||||||
|
hdr("<w:p><w:r><w:t>hi</w:t></w:r></w:p>"), 9922));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** document.xml делегирует rewrite: полоса — из собственной sectPr, не из band. */
|
||||||
|
@Test
|
||||||
|
void rewritePart_document_usesOwnSectPr() {
|
||||||
|
String xml = doc(table("<w:jc w:val=\"center\"/>"
|
||||||
|
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
|
||||||
|
String fixed = TableIndentNormalizer.rewritePart("word/document.xml", xml, 12345);
|
||||||
|
assertTrue(fixed.contains("<w:tblInd w:w=\"2681\" w:type=\"dxa\"/>"),
|
||||||
|
"собственная полоса 9922, не внешний band: " + fixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** strict-pgMar (w:start/w:end) — band считается, а не берётся из дефолтов. */
|
||||||
|
@Test
|
||||||
|
void bandOf_strictStartEndFields() {
|
||||||
|
String xml = "<w:document xmlns:w=\"http://purl.oclc.org/ooxml/wordprocessingml/main\">"
|
||||||
|
+ "<w:body><w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
|
||||||
|
+ "<w:pgMar w:top=\"1134\" w:end=\"850\" w:bottom=\"1134\" w:start=\"1134\"/>"
|
||||||
|
+ "</w:sectPr></w:body></w:document>";
|
||||||
|
assertEquals(9922, TableIndentNormalizer.bandOf(xml));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** bandOf: несколько body-level sectPr — полоса неоднозначна (−1). */
|
||||||
|
@Test
|
||||||
|
void bandOf_ambiguous_returnsMinusOne() {
|
||||||
|
String xml = doc("<w:p/>").replace("</w:sectPr></w:body>",
|
||||||
|
"</w:sectPr><w:sectPr><w:pgSz w:w=\"12240\"/></w:sectPr></w:body>");
|
||||||
|
assertEquals(-1, TableIndentNormalizer.bandOf(xml));
|
||||||
|
}
|
||||||
|
|
||||||
private static byte[] zip(Map<String, String> parts) throws IOException {
|
private static byte[] zip(Map<String, String> parts) throws IOException {
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1290
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,153 @@
|
|||||||
|
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/>"), "пустые абзацы-концы строк не выброшены");
|
||||||
|
// таблица переносится структурой, а не плоскими абзацами (TAP → w:tbl)
|
||||||
|
assertTrue(xml.contains("<w:tbl>"), "w:tbl потерян");
|
||||||
|
assertEquals(2, xml.split("<w:tr>", -1).length - 1, "строки таблицы");
|
||||||
|
assertEquals(4, xml.split("<w:tc>", -1).length - 1, "ячейки таблицы");
|
||||||
|
int tblEnd = xml.indexOf("</w:tbl>");
|
||||||
|
assertTrue(tblEnd > xml.indexOf("Ячейка 4"), "ячейки утёкли из w:tbl");
|
||||||
|
assertTrue(xml.contains("<w:gridCol"), "сетка таблицы потеряна");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void tableFixture_becomesTblWithImage() throws IOException {
|
||||||
|
byte[] docx = DocToDocx.convert(sample("ru-table-image.doc"));
|
||||||
|
String xml = documentXml(sample("ru-table-image.doc"));
|
||||||
|
assertTrue(xml.contains("<w:tbl>"), "таблица не перенесена структурой");
|
||||||
|
assertTrue(xml.contains("<w:gridCol"), "сетка потеряна");
|
||||||
|
boolean hasImage = false;
|
||||||
|
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||||
|
ZipEntry e;
|
||||||
|
while ((e = zip.getNextEntry()) != null) {
|
||||||
|
hasImage |= e.getName().startsWith("word/media/");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(hasImage, "картинка в фикстуре потеряна");
|
||||||
|
}
|
||||||
|
|
||||||
|
@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,172 @@
|
|||||||
|
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 scan_tDefTable_twoByteLength() {
|
||||||
|
// sprmTDefTable 0xD608 (§2.9.321): cb — 2 байта, «остаток + 1»;
|
||||||
|
// cb=304 > 255 — формула «1 + первый байт» сбилась бы на 49
|
||||||
|
byte[] buf = new byte[2 + 305 + 3];
|
||||||
|
buf[0] = 0x08;
|
||||||
|
buf[1] = (byte) 0xD6;
|
||||||
|
buf[2] = 0x30;
|
||||||
|
buf[3] = 0x01; // cb = 304
|
||||||
|
buf[2 + 305] = 0x35;
|
||||||
|
buf[3 + 305] = 0x08;
|
||||||
|
buf[4 + 305] = 0x01;
|
||||||
|
List<Integer> sizes = new ArrayList<>();
|
||||||
|
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> sizes.add(len));
|
||||||
|
assertEquals(List.of(305, 1), sizes, "второй Prl найден — разбор не сместился");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void scan_tDefTable_truncated_stops() {
|
||||||
|
byte[] buf = {0x08, (byte) 0xD6, 0x30, 0x01, 0x00}; // cb=304, данных нет
|
||||||
|
int[] count = {0};
|
||||||
|
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||||
|
assertEquals(0, count[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void scan_pChgTabsSentinel_stops() {
|
||||||
|
// PChgTabsPapxOperand (§2.9.183, 0xC60D): cb=0xFF длины не выражается —
|
||||||
|
// обрыв, «1+cb» сдвинул бы разбор на 1 байт
|
||||||
|
byte[] buf = {0x0D, (byte) 0xC6, (byte) 0xFF, 0x35, 0x08, 0x01};
|
||||||
|
int[] count = {0};
|
||||||
|
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||||
|
assertEquals(0, count[0], "0xFF-длина не должна сдвигать разбор на 1 байт");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void scan_pChgTabsSentinel_lengthByFormula() {
|
||||||
|
// sprmPChgTabs 0xC615 (§2.9.182): cb=0xFF — длина 3 + 4·cTabsDel +
|
||||||
|
// 3·cTabsAdd; здесь n=1, m=1 → 10, следующий Prl (0x0835) не съеден
|
||||||
|
byte[] buf = {0x15, (byte) 0xC6, (byte) 0xFF, 0x01,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x35, 0x08, 0x01};
|
||||||
|
List<Integer> seen = new ArrayList<>();
|
||||||
|
List<Integer> sizes = new ArrayList<>();
|
||||||
|
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> {
|
||||||
|
seen.add(sprm);
|
||||||
|
sizes.add(len);
|
||||||
|
});
|
||||||
|
assertEquals(List.of(0xC615, 0x0835), seen, "разбор не сместился и не оборвался");
|
||||||
|
assertEquals(List.of(10, 1), sizes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void indents_80FamilyNestAndDefaults() {
|
||||||
|
Grpprl.Indents empty = new Grpprl.Indents();
|
||||||
|
assertEquals(0, empty.left());
|
||||||
|
assertEquals(-1, empty.right());
|
||||||
|
assertEquals(Integer.MIN_VALUE, empty.left1());
|
||||||
|
// только 80-е семейство: nest80 к dxaLeft80, left180 со знаком, right80
|
||||||
|
byte[] only80 = {
|
||||||
|
(byte) 0x0F, (byte) 0x84, (byte) 0x80, 0x02, // dxaLeft80 = 640
|
||||||
|
(byte) 0x10, 0x46, 0x2C, 0x00, // nest80 = 44
|
||||||
|
0x11, (byte) 0x84, (byte) 0x98, (byte) 0xFE, // dxaLeft180 = −360
|
||||||
|
(byte) 0x0E, (byte) 0x84, 0x1E, 0x00, // dxaRight80 = 30
|
||||||
|
};
|
||||||
|
Grpprl.Indents ind = new Grpprl.Indents();
|
||||||
|
Grpprl.scan(only80, 0, only80.length, ind::prl);
|
||||||
|
assertEquals(684, ind.left(), "nest80 прибавляется к dxaLeft80");
|
||||||
|
assertEquals(-360, ind.left1(), "dxaLeft180 — XAS со знаком");
|
||||||
|
assertEquals(30, ind.right());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void indents_modernFamilySupersedes80() {
|
||||||
|
// хоть один современный sprm левого отступа → 80-е семейство целиком в стороне
|
||||||
|
byte[] mixed = {
|
||||||
|
(byte) 0x0F, (byte) 0x84, (byte) 0x80, 0x02, // dxaLeft80 = 640
|
||||||
|
(byte) 0x10, 0x46, 0x2C, 0x00, // nest80 = 44
|
||||||
|
(byte) 0x5E, (byte) 0x84, 0x10, 0x01, // dxaLeft = 272
|
||||||
|
};
|
||||||
|
Grpprl.Indents m = new Grpprl.Indents();
|
||||||
|
Grpprl.scan(mixed, 0, mixed.length, m::prl);
|
||||||
|
assertEquals(272, m.left(), "современное семейство вытесняет 80-е");
|
||||||
|
// современный nest к своему left; right и left1 — слияние last-wins
|
||||||
|
byte[] modern = {
|
||||||
|
(byte) 0x5E, (byte) 0x84, 0x10, 0x01, // dxaLeft = 272
|
||||||
|
0x5F, 0x46, 0x0A, 0x00, // nest = 10
|
||||||
|
(byte) 0x0E, (byte) 0x84, 0x1E, 0x00, // dxaRight80 = 30
|
||||||
|
(byte) 0x5D, (byte) 0x84, 0x2C, 0x01, // dxaRight = 300 — last-wins
|
||||||
|
0x11, (byte) 0x84, (byte) 0x98, (byte) 0xFE, // dxaLeft180 = −360
|
||||||
|
0x60, (byte) 0x84, 0x78, 0x00, // dxaLeft1 = 120 — last-wins
|
||||||
|
};
|
||||||
|
Grpprl.Indents md = new Grpprl.Indents();
|
||||||
|
Grpprl.scan(modern, 0, modern.length, md::prl);
|
||||||
|
assertEquals(282, md.left(), "nest прибавляется к dxaLeft");
|
||||||
|
assertEquals(300, md.right(), "right — слияние last-wins");
|
||||||
|
assertEquals(120, md.left1(), "left1 — слияние last-wins");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* §2.4.4: [x,x) — история НЕ определена (Word наследует полосы
|
||||||
|
* предыдущей секции); [x,x+1) — определена, но только guard-¶
|
||||||
|
* (явно пустой колонтитул, обрывающий наследование).
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void emptyVsGuardOnly() {
|
||||||
|
assertTrue(new Headers.Story(5, 5).empty());
|
||||||
|
assertFalse(new Headers.Story(5, 5).hasContent());
|
||||||
|
assertFalse(new Headers.Story(5, 6).empty());
|
||||||
|
assertFalse(new Headers.Story(5, 6).hasContent());
|
||||||
|
assertFalse(new Headers.Story(5, 7).empty());
|
||||||
|
assertTrue(new Headers.Story(5, 7).hasContent());
|
||||||
|
}
|
||||||
|
|
||||||
|
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,427 @@
|
|||||||
|
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.io.ByteArrayOutputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Списки [MS-DOC] на крафтовых байтовых потоках (образец {@link TablesTest}):
|
||||||
|
* PlfLst/LSTF/LVL → abstractNum (счёт LVL по fSimpleList, плейсхолдеры xst,
|
||||||
|
* MSONFC → ST_NumberFormat, ixchFollow → w:suff, grpprl уровня → w:ind/
|
||||||
|
* w:rFonts), PlfLfo/LFOLVL → w:num с w:startOverride/w:lvl; деградации
|
||||||
|
* (нулевые lcb, обрыв массива LVL, lsid без LSTF).
|
||||||
|
*/
|
||||||
|
class ListsTest {
|
||||||
|
|
||||||
|
// --- крафт -----------------------------------------------------------
|
||||||
|
|
||||||
|
/** LSTF (28 Б, §2.9.147): lsid + flags bit0 fSimpleList. */
|
||||||
|
private static byte[] lstf(int lsid, boolean simple) {
|
||||||
|
byte[] b = new byte[28];
|
||||||
|
put32(b, 0, lsid);
|
||||||
|
b[26] = (byte) (simple ? 1 : 0);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LVL (§2.9.149) = LVLF(28) + grpprlPapx + grpprlChpx + Xst. */
|
||||||
|
private static byte[] lvl(int startAt, int nfc, int jc, int follow, byte[] papx,
|
||||||
|
byte[] chpx, int[] xst) {
|
||||||
|
byte[] b = new byte[28];
|
||||||
|
put32(b, 0, startAt);
|
||||||
|
b[4] = (byte) nfc;
|
||||||
|
b[5] = (byte) jc;
|
||||||
|
b[15] = (byte) follow;
|
||||||
|
b[24] = (byte) chpx.length;
|
||||||
|
b[25] = (byte) papx.length;
|
||||||
|
byte[] x = new byte[2 + 2 * xst.length];
|
||||||
|
put16(x, 0, xst.length);
|
||||||
|
for (int i = 0; i < xst.length; i++) {
|
||||||
|
put16(x, 2 + 2 * i, xst[i]);
|
||||||
|
}
|
||||||
|
return concat(b, papx, chpx, x);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Плоский уровень без grpprl: decimal «%{ilvl+1}.» (плейсхолдер 0x0N). */
|
||||||
|
private static byte[] plainLvl(int level) {
|
||||||
|
return lvl(1, 0x00, 0, 0, new byte[0], new byte[0], new int[] {level, '.'});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** LFOLVL (§2.9.133): iStartAt + битполе (iLvl|fStartAt<<4|fFormatting<<5) + LVL. */
|
||||||
|
private static byte[] lfoLvl(int ilvl, boolean startAt, int start, boolean formatting,
|
||||||
|
byte[] lvlBytes) {
|
||||||
|
int bits = ilvl | (startAt ? 1 << 4 : 0) | (formatting ? 1 << 5 : 0);
|
||||||
|
return concat(u32(start), u32(bits), formatting ? lvlBytes : new byte[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PlfLfo: lfoMac + rgLfo[16] + rgLfoData (cp + rgLfoLvl). */
|
||||||
|
private static byte[] plfLfo(int lsid, int clfolvl, byte[] lfoData) {
|
||||||
|
byte[] lfo = new byte[16];
|
||||||
|
put32(lfo, 0, lsid);
|
||||||
|
lfo[12] = (byte) clfolvl;
|
||||||
|
return concat(u32(1), lfo, u32(0xFFFFFFFFL), lfoData);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SttbfFfn (§2.9.147 FontTable) с одним семейством на индексе ftc. */
|
||||||
|
private static FontTable fonts(String... names) {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
byte[] header = new byte[4];
|
||||||
|
put16(header, 0, names.length);
|
||||||
|
out.writeBytes(header);
|
||||||
|
for (String name : names) {
|
||||||
|
byte[] fam = (name + "\0").getBytes(StandardCharsets.UTF_16LE);
|
||||||
|
int cch = 39 + fam.length;
|
||||||
|
out.write(cch);
|
||||||
|
out.writeBytes(new byte[39]);
|
||||||
|
out.writeBytes(fam);
|
||||||
|
}
|
||||||
|
byte[] table = out.toByteArray();
|
||||||
|
return FontTable.read(table, 0, table.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Lists lists(byte[] plfLst, byte[] lvls, byte[] plfLfo, FontTable fonts) {
|
||||||
|
byte[] table = concat(plfLst, lvls, plfLfo);
|
||||||
|
long fcPlfLst = 0;
|
||||||
|
long lcbPlfLst = plfLst.length;
|
||||||
|
long fcPlfLfo = plfLst.length + lvls.length;
|
||||||
|
long lcbPlfLfo = plfLfo.length;
|
||||||
|
return Lists.read(table, fcPlfLst, lcbPlfLst, fcPlfLfo, lcbPlfLfo, fonts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PlfLst: заголовок cLst SHORT(2Б, §2.9.201) + LSTF-записи с fc+2. */
|
||||||
|
private static byte[] plfLst(byte[]... lstfs) {
|
||||||
|
byte[] head = u16(lstfs.length);
|
||||||
|
byte[][] all = new byte[lstfs.length + 1][];
|
||||||
|
all[0] = head;
|
||||||
|
System.arraycopy(lstfs, 0, all, 1, lstfs.length);
|
||||||
|
return concat(all);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- abstractNum -------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void multiLevelList_levelsAndPlaceholders() {
|
||||||
|
// LSTF lsid=100, 9 уровней: lvl0 decimal «%1.», lvl1 lowerLetter
|
||||||
|
// «%1-%2)» (плейсхолдеры 0x00/0x01) со startAt=3, остальные плоские
|
||||||
|
byte[] l0 = lvl(1, 0x00, 0, 0, new byte[0], new byte[0], new int[] {0, '.'});
|
||||||
|
byte[] l1 = lvl(3, 0x04, 0, 0, new byte[0], new byte[0],
|
||||||
|
new int[] {0, '-', 1, ')'});
|
||||||
|
byte[] rest = concat(plainLvl(2), plainLvl(3), plainLvl(4), plainLvl(5),
|
||||||
|
plainLvl(6), plainLvl(7), plainLvl(8));
|
||||||
|
Lists lists = lists(plfLst(lstf(100, false)), concat(l0, l1, rest),
|
||||||
|
new byte[0], fonts());
|
||||||
|
assertTrue(lists.hasNumbering());
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("<w:abstractNum w:abstractNumId=\"1\">"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/>"
|
||||||
|
+ "<w:numFmt w:val=\"decimal\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlText w:val=\"%1.\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvl w:ilvl=\"1\"><w:start w:val=\"3\"/>"
|
||||||
|
+ "<w:numFmt w:val=\"lowerLetter\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlText w:val=\"%1-%2)\"/>"),
|
||||||
|
"плейсхолдеры 0x00/0x01 → %1/%2: " + xml);
|
||||||
|
assertTrue(xml.contains("<w:lvl w:ilvl=\"8\">"), xml);
|
||||||
|
assertFalse(xml.contains("<w:num "), "PlfLfo нет — w:num быть не должно: " + xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void simpleList_getsOneLevel() {
|
||||||
|
// fSimpleList=1 → ровно 1 LVL; следующий LSTF получает свои 9
|
||||||
|
byte[] simple = plfLst(lstf(100, true), lstf(200, false));
|
||||||
|
byte[] lvls = concat(plainLvl(0), plainLvl(0), plainLvl(1), plainLvl(2),
|
||||||
|
plainLvl(3), plainLvl(4), plainLvl(5), plainLvl(6), plainLvl(7),
|
||||||
|
plainLvl(8));
|
||||||
|
Lists lists = lists(simple, lvls, new byte[0], fonts());
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
String abstract1 = xml.substring(xml.indexOf("<w:abstractNum w:abstractNumId=\"1\">"),
|
||||||
|
xml.indexOf("</w:abstractNum>"));
|
||||||
|
assertEquals(1, abstract1.split("<w:lvl ", -1).length - 1,
|
||||||
|
"fSimpleList → один LVL: " + abstract1);
|
||||||
|
assertTrue(xml.contains("<w:abstractNum w:abstractNumId=\"2\">"), xml);
|
||||||
|
assertEquals(9, xml.substring(xml.indexOf("<w:abstractNum w:abstractNumId=\"2\">"))
|
||||||
|
.split("<w:lvl ", -1).length - 1, "многоуровневый → 9 LVL");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bulletLevel_fontSuffAndText() {
|
||||||
|
// nfc=0x17 bullet, chpx ftc0=Symbol, xst = PUA 0xF0B7, ixchFollow=1 → space
|
||||||
|
byte[] chpx = {0x4F, 0x4A, 0, 0}; // sprmCRgFtc0 = 0
|
||||||
|
byte[] l0 = lvl(1, 0x17, 0, 1, new byte[0], chpx, new int[] {0xF0B7});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts("Symbol"));
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("<w:numFmt w:val=\"bullet\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:suff w:val=\"space\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:rFonts w:ascii=\"Symbol\" w:hAnsi=\"Symbol\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlText w:val=\"\uF0B7\"/>"),
|
||||||
|
"PUA-символ дословно (чинит SymbolFontNormalizer): " + xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void levelPapx_becomesInd() {
|
||||||
|
// grpprlPapx: sprmPDxaLeft=720 + sprmPDxaLeft1=−360 (XAS со знаком)
|
||||||
|
byte[] papx = concat(prl2(0x845E, 720),
|
||||||
|
new byte[] {0x60, (byte) 0x84, (byte) 0x98, (byte) 0xFE});
|
||||||
|
byte[] l0 = lvl(1, 0x00, 2, 2, papx, new byte[0], new int[] {0, '.'});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("<w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr>"),
|
||||||
|
xml);
|
||||||
|
assertTrue(xml.contains("<w:suff w:val=\"nothing\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlJc w:val=\"right\"/>"), xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void levelPapx80Variants_becomeInd() {
|
||||||
|
// grpprlPapx 80-вариантами: sprmPDxaLeft80=720 + sprmPDxaLeft180=−360
|
||||||
|
// → тот же w:ind, что у современного семейства (общий Grpprl.Indents)
|
||||||
|
byte[] papx = concat(prl2(0x840F, 720),
|
||||||
|
new byte[] {0x11, (byte) 0x84, (byte) 0x98, (byte) 0xFE});
|
||||||
|
byte[] l0 = lvl(1, 0x00, 0, 0, papx, new byte[0], new int[] {0, '.'});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
|
||||||
|
assertTrue(lists.numberingXml().contains(
|
||||||
|
"<w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr>"),
|
||||||
|
lists.numberingXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void literalPercent_doubled() {
|
||||||
|
byte[] l0 = lvl(1, 0x00, 0, 0, new byte[0], new byte[0],
|
||||||
|
new int[] {'%', '5', '0', '%', 0, '.'});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
|
||||||
|
// «%50%» + плейсхолдер 1 + «.» → «%%»+«50»+«%%»+«%1»+«.»
|
||||||
|
assertTrue(lists.numberingXml().contains("<w:lvlText w:val=\"%%50%%%1.\"/>"),
|
||||||
|
"литеральный % удваивается: " + lists.numberingXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void exoticNfc_fallsBackToDecimal() {
|
||||||
|
byte[] l0 = lvl(1, 0x0A, 0, 0, new byte[0], new byte[0], new int[] {'%', '1'});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
|
||||||
|
assertTrue(lists.numberingXml().contains("<w:numFmt w:val=\"decimal\"/>"),
|
||||||
|
"CJK-MSONFC → decimal: " + lists.numberingXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void knownNfc_mappedToStNumberFormat() {
|
||||||
|
int[] nfc = {0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x16, 0x39, 0x3A, 0x3B, 0xFF};
|
||||||
|
String[] st = {"upperRoman", "lowerRoman", "upperLetter", "ordinal",
|
||||||
|
"cardinalText", "ordinalText",
|
||||||
|
"decimalZero", "numberInDash", "russianLower", "russianUpper", "none"};
|
||||||
|
for (int i = 0; i < nfc.length; i++) {
|
||||||
|
byte[] l0 = lvl(1, nfc[i], 0, 0, new byte[0], new byte[0], new int[] {'%'});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
|
||||||
|
assertTrue(lists.numberingXml().contains("<w:numFmt w:val=\"" + st[i] + "\"/>"),
|
||||||
|
"nfc 0x" + Integer.toHexString(nfc[i]) + " → " + st[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void levelRich_jcFirstLineBoldSzAndEscapes() {
|
||||||
|
// papx: left=100 + left1=220 → firstLine; chpx: bold + hps=28 + ftc0=0;
|
||||||
|
// jc=1 → center; имя семейства с & < " → экранирование в w:rFonts
|
||||||
|
byte[] papx = concat(prl2(0x845E, 100), prl2(0x8460, 220));
|
||||||
|
byte[] chpx = concat(new byte[] {0x35, 0x08, 1},
|
||||||
|
new byte[] {0x43, 0x4A, 28, 0}, new byte[] {0x4F, 0x4A, 0, 0});
|
||||||
|
byte[] l0 = lvl(1, 0x00, 1, 1, papx, chpx, new int[] {'1', '.', ' '});
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0],
|
||||||
|
fonts("T&imes <New> \"Q\""));
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("<w:lvlJc w:val=\"center\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:ind w:left=\"100\" w:firstLine=\"220\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:b/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:sz w:val=\"28\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("w:ascii=\"T&imes <New> "Q"\""),
|
||||||
|
"«>» в атрибуте легален и не экранируется: " + xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- w:num / LFOLVL ------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lfo_numWithStartOverrideAndFormatting() {
|
||||||
|
byte[] l0 = plainLvl(0);
|
||||||
|
byte[] overrideLvl = lvl(1, 0x01, 0, 0, new byte[0], new byte[0],
|
||||||
|
new int[] {'%', '2', '.'});
|
||||||
|
byte[] data = concat(lfoLvl(0, true, 7, false, new byte[0]),
|
||||||
|
lfoLvl(1, false, 0, true, overrideLvl));
|
||||||
|
Lists lists = lists(plfLst(lstf(100, false)),
|
||||||
|
concat(l0, plainLvl(1), plainLvl(2), plainLvl(3), plainLvl(4),
|
||||||
|
plainLvl(5), plainLvl(6), plainLvl(7), plainLvl(8)),
|
||||||
|
plfLfo(100, 2, data), fonts());
|
||||||
|
assertTrue(lists.hasNum(1));
|
||||||
|
assertFalse(lists.hasNum(2));
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("<w:num w:numId=\"1\"><w:abstractNumId w:val=\"1\"/>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlOverride w:ilvl=\"0\">"
|
||||||
|
+ "<w:startOverride w:val=\"7\"/></w:lvlOverride>"), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlOverride w:ilvl=\"1\"><w:lvl w:ilvl=\"1\">"
|
||||||
|
+ "<w:start w:val=\"1\"/><w:numFmt w:val=\"upperRoman\"/>"), xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lfoWithoutMatchingLstf_hasNoNum() {
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), plainLvl(0),
|
||||||
|
plfLfo(999, 0, new byte[0]), fonts());
|
||||||
|
assertTrue(lists.hasNumbering());
|
||||||
|
assertFalse(lists.hasNum(1), "lsid без LSTF — num не эмитится");
|
||||||
|
assertFalse(lists.numberingXml().contains("<w:num "),
|
||||||
|
lists.numberingXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void zeroMacros_emptyTables() {
|
||||||
|
// lstfMac=0 / lfoMac=0 — пустые таблицы без падения
|
||||||
|
byte[] table = concat(u32(0), u32(0));
|
||||||
|
Lists lists = Lists.read(table, 0, 4, 4, 4, fonts());
|
||||||
|
assertFalse(lists.hasNumbering());
|
||||||
|
assertFalse(lists.hasNum(0));
|
||||||
|
assertFalse(lists.hasNum(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void truncatedSecondLstf_staysNull() {
|
||||||
|
// два многоуровневых LSTF, влезли 3 LVL: второй — null, LFO на него не цепляется
|
||||||
|
byte[] truncated = concat(plainLvl(0), plainLvl(1), plainLvl(2));
|
||||||
|
Lists lists = lists(plfLst(lstf(100, false), lstf(200, false)), truncated,
|
||||||
|
plfLfo(200, 0, new byte[0]), fonts());
|
||||||
|
assertTrue(lists.hasNumbering(), "первый LSTF валиден");
|
||||||
|
assertFalse(lists.hasNum(1), "lsid=200 указывает на null-LSTF");
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("w:abstractNumId=\"1\""), xml);
|
||||||
|
assertFalse(xml.contains("w:abstractNumId=\"2\""), xml);
|
||||||
|
assertFalse(xml.contains("<w:num "), xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void hostileLevelFields_degradeToInvalid() {
|
||||||
|
// cbPapx за пределами потока
|
||||||
|
assertFalse(lists(plfLst(lstf(100, false)), rawLvl(200), new byte[0], fonts())
|
||||||
|
.hasNumbering());
|
||||||
|
// заголовок xst обрезан: поток кончается сразу после grpprl
|
||||||
|
byte[] noXst = rawLvl(2, (byte) 0x62, (byte) 0x84);
|
||||||
|
assertFalse(lists(plfLst(lstf(100, false)), noXst, new byte[0], fonts())
|
||||||
|
.hasNumbering());
|
||||||
|
// враждебный cch
|
||||||
|
byte[] bigCch = concat(rawLvl(0), u16(0xFFFF));
|
||||||
|
assertFalse(lists(plfLst(lstf(100, false)), bigCch, new byte[0], fonts())
|
||||||
|
.hasNumbering());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lfoDataTruncated_keepsLfoWithoutOverrides() {
|
||||||
|
// clfolvl=1, но LFOData обрывается на cp / первом LFOLVL
|
||||||
|
assertFalse(lists(plfLst(lstf(100, true)), plainLvl(0),
|
||||||
|
plfLfo(100, 1, new byte[0]), fonts()).numberingXml()
|
||||||
|
.contains("lvlOverride"));
|
||||||
|
assertTrue(lists(plfLst(lstf(100, true)), plainLvl(0),
|
||||||
|
plfLfo(100, 1, u32(0)), fonts()).hasNum(1));
|
||||||
|
assertFalse(lists(plfLst(lstf(100, true)), plainLvl(0),
|
||||||
|
plfLfo(100, 1, u32(0)), fonts()).numberingXml()
|
||||||
|
.contains("lvlOverride"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lfoLvlFormattingTruncated_stopsOverrides() {
|
||||||
|
// fFormatting, но LVL обрезан — переопределение отброшено, num жив
|
||||||
|
byte[] data = concat(u32(0), u32(1 << 5), rawLvl(100));
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), plainLvl(0),
|
||||||
|
plfLfo(100, 1, data), fonts());
|
||||||
|
assertTrue(lists.hasNum(1));
|
||||||
|
assertFalse(lists.numberingXml().contains("lvlOverride"),
|
||||||
|
lists.numberingXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lfoLvlFlags_ilvlCapAndEmptyOverride() {
|
||||||
|
// ilvl=9 — за пределами уровней (скип); без fStartAt/fFormatting — пустой lvlOverride
|
||||||
|
byte[] data = concat(u32(0), u32(9), u32(0), u32(1), u32(0));
|
||||||
|
Lists lists = lists(plfLst(lstf(100, true)), plainLvl(0),
|
||||||
|
plfLfo(100, 2, data), fonts());
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertFalse(xml.contains("w:ilvl=\"9\""), xml);
|
||||||
|
assertTrue(xml.contains("<w:lvlOverride w:ilvl=\"1\"></w:lvlOverride>"), xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- деградации ----------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void zeroLcb_emptyLists() {
|
||||||
|
byte[] table = new byte[64];
|
||||||
|
Lists lists = Lists.read(table, 0, 0, 0, 0, fonts());
|
||||||
|
assertFalse(lists.hasNumbering());
|
||||||
|
assertFalse(lists.hasNum(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void truncatedLevelArray_keepsParsedLevels() {
|
||||||
|
// 9 уровней влезает только 3 — abstractNum с ilvl 0..2, без падения
|
||||||
|
byte[] full = concat(plainLvl(0), plainLvl(1), plainLvl(2), plainLvl(3),
|
||||||
|
plainLvl(4), plainLvl(5), plainLvl(6), plainLvl(7), plainLvl(8));
|
||||||
|
byte[] truncated = new byte[plainLvl(0).length * 3];
|
||||||
|
System.arraycopy(full, 0, truncated, 0, truncated.length);
|
||||||
|
Lists lists = lists(plfLst(lstf(100, false)), truncated, new byte[0], fonts());
|
||||||
|
assertTrue(lists.hasNumbering());
|
||||||
|
String xml = lists.numberingXml();
|
||||||
|
assertTrue(xml.contains("<w:lvl w:ilvl=\"2\">"), xml);
|
||||||
|
assertFalse(xml.contains("<w:lvl w:ilvl=\"3\">"), xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void garbageTable_emptyLists() {
|
||||||
|
byte[] table = "не PlfLst вообще".getBytes(StandardCharsets.UTF_8);
|
||||||
|
Lists lists = Lists.read(table, 2, 100, 2, 100, fonts());
|
||||||
|
assertFalse(lists.hasNumbering());
|
||||||
|
assertFalse(lists.hasNum(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- хелперы ---------------------------------------------------------
|
||||||
|
|
||||||
|
/** LVLF с заданным cbPapx и байтами grpprl (для guard-тестов). */
|
||||||
|
private static byte[] rawLvl(int cbPapx, byte... grpprl) {
|
||||||
|
byte[] b = new byte[28];
|
||||||
|
b[25] = (byte) cbPapx;
|
||||||
|
return concat(b, grpprl);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] u16(int v) {
|
||||||
|
byte[] b = new byte[2];
|
||||||
|
put16(b, 0, v);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] prl2(int sprm, int v) {
|
||||||
|
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] u32(long v) {
|
||||||
|
byte[] b = new byte[4];
|
||||||
|
put32(b, 0, (int) v);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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,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,167 @@
|
|||||||
|
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) {
|
||||||
|
return wordDocument(bx, shortForm, cb, grpprl, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] wordDocument(int bx, boolean shortForm, int cb,
|
||||||
|
byte[] grpprl, int istd) {
|
||||||
|
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] = (byte) istd;
|
||||||
|
wd[infkp + 3] = (byte) (istd >>> 8);
|
||||||
|
System.arraycopy(grpprl, 0, wd, infkp + 4, grpprl.length);
|
||||||
|
} else {
|
||||||
|
wd[infkp] = (byte) cb;
|
||||||
|
wd[infkp + 1] = (byte) istd;
|
||||||
|
wd[infkp + 2] = (byte) (istd >>> 8);
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void istd_extractedBothForms() {
|
||||||
|
PapxIndex longForm = PapxIndex.read(table(2), 0, 12,
|
||||||
|
wordDocument(11, false, 3, GRPRL_PB, 10));
|
||||||
|
assertEquals(10, longForm.istdFor(2048));
|
||||||
|
PapxIndex shortForm = PapxIndex.read(table(2), 0, 12,
|
||||||
|
wordDocument(11, true, 3, new byte[] {0x07, 0x24, 0x01, 0}, 11));
|
||||||
|
assertEquals(11, shortForm.istdFor(2048));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void istdOnly_emptyGrpprlKept() {
|
||||||
|
// cb=0, cb'=1 → GrpPrlAndIstd = istd(2), Prl'ов нет (§2.9.175):
|
||||||
|
// grpprl пустой, istd читается — стиль единственное свойство
|
||||||
|
PapxIndex idx = PapxIndex.read(table(2), 0, 12,
|
||||||
|
wordDocument(11, true, 1, new byte[0], 12));
|
||||||
|
assertArrayEquals(new byte[0], idx.grpprlFor(2048));
|
||||||
|
assertEquals(12, idx.istdFor(2048));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void istdFor_outsideRange_minusOne() {
|
||||||
|
PapxIndex idx = PapxIndex.read(table(2), 0, 12,
|
||||||
|
wordDocument(11, false, 3, GRPRL_PB, 10));
|
||||||
|
assertEquals(-1, idx.istdFor(2200), "вне диапазона — стиля нет");
|
||||||
|
}
|
||||||
|
|
||||||
|
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,216 @@
|
|||||||
|
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.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import ru.pjandro.wordpdf.ValidationException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Юниты {@link Sections} ([MS-DOC] §2.6.3, PlcfSed/Sepx): по-секционная
|
||||||
|
* геометрия и continuous из {@code list()}, одиночные аксессоры — последней
|
||||||
|
* секции, guard'ы aCP, пропуски битых Sepx.
|
||||||
|
*/
|
||||||
|
class SectionsTest {
|
||||||
|
|
||||||
|
/** PlcfSed из n секций; aCp = [0, 100, …, n·100], fcSepx[i] — адреса в wordDocument. */
|
||||||
|
private static byte[] plcfSed(int... fcSepxs) {
|
||||||
|
int n = fcSepxs.length;
|
||||||
|
int[] aCp = new int[n + 1];
|
||||||
|
for (int i = 0; i <= n; i++) {
|
||||||
|
aCp[i] = i * 100;
|
||||||
|
}
|
||||||
|
return plcfSed(aCp, fcSepxs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PlcfSed с произвольным aCp (n+1 значений) и fcSepx[i] в wordDocument. */
|
||||||
|
private static byte[] plcfSed(int[] aCp, 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, aCp[i]);
|
||||||
|
}
|
||||||
|
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], 500);
|
||||||
|
assertEquals(12240, s.pageWidth());
|
||||||
|
assertEquals(15840, s.pageHeight());
|
||||||
|
assertEquals(1440, s.marginLeft());
|
||||||
|
assertEquals(720, s.header());
|
||||||
|
assertEquals(0, s.continuousSectionEnds());
|
||||||
|
// одна неявная секция [0, ccpText) с дефолтами
|
||||||
|
List<Sections.Section> list = s.list();
|
||||||
|
assertEquals(1, list.size());
|
||||||
|
assertEquals(0, list.get(0).cpStart());
|
||||||
|
assertEquals(500, list.get(0).cpEnd());
|
||||||
|
assertFalse(list.get(0).continuous());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void badSed_rejected() {
|
||||||
|
byte[] t = plcfSed(0);
|
||||||
|
assertThrows(ValidationException.class, () -> Sections.read(t, 0, 21, new byte[0], 1000));
|
||||||
|
assertThrows(ValidationException.class,
|
||||||
|
() -> Sections.read(t, 0, t.length + 1, new byte[0], 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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, 1000);
|
||||||
|
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, 1000);
|
||||||
|
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, 1000);
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Две секции со своими Sepx: {@code list()} отдаёт CP-диапазон
|
||||||
|
* [aCP[i], aCP[i+1]) и геометрию КАЖДОЙ секции; continuous — из sprmSBkc
|
||||||
|
* своей секции (§2.6.3 SBkcOperand — разрыв, ЗАКАНЧИВАЮЩИЙ секцию);
|
||||||
|
* одиночные аксессоры — последней.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void multiSection_listPerSection() {
|
||||||
|
byte[] wd = new byte[4096];
|
||||||
|
sepx(wd, 64, concat(prl2(Grpprl.SPRM_S_XA_PAGE, 12240),
|
||||||
|
prl2(Grpprl.SPRM_S_YA_PAGE, 15840),
|
||||||
|
prl2(Grpprl.SPRM_S_DXA_LEFT, 1440),
|
||||||
|
new byte[] {0x09, 0x30, 0x00})); // sprmSBkc=bkcContinuous
|
||||||
|
sepx(wd, 128, concat(prl2(Grpprl.SPRM_S_XA_PAGE, 16838),
|
||||||
|
prl2(Grpprl.SPRM_S_YA_PAGE, 11906),
|
||||||
|
prl2(Grpprl.SPRM_S_DXA_LEFT, 720),
|
||||||
|
new byte[] {0x09, 0x30, 0x02})); // bkcNewPage
|
||||||
|
byte[] t = plcfSed(new int[] {0, 10, 25}, 64, 128);
|
||||||
|
Sections s = Sections.read(t, 0, t.length, wd, 25);
|
||||||
|
List<Sections.Section> list = s.list();
|
||||||
|
assertEquals(2, list.size());
|
||||||
|
Sections.Section s0 = list.get(0);
|
||||||
|
assertEquals(0, s0.cpStart());
|
||||||
|
assertEquals(10, s0.cpEnd());
|
||||||
|
assertEquals(12240, s0.pageWidth());
|
||||||
|
assertEquals(15840, s0.pageHeight());
|
||||||
|
assertEquals(1440, s0.marginLeft());
|
||||||
|
assertTrue(s0.continuous(), "sprmSBkc=0 у секции 0");
|
||||||
|
Sections.Section s1 = list.get(1);
|
||||||
|
assertEquals(10, s1.cpStart());
|
||||||
|
assertEquals(25, s1.cpEnd());
|
||||||
|
assertEquals(16838, s1.pageWidth());
|
||||||
|
assertEquals(11906, s1.pageHeight());
|
||||||
|
assertEquals(720, s1.marginLeft());
|
||||||
|
assertFalse(s1.continuous(), "bkcNewPage у секции 1");
|
||||||
|
// аксессоры — последней секции (подсчёт страниц не меняется)
|
||||||
|
assertEquals(16838, s.pageWidth());
|
||||||
|
assertEquals(720, s.marginLeft());
|
||||||
|
assertEquals(1, s.continuousSectionEnds());
|
||||||
|
}
|
||||||
|
|
||||||
|
@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, 1000);
|
||||||
|
// секции 0 и 1 — не последние: обе continuous считаются;
|
||||||
|
// секция 2 — последняя: bkc в оценку не идёт
|
||||||
|
assertEquals(2, s.continuousSectionEnds());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** §2.8.26: «MUST NOT contain duplicate CPs» — дубль и спад невозможны. */
|
||||||
|
@Test
|
||||||
|
void nonIncreasingAcp_rejected() {
|
||||||
|
byte[] dup = plcfSed(new int[] {0, 5, 5}, 0, 0);
|
||||||
|
assertThrows(ValidationException.class, () -> Sections.read(dup, 0, dup.length,
|
||||||
|
new byte[0], 1000));
|
||||||
|
byte[] down = plcfSed(new int[] {0, 7, 3}, 0, 0);
|
||||||
|
assertThrows(ValidationException.class, () -> Sections.read(down, 0, down.length,
|
||||||
|
new byte[0], 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Финальный aCP реальные файлы Word пишут за ccpText (page-numbers.doc:
|
||||||
|
* aCp[1]=108 при ccpText=33) — не отбраковка; конец последней секции
|
||||||
|
* клампится к ccpText.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void lastAcpBeyondText_clamped() {
|
||||||
|
byte[] t = plcfSed(new int[] {0, 101}, 0);
|
||||||
|
Sections s = Sections.read(t, 0, t.length, new byte[0], 100);
|
||||||
|
assertEquals(100, s.list().get(0).cpEnd());
|
||||||
|
}
|
||||||
|
|
||||||
|
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,257 @@
|
|||||||
|
package ru.pjandro.wordpdf.internal.doc;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Юниты {@link Styles} ([MS-DOC] §2.9.271/.272/.260/.308/.309, §2.4.6.5):
|
||||||
|
* крафтовый STSH — разбор LPStshi/LPStd/Std (stdf + xstzName + LPUpx),
|
||||||
|
* цепочка base-first, защита от циклов и битого STSH.
|
||||||
|
*/
|
||||||
|
class StylesTest {
|
||||||
|
|
||||||
|
/** jc=center (sprmPJc 0x2461, 1 байт). */
|
||||||
|
private static final byte[] JC_CENTER = {0x61, 0x24, 0x01};
|
||||||
|
/** left 720 (sprmPDxaLeft 0x845E, 2 байта). */
|
||||||
|
private static final byte[] LEFT_720 = {0x5E, (byte) 0x84, (byte) 0xD0, 0x02};
|
||||||
|
/** bold (sprmCBold 0x0835, toggle on). */
|
||||||
|
private static final byte[] BOLD = {0x35, 0x08, 0x01};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* STSH: cstd стилей, rglpstd с istd 10..(9+n); пустые слоты 0..9.
|
||||||
|
* Каждый стиль — Std(stdf + xstzName + cupx × LPUpx).
|
||||||
|
*/
|
||||||
|
private static byte[] stsh(int cstd, byte[]... stylesFrom10) {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
put16(out, 18); // cbStshi
|
||||||
|
put16(out, cstd); // cstd
|
||||||
|
put16(out, 0x0A); // cbSTDBaseInFile
|
||||||
|
out.write(new byte[14], 0, 14); // остальное STSHI
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
put16(out, 0); // пустые фиксированные стили
|
||||||
|
}
|
||||||
|
for (byte[] std : stylesFrom10) {
|
||||||
|
put16(out, std.length);
|
||||||
|
out.write(std, 0, std.length);
|
||||||
|
if (((2 + std.length) & 1) != 0) {
|
||||||
|
out.write(0); // LPStd на чётной границе (padding вне cbStd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Std: stk=1, istdBase, cupx по числу непустых UPX; xstzName cch=2. */
|
||||||
|
private static byte[] std(int sti, int stk, int istdBase, byte[] papx, byte[] chpx) {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
long base = sti | ((long) stk << 16) | ((long) istdBase << 20);
|
||||||
|
int cupx = (papx == null ? 0 : 1) + (chpx == null ? 0 : 1);
|
||||||
|
byte[] stdf = new byte[10];
|
||||||
|
stdf[0] = (byte) base;
|
||||||
|
stdf[1] = (byte) (base >>> 8);
|
||||||
|
stdf[2] = (byte) (base >>> 16);
|
||||||
|
stdf[3] = (byte) (base >>> 24);
|
||||||
|
stdf[4] = (byte) cupx;
|
||||||
|
out.write(stdf, 0, 10);
|
||||||
|
byte[] name = new byte[8]; // cch=2, "Ab", chTerm=0
|
||||||
|
put16(name, 0, 2);
|
||||||
|
name[2] = 'A';
|
||||||
|
name[4] = 'b';
|
||||||
|
out.write(name, 0, 8);
|
||||||
|
if (papx != null) {
|
||||||
|
byte[] data = new byte[2 + papx.length]; // UpxPapx: istd(2) + grpprl
|
||||||
|
System.arraycopy(papx, 0, data, 2, papx.length);
|
||||||
|
upx(out, data);
|
||||||
|
}
|
||||||
|
if (chpx != null) {
|
||||||
|
upx(out, chpx);
|
||||||
|
}
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void upx(ByteArrayOutputStream out, byte[] data) {
|
||||||
|
put16(out, data.length);
|
||||||
|
out.write(data, 0, data.length);
|
||||||
|
if ((data.length & 1) != 0) {
|
||||||
|
out.write(0); // LPUpx на чётной границе
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void put16(ByteArrayOutputStream out, int v) {
|
||||||
|
out.write(v & 0xFF);
|
||||||
|
out.write((v >>> 8) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void put16(byte[] b, int off, int v) {
|
||||||
|
b[off] = (byte) v;
|
||||||
|
b[off + 1] = (byte) (v >>> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void chain_baseFirstDerivedOverrides() {
|
||||||
|
// istd10: jc center + bold; istd11: base 10, + left 720
|
||||||
|
byte[] table = stsh(12,
|
||||||
|
std(65, 1, 0x0FFF, JC_CENTER, BOLD),
|
||||||
|
std(105, 1, 10, LEFT_720, null));
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertEquals(12, s.count());
|
||||||
|
byte[] chain = s.papxChain(11);
|
||||||
|
assertArrayEquals(concat(JC_CENTER, LEFT_720), chain,
|
||||||
|
"base-first: предок раньше потомка");
|
||||||
|
assertArrayEquals(BOLD, s.chpxChain(11), "CHPX наследуется по той же цепочке");
|
||||||
|
assertArrayEquals(JC_CENTER, s.papxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknownAndEmptyStil_emptyChain() {
|
||||||
|
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(0), "пустой слот — без свойств");
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(99), "istd за таблицей — без свойств");
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(-1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void baseBeyondTable_chainStops() {
|
||||||
|
// istdBase=99 (несуществующий) — цепочка обрывается на собственном grpprl
|
||||||
|
byte[] table = stsh(12, std(65, 1, 99, JC_CENTER, null));
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(JC_CENTER, s.papxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void selfBase_cycleTerminated() {
|
||||||
|
// istdBase=сам на себя — защита MAX_CHAIN: 16 копий, не бесконечность
|
||||||
|
byte[] table = stsh(12, std(65, 1, 10, JC_CENTER, null));
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
byte[] chain = s.papxChain(10);
|
||||||
|
assertEquals(16 * JC_CENTER.length, chain.length,
|
||||||
|
"цепочка обязана оборваться: " + Arrays.toString(chain));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void characterStyle_noParagraphProps() {
|
||||||
|
// stk=2 (символьный) — UpxPapx/UpxChpx не читаются (§2.9.267)
|
||||||
|
byte[] table = stsh(12, std(65, 2, 0x0FFF, JC_CENTER, BOLD));
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(10));
|
||||||
|
assertArrayEquals(new byte[0], s.chpxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void brokenStsh_emptyTableNotThrow() {
|
||||||
|
assertEmptyFor(new byte[0]);
|
||||||
|
assertEmptyFor(new byte[] {18, 0, 0, 0}); // cstd=0
|
||||||
|
assertEmptyFor(new byte[] {18, 0, 1, 0, 4, 0}); // cbSTDBaseInFile<5
|
||||||
|
assertEmptyFor(new byte[] {2, 0, 16, 0, 10, 0, 0}); // cbStshi<4
|
||||||
|
// Std обрезан по конец потока — слот не заполнен, цепочка пуста
|
||||||
|
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
|
||||||
|
byte[] truncated = Arrays.copyOf(table, 60);
|
||||||
|
Styles s = Styles.read(truncated, 0, truncated.length);
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(10));
|
||||||
|
assertArrayEquals(new byte[0], s.chpxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertEmptyFor(byte[] table) {
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertEquals(0, s.count(), "битый STSH — пустая таблица, не исключение");
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void zeroLcb_empty() {
|
||||||
|
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
|
||||||
|
assertEquals(0, Styles.read(table, 0, 0).count());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void badFc_empty() {
|
||||||
|
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
|
||||||
|
assertEquals(0, Styles.read(table, -1, table.length).count(), "fc<0");
|
||||||
|
assertEquals(0, Styles.read(table, table.length - 3, 3).count(),
|
||||||
|
"STSHI-заголовок не влезает в поток");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void hugeCstd_empty() {
|
||||||
|
// cstd ≥ 0x0FFE — зарезервировано (§2.9.271), таблица пустая
|
||||||
|
byte[] table = stsh(0x0FFE, std(65, 1, 0x0FFF, JC_CENTER, null));
|
||||||
|
assertEquals(0, Styles.read(table, 0, table.length).count());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void oddStshi_parsedWithPadding() {
|
||||||
|
// cbStshi=19 (нечётный) — LPStd-массив начинается со следующего чётного
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
put16(out, 19); // cbStshi — нечётный
|
||||||
|
put16(out, 11); // cstd
|
||||||
|
put16(out, 0x0A); // cbSTDBaseInFile
|
||||||
|
out.write(new byte[15], 0, 15); // остальное STSHI (19 − 4)
|
||||||
|
out.write(0); // padding до чётной границы
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
put16(out, 0); // пустые фиксированные стили
|
||||||
|
}
|
||||||
|
byte[] s = std(65, 1, 0x0FFF, JC_CENTER, null);
|
||||||
|
put16(out, s.length);
|
||||||
|
out.write(s, 0, s.length);
|
||||||
|
byte[] table = out.toByteArray();
|
||||||
|
Styles st = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(JC_CENTER, st.papxChain(10), "нечётный cbStshi — padding");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void stdWithoutName_noProps() {
|
||||||
|
// cbStd = только stdf — xstzName не влезает, стиль без свойств
|
||||||
|
byte[] table = stsh(12, new byte[10]);
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void upxBeyondStd_stops() {
|
||||||
|
// cupx=1, LPUpx вылезает за Std — разбор UPX обрывается (§2.9.271)
|
||||||
|
byte[] stdf = new byte[10];
|
||||||
|
stdf[4] = 1; // cupx=1
|
||||||
|
byte[] name = new byte[8];
|
||||||
|
put16(name, 0, 2);
|
||||||
|
name[2] = 'A';
|
||||||
|
name[4] = 'b';
|
||||||
|
byte[] raw = concat(concat(stdf, name), new byte[] {6, 0, 1, 2});
|
||||||
|
byte[] table = stsh(12, raw);
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void emptyUpxPapx_noProps() {
|
||||||
|
// UpxPapx с cbUpx=0 — ни istd, ни grpprl; UpxChpx на месте i=0 не читается
|
||||||
|
byte[] stdf = new byte[10];
|
||||||
|
long base = 65 | (1L << 16) | (0xFFFL << 20);
|
||||||
|
stdf[0] = (byte) base;
|
||||||
|
stdf[1] = (byte) (base >>> 8);
|
||||||
|
stdf[2] = (byte) (base >>> 16);
|
||||||
|
stdf[3] = (byte) (base >>> 24);
|
||||||
|
stdf[4] = 1; // cupx=1
|
||||||
|
byte[] name = new byte[8];
|
||||||
|
put16(name, 0, 2);
|
||||||
|
name[2] = 'A';
|
||||||
|
name[4] = 'b';
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
out.write(stdf, 0, 10);
|
||||||
|
out.write(name, 0, 8);
|
||||||
|
upx(out, new byte[0]); // cbUpx=0
|
||||||
|
byte[] table = stsh(12, out.toByteArray());
|
||||||
|
Styles s = Styles.read(table, 0, table.length);
|
||||||
|
assertArrayEquals(new byte[0], s.papxChain(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] concat(byte[] a, byte[] b) {
|
||||||
|
byte[] out = new byte[a.length + b.length];
|
||||||
|
System.arraycopy(a, 0, out, 0, a.length);
|
||||||
|
System.arraycopy(b, 0, out, a.length, b.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
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.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Юниты {@link Tables} ([MS-DOC] §2.6.3, §2.9.321/.302/.303/.39/.171):
|
||||||
|
* TAP TTP-абзаца → сетка (ширины из rgdxaCenter, сдвиг от поля) и границы
|
||||||
|
* w:tblBorders; деградация в {@code null} на битом/отсутствующем
|
||||||
|
* sprmTDefTable.
|
||||||
|
*/
|
||||||
|
class TablesTest {
|
||||||
|
|
||||||
|
/** TDefTableOperand: ncols + centers (без rgTc80 — он не читается). */
|
||||||
|
private static byte[] defTable(int[] centers) {
|
||||||
|
byte[] op = new byte[3 + 2 * centers.length];
|
||||||
|
op[0] = (byte) (op.length - 2 + 1 & 0xFF);
|
||||||
|
op[1] = (byte) ((op.length - 2 + 1) >>> 8);
|
||||||
|
op[2] = (byte) (centers.length - 1);
|
||||||
|
for (int i = 0; i < centers.length; i++) {
|
||||||
|
op[3 + 2 * i] = (byte) centers[i];
|
||||||
|
op[4 + 2 * i] = (byte) (centers[i] >>> 8);
|
||||||
|
}
|
||||||
|
return concat(new byte[] {0x08, (byte) 0xD6}, op);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TableBordersOperand: 6 × Brc (cv + dptLineWidth + brcType + флаги). */
|
||||||
|
private static byte[] borders(int[][] brcs) {
|
||||||
|
byte[] op = new byte[1 + 6 * 8];
|
||||||
|
op[0] = 0x30;
|
||||||
|
for (int i = 0; i < brcs.length && i < 6; i++) {
|
||||||
|
int b = 1 + i * 8;
|
||||||
|
op[b] = (byte) brcs[i][0]; // R
|
||||||
|
op[b + 1] = (byte) brcs[i][1]; // G
|
||||||
|
op[b + 2] = (byte) brcs[i][2]; // B
|
||||||
|
op[b + 3] = (byte) brcs[i][3]; // fAuto (0xFF — auto)
|
||||||
|
op[b + 4] = (byte) brcs[i][4]; // dptLineWidth
|
||||||
|
op[b + 5] = (byte) brcs[i][5]; // brcType
|
||||||
|
}
|
||||||
|
return concat(new byte[] {0x13, (byte) 0xD6}, op);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TableBordersOperand80: 6 × Brc80 (dptLineWidth + brcType + ico + флаги). */
|
||||||
|
private static byte[] borders80(int[][] brc80s) {
|
||||||
|
byte[] op = new byte[1 + 6 * 4];
|
||||||
|
op[0] = 0x18;
|
||||||
|
for (int i = 0; i < brc80s.length && i < 6; i++) {
|
||||||
|
int b = 1 + i * 4;
|
||||||
|
op[b] = (byte) brc80s[i][0]; // dptLineWidth
|
||||||
|
op[b + 1] = (byte) brc80s[i][1]; // brcType
|
||||||
|
op[b + 2] = (byte) brc80s[i][2]; // ico
|
||||||
|
}
|
||||||
|
return concat(new byte[] {0x05, (byte) 0xD6}, op);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prl выравнивания таблицы: sprmTJc (0x548A) / sprmTJc90 (0x5400), u16. */
|
||||||
|
private static byte[] tblJc(int sprm, int value) {
|
||||||
|
return concat(new byte[] {(byte) (sprm & 0xFF), (byte) (sprm >>> 8)},
|
||||||
|
new byte[] {(byte) value, (byte) (value >>> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void grid_widthsAndIndent() {
|
||||||
|
Tables.Grid g = Tables.parse(defTable(new int[] {100, 910, 1995}));
|
||||||
|
assertEquals(2, g.colWidths().length);
|
||||||
|
assertEquals(810, g.colWidths()[0]);
|
||||||
|
assertEquals(1085, g.colWidths()[1]);
|
||||||
|
assertEquals(100, g.indent(), "первый center — сдвиг от поля");
|
||||||
|
assertEquals("", g.bordersXml(), "без sprmTTableBorders — границ нет");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void grid_negativeIndent() {
|
||||||
|
// XAS со знаком (0xFF9C = −100) — таблица залезает на поле
|
||||||
|
Tables.Grid g = Tables.parse(defTable(new int[] {-100, 810}));
|
||||||
|
assertEquals(-100, g.indent());
|
||||||
|
assertEquals(910, g.colWidths()[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sprmTJc_centerInTap() {
|
||||||
|
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
|
||||||
|
tblJc(Grpprl.SPRM_T_JC, 1)));
|
||||||
|
assertEquals("center", g.tblJc());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sprmTJc90_right_noModern() {
|
||||||
|
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
|
||||||
|
tblJc(Grpprl.SPRM_T_JC90, 2)));
|
||||||
|
assertEquals("right", g.tblJc());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sprmTJc_modernWinsOver90() {
|
||||||
|
// современный перекрывает 90-вариант в любом порядке (тот же паттерн,
|
||||||
|
// что у d613 над d605)
|
||||||
|
assertEquals("center", Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
|
||||||
|
tblJc(Grpprl.SPRM_T_JC, 1), tblJc(Grpprl.SPRM_T_JC90, 2))).tblJc());
|
||||||
|
assertEquals("center", Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
|
||||||
|
tblJc(Grpprl.SPRM_T_JC90, 2), tblJc(Grpprl.SPRM_T_JC, 1))).tblJc());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sprmTJc_left_omitted() {
|
||||||
|
// 0 = left (дефолт) → элемент не эмитится; валидных значений больше нет (§2.6.3)
|
||||||
|
assertNull(Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
|
||||||
|
tblJc(Grpprl.SPRM_T_JC, 0))).tblJc());
|
||||||
|
assertNull(Tables.parse(defTable(new int[] {0, 3000, 6000})).tblJc(),
|
||||||
|
"без sprmTJc — left");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void noDefTable_null() {
|
||||||
|
assertNull(Tables.parse(borders(new int[][] {{0, 0, 0, 0xFF, 4, 1}})),
|
||||||
|
"нет sprmTDefTable — сетку построить нельзя");
|
||||||
|
assertNull(Tables.parse(new byte[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void badDefTable_null() {
|
||||||
|
assertNull(Tables.parse(defTable(new int[] {0, 0, 100})), "нулевая ширина");
|
||||||
|
assertNull(Tables.parse(defTable(new int[] {500, 400})), "отрицательная ширина");
|
||||||
|
byte[] ncolsZero = defTable(new int[] {0, 100});
|
||||||
|
ncolsZero[4] = 0; // ncols=0 (§2.9.321: 1..63)
|
||||||
|
assertNull(Tables.parse(ncolsZero));
|
||||||
|
byte[] truncated = {0x08, (byte) 0xD6, 0x04, 0x00, 0x02, 0x20, 0x03};
|
||||||
|
assertNull(Tables.parse(truncated), "centers не влезают в operand");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void borders_d613_typesColorsAndSkip() {
|
||||||
|
Tables.Grid g = Tables.parse(concat(
|
||||||
|
defTable(new int[] {0, 100}),
|
||||||
|
borders(new int[][] {
|
||||||
|
{0xFF, 0, 0, 0, 4, 1}, // top: single, красный 4/8pt
|
||||||
|
{0, 0, 0, 0, 0, 0}, // left: brcType=0 — не эмитится
|
||||||
|
{0, 0, 0, 0xFF, 12, 3}, // bottom: double, auto-цвет
|
||||||
|
{0, 0, 0, 0, 64, 0x40}, // right: brcType≥0x40 → sz×8
|
||||||
|
})));
|
||||||
|
String xml = g.bordersXml();
|
||||||
|
assertTrue(xml.contains("<w:top w:val=\"single\" w:sz=\"4\" w:color=\"FF0000\""), xml);
|
||||||
|
assertFalse(xml.contains("w:left"), "brcType=0 не эмитится: " + xml);
|
||||||
|
assertTrue(xml.contains("<w:bottom w:val=\"double\" w:sz=\"12\""), xml);
|
||||||
|
assertFalse(xml.contains("<w:bottom w:val=\"double\" w:sz=\"12\" w:color"),
|
||||||
|
"fAuto цвет не пишет: " + xml);
|
||||||
|
assertTrue(xml.contains("w:sz=\"512\""), "brcType 0x40: ширина в пунктах ×8: " + xml);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void borders80_fallbackAndPrecedence() {
|
||||||
|
Tables.Grid only80 = Tables.parse(concat(
|
||||||
|
defTable(new int[] {0, 100}),
|
||||||
|
borders80(new int[][] {{1, 1, 2}}))); // ico=2 → blue (§2.9.171)
|
||||||
|
String xml = only80.bordersXml();
|
||||||
|
assertTrue(xml.contains("<w:top w:val=\"single\" w:sz=\"2\""),
|
||||||
|
"dptLineWidth<2 → 2 (§2.9.37): " + xml);
|
||||||
|
assertTrue(xml.contains("w:color=\"0000FF\""), "ico→цвет: " + xml);
|
||||||
|
Tables.Grid both = Tables.parse(concat(
|
||||||
|
defTable(new int[] {0, 100}),
|
||||||
|
borders(new int[][] {{0xFF, 0, 0, 0, 4, 1}}),
|
||||||
|
borders80(new int[][] {{8, 3, 0}})));
|
||||||
|
assertTrue(both.bordersXml().contains("<w:top w:val=\"single\""),
|
||||||
|
"0xD613 приоритетнее 0xD605: " + both.bordersXml());
|
||||||
|
assertFalse(both.bordersXml().contains("double"), "0xD605 проигнорирован: "
|
||||||
|
+ both.bordersXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknownBrcType_fallsBackToSingle() {
|
||||||
|
Tables.Grid g = Tables.parse(concat(
|
||||||
|
defTable(new int[] {0, 100}),
|
||||||
|
borders(new int[][] {{0, 0, 0, 0xFF, 4, 0x7F}})));
|
||||||
|
assertTrue(g.bordersXml().contains("w:val=\"single\""), g.bordersXml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void borderVal_fullStBorderTable() {
|
||||||
|
// ST_Border §2.9.39: каждый brcType — своё имя ST_Border
|
||||||
|
assertEquals("single", Tables.borderVal(0x01));
|
||||||
|
assertEquals("double", Tables.borderVal(0x03));
|
||||||
|
assertEquals("dotted", Tables.borderVal(0x06));
|
||||||
|
assertEquals("dashed", Tables.borderVal(0x07));
|
||||||
|
assertEquals("dotDash", Tables.borderVal(0x08));
|
||||||
|
assertEquals("dotDotDash", Tables.borderVal(0x09));
|
||||||
|
assertEquals("triple", Tables.borderVal(0x0A));
|
||||||
|
assertEquals("thinThickSmallGap", Tables.borderVal(0x0B));
|
||||||
|
assertEquals("thickThinSmallGap", Tables.borderVal(0x0C));
|
||||||
|
assertEquals("thinThickThinSmallGap", Tables.borderVal(0x0D));
|
||||||
|
assertEquals("thinThickMediumGap", Tables.borderVal(0x0E));
|
||||||
|
assertEquals("thickThinMediumGap", Tables.borderVal(0x0F));
|
||||||
|
assertEquals("thinThickThinMediumGap", Tables.borderVal(0x10));
|
||||||
|
assertEquals("thinThickLargeGap", Tables.borderVal(0x11));
|
||||||
|
assertEquals("thickThinLargeGap", Tables.borderVal(0x12));
|
||||||
|
assertEquals("thinThickThinLargeGap", Tables.borderVal(0x13));
|
||||||
|
assertEquals("wave", Tables.borderVal(0x14));
|
||||||
|
assertEquals("doubleWave", Tables.borderVal(0x15));
|
||||||
|
assertEquals("dashSmallGap", Tables.borderVal(0x16));
|
||||||
|
assertEquals("dashDotStroked", Tables.borderVal(0x17));
|
||||||
|
assertEquals("threeDEmboss", Tables.borderVal(0x18));
|
||||||
|
assertEquals("threeDEngrave", Tables.borderVal(0x19));
|
||||||
|
assertEquals("outset", Tables.borderVal(0x1A));
|
||||||
|
assertEquals("outset", Tables.borderVal(0x1B));
|
||||||
|
assertEquals("single", Tables.borderVal(0x02), "неизвестный тип — single");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void malformedOperands_ignored() {
|
||||||
|
// sprmTDefTable с operand < 3 байт — пропускается сканером
|
||||||
|
assertNull(Tables.parse(new byte[] {0x08, (byte) 0xD6, 0x02, 0x00, 0x01}),
|
||||||
|
"operand<3 — TDefTable игнорируется");
|
||||||
|
byte[] ncolsWide = defTable(new int[] {0, 100});
|
||||||
|
ncolsWide[4] = 64; // ncols=64 > 63 (§2.9.321)
|
||||||
|
assertNull(Tables.parse(ncolsWide));
|
||||||
|
// границы неверной длины (≠0x31 / ≠0x19) — игнор, сетка без границ
|
||||||
|
byte[] bad613 = concat(new byte[] {0x13, (byte) 0xD6, 0x10}, new byte[0x10]);
|
||||||
|
byte[] bad605 = {0x05, (byte) 0xD6, 0x04, 0x01, 0x02, 0x03, 0x04};
|
||||||
|
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 100}), bad613, bad605));
|
||||||
|
assertEquals("", g.bordersXml(), "длина не по §2.9.302/.303 — границы игнорируются");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void borders80_icoBeyondPalette_noColor() {
|
||||||
|
// ico за таблицей §2.9.171 — цвет не пишется (FOP возьмёт auto)
|
||||||
|
Tables.Grid g = Tables.parse(concat(
|
||||||
|
defTable(new int[] {0, 100}),
|
||||||
|
borders80(new int[][] {{4, 1, 0xFF}})));
|
||||||
|
assertTrue(g.bordersXml().contains("<w:top"), g.bordersXml());
|
||||||
|
assertFalse(g.bordersXml().contains("w:color"), "ico=0xFF — цвета нет: "
|
||||||
|
+ g.bordersXml());
|
||||||
|
}
|
||||||
|
}
|
||||||
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.
@@ -64,7 +64,7 @@ export async function convertDocx(
|
|||||||
// флаг i обязателен; фолбэк — имя исходника с заменой расширения
|
// флаг i обязателен; фолбэк — имя исходника с заменой расширения
|
||||||
const cd = resp.headers.get('Content-Disposition') ?? ''
|
const cd = resp.headers.get('Content-Disposition') ?? ''
|
||||||
const m = /filename\*=utf-8''([^;]+)/i.exec(cd)
|
const m = /filename\*=utf-8''([^;]+)/i.exec(cd)
|
||||||
const filename = m ? decodeURIComponent(m[1]) : file.name.replace(/\.docx$/i, '') + '.pdf'
|
const filename = m ? decodeURIComponent(m[1]) : file.name.replace(/\.docx?$/i, '') + '.pdf'
|
||||||
const blob = await resp.blob()
|
const blob = await resp.blob()
|
||||||
return { blob, filename }
|
return { blob, filename }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ export default function App() {
|
|||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-semibold">Word → PDF</h1>
|
<h1 className="text-2xl font-semibold">Word → PDF</h1>
|
||||||
<p className="mt-1 text-sm text-muted">
|
<p className="mt-1 text-sm text-muted">
|
||||||
docx → PDF на docx4j + Apache FOP. Лимиты задаёт сервер;
|
docx/doc → PDF на docx4j + Apache FOP. Лимиты задаёт сервер;
|
||||||
переопределение из формы убрано.
|
переопределение из формы убрано.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Зона drag&drop + клик для выбора .docx. Скрытый input[type=file] —
|
* Зона drag&drop + клик для выбора .docx/.doc. Скрытый input[type=file] —
|
||||||
* единственный источник выбора; drop берёт первый файл.
|
* единственный источник выбора; drop берёт первый файл.
|
||||||
*/
|
*/
|
||||||
export default function DropZone({ file, disabled, onSelect }: Props) {
|
export default function DropZone({ file, disabled, onSelect }: Props) {
|
||||||
@@ -53,7 +53,7 @@ export default function DropZone({ file, disabled, onSelect }: Props) {
|
|||||||
<path d="M12 16V4m0 0-4 4m4-4 4 4" />
|
<path d="M12 16V4m0 0-4 4m4-4 4 4" />
|
||||||
<path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" />
|
<path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" />
|
||||||
</svg>
|
</svg>
|
||||||
<span>Перетащите .docx сюда или нажмите для выбора</span>
|
<span>Перетащите .docx или .doc сюда или нажмите для выбора</span>
|
||||||
{file && (
|
{file && (
|
||||||
<span className="text-sm text-muted">
|
<span className="text-sm text-muted">
|
||||||
{file.name} · {(file.size / 1024).toFixed(0)} КБ
|
{file.name} · {(file.size / 1024).toFixed(0)} КБ
|
||||||
@@ -62,7 +62,7 @@ export default function DropZone({ file, disabled, onSelect }: Props) {
|
|||||||
<input
|
<input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
type="file"
|
type="file"
|
||||||
accept=".docx"
|
accept=".docx,.doc"
|
||||||
className="sr-only"
|
className="sr-only"
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user