Мост .doc: перенос гиперссылок HYPERLINK в PDF через w:hyperlink + внешние rels
- DocxBody: парсер hyperlinkUrl (инструкция HYPERLINK, обязательная схема RFC 3986; деградации \l/без схемы/битая кавычка/control-символы), эмиссия <w:hyperlink r:id="hlN"> на FIELD_SEPARATOR..FIELD_END, баланс тегов при поле через границу абзацев, сброс захвата инструкции на FIELD_END (поля без разделителя более не глотают текст) - DocxWriter.write: внешние rels hl0… TargetMode="External" с экранированием - Тесты: 6 юнитов DocToDocxFormattingTest (крафт POIFS, батарея парсера) + WordPdfConverterTest#docHyperlink_linkAnnotationClickable (PDFBox-аннотация /URI на сквозном .doc→PDF)
This commit is contained in:
@@ -7,9 +7,11 @@ import java.util.ArrayDeque;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Deque;
|
import java.util.Deque;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Мост бинарного .doc (Word 97–2003) → минимальный transitional-.docx.
|
* Мост бинарного .doc (Word 97–2003) → минимальный transitional-.docx.
|
||||||
@@ -31,8 +33,11 @@ import java.util.Map;
|
|||||||
* семантика рестартов списков (fNoRestart/ilvlRestartLim), fLegal,
|
* семантика рестартов списков (fNoRestart/ilvlRestartLim), fLegal,
|
||||||
* объединённые/вложенные ячейки и бордюры TC80; объекты/сноски/комментарии
|
* объединённые/вложенные ячейки и бордюры TC80; объекты/сноски/комментарии
|
||||||
* (0x01/0x02/0x05/0x08) и инструкции полей (0x13–0x14) выбрасываются,
|
* (0x01/0x02/0x05/0x08) и инструкции полей (0x13–0x14) выбрасываются,
|
||||||
* результат поля (0x14–0x15) остаётся; прочие управляющие символы не
|
* результат поля (0x14–0x15) остаётся; поле {@code HYPERLINK} в основном
|
||||||
* эмитятся.</p>
|
* тексте переносится как {@code w:hyperlink} с внешней rels-связью на URL из
|
||||||
|
* инструкции ([MS-DOC] §2.4.4; деградации в плоский текст: якорный
|
||||||
|
* переключатель {@code \l}, URL без схемы RFC 3986, ссылки в колонтитуках);
|
||||||
|
* прочие управляющие символы не эмитятся.</p>
|
||||||
*
|
*
|
||||||
* <p>Контракт ошибок: любой некорректный вход (не CFB, не Word, шифрование,
|
* <p>Контракт ошибок: любой некорректный вход (не CFB, не Word, шифрование,
|
||||||
* Word 6/95, обрезка, цикл в цепочках, страницы сверх лимита) —
|
* Word 6/95, обрезка, цикл в цепочках, страницы сверх лимита) —
|
||||||
@@ -146,7 +151,9 @@ public final class DocToDocx {
|
|||||||
ftrRel[i] = "rId" + parts.size();
|
ftrRel[i] = "rId" + parts.size();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return DocxWriter.write(body.build(secs, hdrRel, ftrRel), parts);
|
// hyperlinks наполняются внутри build (body-pass); rels пишутся после
|
||||||
|
String bodyXml = body.build(secs, hdrRel, ftrRel);
|
||||||
|
return DocxWriter.write(bodyXml, parts, body.hyperlinks());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -160,7 +167,7 @@ public final class DocToDocx {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Текст CP 0..ccpText → XML-тело {@code <w:body>}. */
|
/** Текст CP 0..ccpText → XML-тело {@code <w:body>}. */
|
||||||
private static final class DocxBody {
|
static final class DocxBody {
|
||||||
|
|
||||||
/** Длина операнда LSPD: dyaLine (i16) + fMultLinespace (i16), §2.9.181. */
|
/** Длина операнда LSPD: dyaLine (i16) + fMultLinespace (i16), §2.9.181. */
|
||||||
private static final int LSPD_OPERAND_LEN = 4;
|
private static final int LSPD_OPERAND_LEN = 4;
|
||||||
@@ -168,6 +175,15 @@ public final class DocToDocx {
|
|||||||
private static final int FMULT_MULTIPLIER = 1;
|
private static final int FMULT_MULTIPLIER = 1;
|
||||||
/** w:gridSpan эмитится только при покрытии ≥2 колонок tblGrid (§17.4.65). */
|
/** w:gridSpan эмитится только при покрытии ≥2 колонок tblGrid (§17.4.65). */
|
||||||
private static final int MIN_GRID_SPAN = 2;
|
private static final int MIN_GRID_SPAN = 2;
|
||||||
|
/** Схема URL в начале строки (RFC 3986 §3.1), lookingAt. */
|
||||||
|
private static final Pattern URL_SCHEME =
|
||||||
|
Pattern.compile("[A-Za-z][A-Za-z0-9+.\\-]*:");
|
||||||
|
/** ASCII DEL — управляющий символ, невалидный в URL. */
|
||||||
|
private static final char DEL = 0x7F;
|
||||||
|
/** Кавычка-обёртка URL в инструкции HYPERLINK. */
|
||||||
|
private static final char QUOTE = '"';
|
||||||
|
/** Переключатель якорной ссылки Word. */
|
||||||
|
private static final String ANCHOR_SWITCH = "\\l";
|
||||||
|
|
||||||
private final PieceTable pieces;
|
private final PieceTable pieces;
|
||||||
private final ChpxIndex chpx;
|
private final ChpxIndex chpx;
|
||||||
@@ -183,6 +199,14 @@ public final class DocToDocx {
|
|||||||
/** Части пакета (колонтитуки + media); id связи = rId{позиция+1}. */
|
/** Части пакета (колонтитуки + media); id связи = rId{позиция+1}. */
|
||||||
private final List<DocxWriter.Part> parts;
|
private final List<DocxWriter.Part> parts;
|
||||||
private final Deque<Boolean> fieldStack = new ArrayDeque<>();
|
private final Deque<Boolean> fieldStack = new ArrayDeque<>();
|
||||||
|
/** Флаг «поле открыло w:hyperlink», параллельно {@link #fieldStack}. */
|
||||||
|
private final Deque<Boolean> linkStack = new ArrayDeque<>();
|
||||||
|
/** Id открытых ссылок — переоткрыть теги после границы абзаца. */
|
||||||
|
private final Deque<String> openLinkIds = new ArrayDeque<>();
|
||||||
|
/** Сколько тегов ссылки открыто в текущем абзаце (закрываются на границе). */
|
||||||
|
private int linksOpenInPara;
|
||||||
|
/** Targets внешних ссылок; id связи — {@code "hl" + индекс}. */
|
||||||
|
private final List<String> hyperlinks = new ArrayList<>();
|
||||||
/** Состояние полей текущего buildRange (сбрасывается на входе). */
|
/** Состояние полей текущего buildRange (сбрасывается на входе). */
|
||||||
private boolean fieldsAsSimple;
|
private boolean fieldsAsSimple;
|
||||||
private final StringBuilder instr = new StringBuilder();
|
private final StringBuilder instr = new StringBuilder();
|
||||||
@@ -207,6 +231,11 @@ public final class DocToDocx {
|
|||||||
this.parts = parts;
|
this.parts = parts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Targets внешних гиперссылок body (наполняется во время {@link #build}). */
|
||||||
|
List<String> hyperlinks() {
|
||||||
|
return hyperlinks;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Текст CP 0..ccpText → XML-тело {@code <w:body>}: абзацы + межсекционные
|
* Текст CP 0..ccpText → XML-тело {@code <w:body>}: абзацы + межсекционные
|
||||||
* {@code w:sectPr} в pPr абзаца с разрывом 0x0C + body-level sectPr
|
* {@code w:sectPr} в pPr абзаца с разрывом 0x0C + body-level sectPr
|
||||||
@@ -258,6 +287,12 @@ public final class DocToDocx {
|
|||||||
this.sectByEndCp = sectByEndCp;
|
this.sectByEndCp = sectByEndCp;
|
||||||
this.pendingSectPr = null;
|
this.pendingSectPr = null;
|
||||||
fieldStack.clear();
|
fieldStack.clear();
|
||||||
|
linkStack.clear();
|
||||||
|
openLinkIds.clear();
|
||||||
|
linksOpenInPara = 0;
|
||||||
|
if (!fieldsAsSimple) {
|
||||||
|
hyperlinks.clear();
|
||||||
|
}
|
||||||
instr.setLength(0);
|
instr.setLength(0);
|
||||||
capturing = false;
|
capturing = false;
|
||||||
fldSimpleOpen = 0;
|
fldSimpleOpen = 0;
|
||||||
@@ -273,6 +308,14 @@ public final class DocToDocx {
|
|||||||
int istd = istdOf(direct, papx.istdFor(paraFc));
|
int istd = istdOf(direct, papx.istdFor(paraFc));
|
||||||
byte[] styleChpx = styles.chpxChain(istd);
|
byte[] styleChpx = styles.chpxChain(istd);
|
||||||
StringBuilder runs = new StringBuilder();
|
StringBuilder runs = new StringBuilder();
|
||||||
|
// поле-ссылка может покрывать границу абзаца: теги обязаны
|
||||||
|
// балансировать в каждом w:p — переоткрываем активные ссылки
|
||||||
|
// старого→нового (поле остаётся открытым до своего FIELD_END)
|
||||||
|
Iterator<String> reopen = openLinkIds.descendingIterator();
|
||||||
|
while (reopen.hasNext()) {
|
||||||
|
runs.append("<w:hyperlink r:id=\"").append(reopen.next()).append("\">");
|
||||||
|
}
|
||||||
|
linksOpenInPara = openLinkIds.size();
|
||||||
char termMark = 0;
|
char termMark = 0;
|
||||||
while (cp < to) {
|
while (cp < to) {
|
||||||
char ch = pieces.charAt(cp);
|
char ch = pieces.charAt(cp);
|
||||||
@@ -296,6 +339,10 @@ public final class DocToDocx {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (int i = linksOpenInPara; i > 0; i--) {
|
||||||
|
runs.append("</w:hyperlink>");
|
||||||
|
}
|
||||||
|
linksOpenInPara = 0;
|
||||||
String sect = pendingSectPr;
|
String sect = pendingSectPr;
|
||||||
pendingSectPr = null;
|
pendingSectPr = null;
|
||||||
if (sect != null && inTable(direct)) {
|
if (sect != null && inTable(direct)) {
|
||||||
@@ -546,13 +593,16 @@ public final class DocToDocx {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case FIELD_BEGIN:
|
case FIELD_BEGIN:
|
||||||
// fldSimple — sibling w:r, ран закрывается на границе поля
|
// fldSimple/hyperlink — sibling w:r, ран закрывается
|
||||||
|
// на границе поля
|
||||||
closeRun(runs, rPr, content, text);
|
closeRun(runs, rPr, content, text);
|
||||||
if (fieldsAsSimple) {
|
// инструкцию читаем и в теле — URL гиперссылки берётся
|
||||||
instr.setLength(0);
|
// из неё; вывод не меняется: пока поле открыто,
|
||||||
capturing = true;
|
// visible()==false и захваченный текст невидим
|
||||||
}
|
instr.setLength(0);
|
||||||
|
capturing = true;
|
||||||
fieldStack.push(Boolean.FALSE);
|
fieldStack.push(Boolean.FALSE);
|
||||||
|
linkStack.push(Boolean.FALSE);
|
||||||
break;
|
break;
|
||||||
case FIELD_SEPARATOR:
|
case FIELD_SEPARATOR:
|
||||||
closeRun(runs, rPr, content, text);
|
closeRun(runs, rPr, content, text);
|
||||||
@@ -567,13 +617,34 @@ public final class DocToDocx {
|
|||||||
.append("\">");
|
.append("\">");
|
||||||
fldSimpleOpen++;
|
fldSimpleOpen++;
|
||||||
}
|
}
|
||||||
|
// без открытого поля (битый поток) ссылку не открываем —
|
||||||
|
// тег остался бы незакрытым до конца документа
|
||||||
|
String url = fieldsAsSimple || linkStack.isEmpty()
|
||||||
|
? null : hyperlinkUrl(instr);
|
||||||
|
if (url != null) {
|
||||||
|
String linkId = "hl" + hyperlinks.size();
|
||||||
|
hyperlinks.add(url);
|
||||||
|
runs.append("<w:hyperlink r:id=\"").append(linkId).append("\">");
|
||||||
|
linkStack.pop();
|
||||||
|
linkStack.push(Boolean.TRUE);
|
||||||
|
openLinkIds.push(linkId);
|
||||||
|
linksOpenInPara++;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case FIELD_END:
|
case FIELD_END:
|
||||||
closeRun(runs, rPr, content, text);
|
closeRun(runs, rPr, content, text);
|
||||||
|
// поле без разделителя (инструкция есть, результата нет)
|
||||||
|
// — иначе захват инструкции «залип» бы до конца потока
|
||||||
|
capturing = false;
|
||||||
if (fldSimpleOpen > 0) {
|
if (fldSimpleOpen > 0) {
|
||||||
runs.append("</w:fldSimple>");
|
runs.append("</w:fldSimple>");
|
||||||
fldSimpleOpen--;
|
fldSimpleOpen--;
|
||||||
}
|
}
|
||||||
|
if (!linkStack.isEmpty() && linkStack.pop()) {
|
||||||
|
runs.append("</w:hyperlink>");
|
||||||
|
openLinkIds.pop();
|
||||||
|
linksOpenInPara--;
|
||||||
|
}
|
||||||
if (!fieldStack.isEmpty()) {
|
if (!fieldStack.isEmpty()) {
|
||||||
fieldStack.pop();
|
fieldStack.pop();
|
||||||
}
|
}
|
||||||
@@ -693,6 +764,70 @@ public final class DocToDocx {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL из инструкции поля HYPERLINK ([MS-DOC] §2.4.4: токен, затем
|
||||||
|
* {@code "url"} или url без кавычек, затем switch'и). Схема обязательна
|
||||||
|
* (RFC 3986 §3.1) — {@code readme.txt}/{@code #bookmark} ссылкой не
|
||||||
|
* считаются. Якорный переключатель {@code \l} — {@code null}: закладки
|
||||||
|
* (w:bookmarkStart) мост не переносит, ссылаться некуда. Деградация
|
||||||
|
* (не гиперссылка/битая инструкция) — {@code null}, результат поля
|
||||||
|
* остаётся плоским текстом.
|
||||||
|
*/
|
||||||
|
static String hyperlinkUrl(CharSequence instruction) {
|
||||||
|
String s = instruction.toString().trim();
|
||||||
|
int end = 0;
|
||||||
|
while (end < s.length() && !Character.isWhitespace(s.charAt(end))) {
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
if (!"HYPERLINK".equalsIgnoreCase(s.substring(0, end))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int p = end;
|
||||||
|
while (p < s.length() && Character.isWhitespace(s.charAt(p))) {
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
if (p == s.length()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String url;
|
||||||
|
String tail;
|
||||||
|
if (s.charAt(p) == QUOTE) {
|
||||||
|
int close = s.indexOf(QUOTE, p + 1);
|
||||||
|
if (close < 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
url = s.substring(p + 1, close);
|
||||||
|
tail = s.substring(close + 1);
|
||||||
|
} else {
|
||||||
|
int sp = p;
|
||||||
|
while (sp < s.length() && !Character.isWhitespace(s.charAt(sp))) {
|
||||||
|
sp++;
|
||||||
|
}
|
||||||
|
url = s.substring(p, sp);
|
||||||
|
tail = s.substring(sp);
|
||||||
|
}
|
||||||
|
for (String tok : tail.trim().split("\\s+")) {
|
||||||
|
if (ANCHOR_SWITCH.equalsIgnoreCase(tok)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (url.isEmpty() || hasControlChar(url)
|
||||||
|
|| !URL_SCHEME.matcher(url).lookingAt()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasControlChar(String url) {
|
||||||
|
for (int i = 0; i < url.length(); i++) {
|
||||||
|
char c = url.charAt(i);
|
||||||
|
if (c < CONTROL_LIMIT || c == DEL) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private boolean visible() {
|
private boolean visible() {
|
||||||
return fieldStack.isEmpty() || fieldStack.peek();
|
return fieldStack.isEmpty() || fieldStack.peek();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,10 +17,11 @@ import java.util.zip.ZipOutputStream;
|
|||||||
* word/document.xml + переданные {@link Part}. Ссылки частей получают
|
* word/document.xml + переданные {@link Part}. Ссылки частей получают
|
||||||
* {@code rId1…} в порядке списка (officeDocument — только в _rels/.rels,
|
* {@code rId1…} в порядке списка (officeDocument — только в _rels/.rels,
|
||||||
* self-ссылка в rels документа недопустима); вызывающий обязан
|
* self-ссылка в rels документа недопустима); вызывающий обязан
|
||||||
* использовать те же id в {@code w:headerReference}/{@code w:pic}. XML-части
|
* использовать те же id в {@code w:headerReference}/{@code w:pic}.
|
||||||
* идут в [Content_Types].xml как Override, медиа — как Default по расширению
|
* Внешние гиперссылки получают {@code hl0…} с {@code TargetMode="External"}.
|
||||||
* (дедупликация по расширению). Байты уходят в штатный пайплайн docx4j
|
* XML-части идут в [Content_Types].xml как Override, медиа — как Default по
|
||||||
* (шаги 1–7 {@code WordPdfConverter}).</p>
|
* расширению (дедупликация по расширению). Байты уходят в штатный пайплайн
|
||||||
|
* docx4j (шаги 1–7 {@code WordPdfConverter}).</p>
|
||||||
*/
|
*/
|
||||||
final class DocxWriter {
|
final class DocxWriter {
|
||||||
|
|
||||||
@@ -37,6 +38,10 @@ final class DocxWriter {
|
|||||||
|
|
||||||
private static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
|
private static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
|
||||||
|
|
||||||
|
/** Тип связи внешней гиперссылки (ECMA-376 Part 2). */
|
||||||
|
private static final String HYPERLINK_REL_TYPE =
|
||||||
|
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
|
||||||
|
|
||||||
private static final String ROOT_RELS = XML_DECL
|
private static final String ROOT_RELS = XML_DECL
|
||||||
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
||||||
+ "<Relationship Id=\"rId1\" "
|
+ "<Relationship Id=\"rId1\" "
|
||||||
@@ -47,17 +52,21 @@ final class DocxWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Пакет из готового XML-тела {@code <w:body>} (без самого элемента)
|
* Пакет из готового XML-тела {@code <w:body>} (без самого элемента),
|
||||||
* и дополнительных частей (их id — {@code rId2…} по порядку списка).
|
* дополнительных частей (их id — {@code rId1…} по порядку списка) и
|
||||||
|
* targets внешних гиперссылок (id — {@code hl0…}, {@code
|
||||||
|
* TargetMode="External"}; id номеронезависимы — media-части доезжают
|
||||||
|
* уже во время сборки тела, смещение {@code rIdN+1…} было бы
|
||||||
|
* нестабильным).
|
||||||
*/
|
*/
|
||||||
static byte[] write(String bodyXml, List<Part> parts) {
|
static byte[] write(String bodyXml, List<Part> parts, List<String> hyperlinkTargets) {
|
||||||
String document = XML_DECL + "<w:document " + NAMESPACES + "><w:body>"
|
String document = XML_DECL + "<w:document " + NAMESPACES + "><w:body>"
|
||||||
+ bodyXml + "</w:body></w:document>";
|
+ bodyXml + "</w:body></w:document>";
|
||||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(1 << 14);
|
ByteArrayOutputStream bos = new ByteArrayOutputStream(1 << 14);
|
||||||
try (ZipOutputStream zip = new ZipOutputStream(bos, StandardCharsets.UTF_8)) {
|
try (ZipOutputStream zip = new ZipOutputStream(bos, StandardCharsets.UTF_8)) {
|
||||||
put(zip, "[Content_Types].xml", contentTypes(parts));
|
put(zip, "[Content_Types].xml", contentTypes(parts));
|
||||||
put(zip, "_rels/.rels", ROOT_RELS);
|
put(zip, "_rels/.rels", ROOT_RELS);
|
||||||
put(zip, "word/_rels/document.xml.rels", documentRels(parts));
|
put(zip, "word/_rels/document.xml.rels", documentRels(parts, hyperlinkTargets));
|
||||||
put(zip, "word/document.xml", document);
|
put(zip, "word/document.xml", document);
|
||||||
for (Part part : parts) {
|
for (Part part : parts) {
|
||||||
zip.putNextEntry(new ZipEntry(part.entry()));
|
zip.putNextEntry(new ZipEntry(part.entry()));
|
||||||
@@ -103,11 +112,12 @@ final class DocxWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Связи document.xml: части в порядке списка (rId1…). officeDocument
|
* Связи document.xml: части в порядке списка (rId1…), затем внешние
|
||||||
|
* гиперссылки (hl0…, TargetMode="External"). officeDocument
|
||||||
* здесь нет — он только в _rels/.rels; self-ссылка зациклила бы
|
* здесь нет — он только в _rels/.rels; self-ссылка зациклила бы
|
||||||
* docx4j {@code PartialDeepCopy.deepCopyRelationships}.
|
* docx4j {@code PartialDeepCopy.deepCopyRelationships}.
|
||||||
*/
|
*/
|
||||||
private static String documentRels(List<Part> parts) {
|
private static String documentRels(List<Part> parts, List<String> hyperlinkTargets) {
|
||||||
StringBuilder xml = new StringBuilder(XML_DECL)
|
StringBuilder xml = new StringBuilder(XML_DECL)
|
||||||
.append("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
|
.append("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
|
||||||
for (int i = 0; i < parts.size(); i++) {
|
for (int i = 0; i < parts.size(); i++) {
|
||||||
@@ -117,9 +127,20 @@ final class DocxWriter {
|
|||||||
xml.append("<Relationship Id=\"rId").append(1 + i).append("\" Type=\"")
|
xml.append("<Relationship Id=\"rId").append(1 + i).append("\" Type=\"")
|
||||||
.append(part.relType()).append("\" Target=\"").append(target).append("\"/>");
|
.append(part.relType()).append("\" Target=\"").append(target).append("\"/>");
|
||||||
}
|
}
|
||||||
|
for (int i = 0; i < hyperlinkTargets.size(); i++) {
|
||||||
|
xml.append("<Relationship Id=\"hl").append(i).append("\" Type=\"")
|
||||||
|
.append(HYPERLINK_REL_TYPE).append("\" Target=\"")
|
||||||
|
.append(escapeAttr(hyperlinkTargets.get(i)))
|
||||||
|
.append("\" TargetMode=\"External\"/>");
|
||||||
|
}
|
||||||
return xml.append("</Relationships>").toString();
|
return xml.append("</Relationships>").toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Атрибутный экранировщик Target (дубликат образец {@code Lists.escapeAttr}). */
|
||||||
|
private static String escapeAttr(String s) {
|
||||||
|
return s.replace("&", "&").replace("<", "<").replace("\"", """);
|
||||||
|
}
|
||||||
|
|
||||||
private static void put(ZipOutputStream zip, String name, String content) throws IOException {
|
private static void put(ZipOutputStream zip, String name, String content) throws IOException {
|
||||||
zip.putNextEntry(new ZipEntry(name));
|
zip.putNextEntry(new ZipEntry(name));
|
||||||
zip.write(content.getBytes(StandardCharsets.UTF_8));
|
zip.write(content.getBytes(StandardCharsets.UTF_8));
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import org.apache.pdfbox.pdmodel.PDPage;
|
|||||||
import org.apache.pdfbox.pdmodel.PDResources;
|
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.pdmodel.interactive.action.PDActionURI;
|
||||||
|
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
|
||||||
|
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
|
||||||
import org.apache.pdfbox.text.PDFTextStripper;
|
import org.apache.pdfbox.text.PDFTextStripper;
|
||||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -19,6 +22,7 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@@ -103,6 +107,22 @@ class WordPdfConverterTest {
|
|||||||
return s.replaceAll("\\s+", " ");
|
return s.replaceAll("\\s+", " ");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** /URI всех ссылочных аннотаций PDF'а (все страницы). */
|
||||||
|
private static List<String> linkUris(Path pdf) throws IOException {
|
||||||
|
List<String> uris = new ArrayList<>();
|
||||||
|
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||||
|
for (PDPage page : doc.getPages()) {
|
||||||
|
for (PDAnnotation ann : page.getAnnotations()) {
|
||||||
|
if (ann instanceof PDAnnotationLink link
|
||||||
|
&& link.getAction() instanceof PDActionURI uri) {
|
||||||
|
uris.add(uri.getURI());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return uris;
|
||||||
|
}
|
||||||
|
|
||||||
/** BaseFont-имена вшитых шрифтов PDF (например "EAAAAA+Carlito-Bold"). */
|
/** BaseFont-имена вшитых шрифтов PDF (например "EAAAAA+Carlito-Bold"). */
|
||||||
private static Set<String> embeddedFontNames(Path pdf) throws IOException {
|
private static Set<String> embeddedFontNames(Path pdf) throws IOException {
|
||||||
Set<String> names = new TreeSet<>();
|
Set<String> names = new TreeSet<>();
|
||||||
@@ -1337,6 +1357,23 @@ class WordPdfConverterTest {
|
|||||||
"лимит 1 страница не удержал двухстраничный .doc");
|
"лимит 1 страница не удержал двухстраничный .doc");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Синтетический .doc с полем HYPERLINK (фикстуры заказчика ссылок не
|
||||||
|
* содержат — крафт POIFS, дубль хелперов DocToDocxFormattingTest):
|
||||||
|
* инструкция → внешняя rels-связь документа, результат → содержимое
|
||||||
|
* w:hyperlink, FOP кладёт поверх кликабельную аннотацию с /URI.
|
||||||
|
* Регрессия — internal.doc.DocxBody#hyperlinkUrl + DocxWriter#write.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void docHyperlink_linkAnnotationClickable() throws Exception {
|
||||||
|
Path pdf = convertPdf(hyperlinkDoc(), "doc-hyperlink");
|
||||||
|
String text = norm(pdfText(pdf));
|
||||||
|
assertTrue(text.contains("before сайт after"), "текст ссылки: " + text);
|
||||||
|
assertEquals(List.of("https://pjandro.ru/docs?q=1&z=2"), linkUris(pdf),
|
||||||
|
"аннотация-ссылка не найдена");
|
||||||
|
assertFalse(text.contains("#"), ".notdef-боксы в тексте");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Синтетический .doc со списками (ни одна фикстура заказчика списков не
|
* Синтетический .doc со списками (ни одна фикстура заказчика списков не
|
||||||
* содержит — крафт POIFS, дубль хелперов DocToDocxFormattingTest):
|
* содержит — крафт POIFS, дубль хелперов DocToDocxFormattingTest):
|
||||||
@@ -1698,6 +1735,56 @@ class WordPdfConverterTest {
|
|||||||
"объединённая ячейка шире половины полосы, right=" + rightEdge[0]);
|
"объединённая ячейка шире половины полосы, right=" + rightEdge[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- крафт .doc с гиперссылкой (дубль DocToDocxFormattingTest) ------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Абзац «before [поле HYPERLINK → сайт] after». PAPX — прямой jc=left:
|
||||||
|
* форма GrpPrlAndIstd в этом дубле требует нечётный grpprl.
|
||||||
|
*/
|
||||||
|
private static byte[] hyperlinkDoc() throws IOException {
|
||||||
|
String text = "before " + (char) 0x13
|
||||||
|
+ " HYPERLINK \"https://pjandro.ru/docs?q=1&z=2\" " + (char) 0x14
|
||||||
|
+ "сайт" + (char) 0x15 + " after\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;
|
||||||
|
put32(wd, page, LISTS_TEXT_FC); // rgfc: один абзац
|
||||||
|
put32(wd, page + 4, LISTS_TEXT_FC + 2 * text.length());
|
||||||
|
wd[page + 8] = 87; // rgbx[0] → bx
|
||||||
|
wd[page + 511] = 1; // cpara
|
||||||
|
papxEntry(wd, page, 87, prl(0x2461, 0));
|
||||||
|
byte[] tab = new byte[53];
|
||||||
|
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);
|
||||||
|
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 со списками (дубль DocToDocxFormattingTest) ----------
|
// --- крафт .doc со списками (дубль DocToDocxFormattingTest) ----------
|
||||||
|
|
||||||
private static final int LISTS_TEXT_FC = 2048;
|
private static final int LISTS_TEXT_FC = 2048;
|
||||||
|
|||||||
+187
-1
@@ -2,6 +2,7 @@ package ru.pjandro.wordpdf.internal.doc;
|
|||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
@@ -25,7 +26,9 @@ import ru.pjandro.wordpdf.ValidationException;
|
|||||||
* со стилевым jc, деградация строк без корректного TDefTable, таблица в
|
* со стилевым jc, деградация строк без корректного TDefTable, таблица в
|
||||||
* колонтитуке с выравниванием sprmTJc (→ w:jc в tblPr) и списки
|
* колонтитуке с выравниванием sprmTJc (→ w:jc в tblPr) и списки
|
||||||
* (PlfLst/PlfLfo → w:numPr + numbering.xml, снятие прямым ilfo=0,
|
* (PlfLst/PlfLfo → w:numPr + numbering.xml, снятие прямым ilfo=0,
|
||||||
* ilvl=0x0C, деградация без списочных таблиц).
|
* ilvl=0x0C, деградация без списочных таблиц) и гиперссылки (поле HYPERLINK
|
||||||
|
* → w:hyperlink + внешняя rels-связь, деградации якоря \l и URL без схемы,
|
||||||
|
* баланс тегов при поле через границу абзацев).
|
||||||
*/
|
*/
|
||||||
class DocToDocxFormattingTest {
|
class DocToDocxFormattingTest {
|
||||||
|
|
||||||
@@ -1461,6 +1464,189 @@ class DocToDocxFormattingTest {
|
|||||||
"w:jc должен идти после tblW и до tblGrid (CT_TblPrBase): " + footer);
|
"w:jc должен идти после tblW и до tblGrid (CT_TblPrBase): " + footer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- гиперссылки (поле HYPERLINK в основном тексте) -----------------
|
||||||
|
|
||||||
|
/** URL для крафта поля HYPERLINK. */
|
||||||
|
private static final String LINK_URL = "https://example.com/x?a=1&b=2";
|
||||||
|
|
||||||
|
/** ¶-маркер абзаца (.doc). */
|
||||||
|
private static final char PARA = '\r';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Синтетический .doc с произвольным основным текстом: по PAPX-записи на
|
||||||
|
* абзац (пустой grpprl — плоские свойства), CHPX/STSH нет (дефолты);
|
||||||
|
* раскладка потоков — как {@link #listDoc}.
|
||||||
|
*/
|
||||||
|
private static byte[] hyperlinkDoc(String text) throws IOException {
|
||||||
|
byte[] wd = new byte[TEXT_FC + text.length() * 2];
|
||||||
|
put16(wd, 0, 0xA5EC);
|
||||||
|
put16(wd, 2, 0x00C1);
|
||||||
|
put16(wd, 10, 1 << 9); // fWhichTblStm → 1Table
|
||||||
|
put16(wd, 62, 4); // cslw
|
||||||
|
put32(wd, 64, wd.length); // cbMac
|
||||||
|
put32(wd, 76, text.length()); // ccpText
|
||||||
|
put16(wd, 152, 98); // cbRgFcLcb
|
||||||
|
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, TEXT_FC, t.length);
|
||||||
|
// PapxFkp pn=3: границы абзацев по ¶-маркерам, пустые GrpPrlAndIstd
|
||||||
|
int paras = 0;
|
||||||
|
for (int i = 0; i < text.length(); i++) {
|
||||||
|
if (text.charAt(i) == PARA) {
|
||||||
|
paras++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!text.endsWith("\r")) {
|
||||||
|
paras++;
|
||||||
|
}
|
||||||
|
int[] starts = new int[paras + 1];
|
||||||
|
int k = 1;
|
||||||
|
for (int i = 0; i < text.length() && k < paras; i++) {
|
||||||
|
if (text.charAt(i) == PARA) {
|
||||||
|
starts[k++] = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
starts[paras] = text.length();
|
||||||
|
int page = 3 * 512;
|
||||||
|
for (int i = 0; i <= paras; i++) {
|
||||||
|
put32(wd, page + i * 4, TEXT_FC + 2 * starts[i]);
|
||||||
|
}
|
||||||
|
int rgbx = page + (paras + 1) * 4;
|
||||||
|
for (int i = 0; i < paras; i++) {
|
||||||
|
wd[rgbx + i * 13] = (byte) (87 + 8 * i);
|
||||||
|
papxEntry(wd, page, 87 + 8 * i, 0, new byte[0]);
|
||||||
|
}
|
||||||
|
wd[page + 511] = (byte) paras;
|
||||||
|
byte[] tab = new byte[53];
|
||||||
|
put32(tab, 0, 0); // PlcfSed aCP[0]
|
||||||
|
put32(tab, 4, text.length()); // aCP[1]
|
||||||
|
put32(tab, 20, TEXT_FC); // PlcfBtePapx aFc
|
||||||
|
put32(tab, 24, TEXT_FC + 2 * text.length());
|
||||||
|
put32(tab, 28, 3); // pn=3
|
||||||
|
tab[32] = 0x02; // Clx Pcdt, один несжатый кусок
|
||||||
|
put32(tab, 33, 16);
|
||||||
|
put32(tab, 37, 0);
|
||||||
|
put32(tab, 41, text.length());
|
||||||
|
put32(tab, 47, 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countOccurrences(String s, String sub) {
|
||||||
|
int n = 0;
|
||||||
|
for (int i = s.indexOf(sub); i >= 0; i = s.indexOf(sub, i + 1)) {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Деградация: результат плоским текстом, ни тега, ни rels-записи. */
|
||||||
|
private static void assertNoHyperlink(byte[] doc) throws IOException {
|
||||||
|
String xml = documentXml(doc);
|
||||||
|
assertFalse(xml.contains("<w:hyperlink"), "ссылка не должна открыться: " + xml);
|
||||||
|
assertTrue(xml.contains("Сайт"), "результат поля потерян: " + xml);
|
||||||
|
assertFalse(partXml(doc, "word/_rels/document.xml.rels").contains("hl0"),
|
||||||
|
"rels-запись не должна появиться");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Поле HYPERLINK: инструкция → w:hyperlink r:id="hl0" + внешняя связь
|
||||||
|
* TargetMode="External" (экранирование & в Target), результат поля —
|
||||||
|
* содержимое ссылки; текст инструкции и URL в вывод не попадают.
|
||||||
|
* Регрессия — DocxBody#hyperlinkUrl + DocxWriter#documentRels.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void hyperlink_quotedUrl_becomesExternalLink() throws IOException {
|
||||||
|
byte[] doc = hyperlinkDoc("before " + (char) 0x13
|
||||||
|
+ " HYPERLINK \"" + LINK_URL + "\" \\o \"Подсказка\" " + (char) 0x14
|
||||||
|
+ "Сайт" + (char) 0x15 + " after\r");
|
||||||
|
String xml = documentXml(doc);
|
||||||
|
assertTrue(xml.contains("<w:hyperlink r:id=\"hl0\">"), xml);
|
||||||
|
assertTrue(xml.contains(">Сайт<"), "результат поля потерян: " + xml);
|
||||||
|
assertFalse(xml.contains("HYPERLINK"), "инструкция утёк в вывод: " + xml);
|
||||||
|
assertFalse(xml.contains("example.com"), "URL утёк в текст: " + xml);
|
||||||
|
assertFalse(xml.contains("Подсказка"), "switch утёк в вывод: " + xml);
|
||||||
|
String rels = partXml(doc, "word/_rels/document.xml.rels");
|
||||||
|
assertTrue(rels.contains("Id=\"hl0\""), rels);
|
||||||
|
assertTrue(rels.contains("Type=\"http://schemas.openxmlformats.org/officeDocument"
|
||||||
|
+ "/2006/relationships/hyperlink\""), rels);
|
||||||
|
assertTrue(rels.contains("Target=\"https://example.com/x?a=1&b=2\""), rels);
|
||||||
|
assertTrue(rels.contains("TargetMode=\"External\""), rels);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** URL без кавычек — валидная форма инструкции Word. */
|
||||||
|
@Test
|
||||||
|
void hyperlink_unquotedUrl_accepted() throws IOException {
|
||||||
|
byte[] doc = hyperlinkDoc("x" + (char) 0x13 + "HYPERLINK https://example.com"
|
||||||
|
+ (char) 0x14 + "Сайт" + (char) 0x15 + "\r");
|
||||||
|
assertTrue(documentXml(doc).contains("<w:hyperlink r:id=\"hl0\">"));
|
||||||
|
assertTrue(partXml(doc, "word/_rels/document.xml.rels")
|
||||||
|
.contains("Target=\"https://example.com\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Якорный переключатель \l: закладок мост не переносит — плоский текст. */
|
||||||
|
@Test
|
||||||
|
void hyperlink_anchorSwitch_degradesToPlain() throws IOException {
|
||||||
|
assertNoHyperlink(hyperlinkDoc((char) 0x13 + " HYPERLINK \"https://example.com\""
|
||||||
|
+ " \\l \"закладка\" " + (char) 0x14 + "Сайт" + (char) 0x15 + "\r"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** URL без схемы RFC 3986 (относительный путь) — плоский текст. */
|
||||||
|
@Test
|
||||||
|
void hyperlink_noScheme_degradesToPlain() throws IOException {
|
||||||
|
assertNoHyperlink(hyperlinkDoc((char) 0x13 + "HYPERLINK readme.txt"
|
||||||
|
+ (char) 0x14 + "Сайт" + (char) 0x15 + "\r"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Поле покрывает границу абзацев: тег переоткрывается/закрывается в
|
||||||
|
* каждом w:p (баланс по абзацам), rels-запись одна.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void hyperlink_spansParagraphs_tagsBalancePerParagraph() throws IOException {
|
||||||
|
byte[] doc = hyperlinkDoc("pre " + (char) 0x13 + " HYPERLINK \"https://ex.com\" "
|
||||||
|
+ (char) 0x14 + "one\r" + "two" + (char) 0x15 + " post\r");
|
||||||
|
String xml = documentXml(doc);
|
||||||
|
assertEquals(2, countOccurrences(xml, "<w:hyperlink "), xml);
|
||||||
|
assertEquals(2, countOccurrences(xml, "</w:hyperlink>"), xml);
|
||||||
|
for (String para : xml.split("</w:p>")) {
|
||||||
|
assertEquals(countOccurrences(para, "<w:hyperlink "),
|
||||||
|
countOccurrences(para, "</w:hyperlink>"),
|
||||||
|
"незакрытый тег ссылки в абзаце: " + para);
|
||||||
|
}
|
||||||
|
String rels = partXml(doc, "word/_rels/document.xml.rels");
|
||||||
|
assertTrue(rels.contains("Id=\"hl0\""), rels);
|
||||||
|
assertEquals(1, countOccurrences(rels, "Id=\"hl0\""), "rels-запись должна быть одна");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Грамматика инструкции HYPERLINK (все ветви {@link DocToDocx.DocxBody#hyperlinkUrl}). */
|
||||||
|
@Test
|
||||||
|
void hyperlinkUrl_wordFieldGrammar() {
|
||||||
|
assertEquals("https://example.com/x?a=1",
|
||||||
|
DocToDocx.DocxBody.hyperlinkUrl(" HYPERLINK \"https://example.com/x?a=1\" "));
|
||||||
|
assertEquals("https://example.com",
|
||||||
|
DocToDocx.DocxBody.hyperlinkUrl("HYPERLINK https://example.com"));
|
||||||
|
assertEquals("http://a.b", DocToDocx.DocxBody.hyperlinkUrl("hyperlink \"http://a.b\""));
|
||||||
|
assertEquals("mailto:a@b.c",
|
||||||
|
DocToDocx.DocxBody.hyperlinkUrl(" HYPERLINK \"mailto:a@b.c\" \\h"));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl(" HYPERLINK \"http://a\" \\l \"bk\" "));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl(" HYPERLINK readme.txt"));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl(" HYPERLINK \"http://a"));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl(" HYPERLINK \"http://a" + (char) 7 + "\""));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl("HYPERLINK \"\""));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl("HYPERLINK"));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl(""));
|
||||||
|
assertNull(DocToDocx.DocxBody.hyperlinkUrl(" PAGE "));
|
||||||
|
}
|
||||||
|
|
||||||
// --- мелочь ----------------------------------------------------------
|
// --- мелочь ----------------------------------------------------------
|
||||||
|
|
||||||
private static byte[] prl(int sprm, int toggle) {
|
private static byte[] prl(int sprm, int toggle) {
|
||||||
|
|||||||
Reference in New Issue
Block a user