Мост .xlsx → PDF: SpreadsheetML-конвейер без LibreOffice/POI #91
Binary file not shown.
+18
-11
@@ -1,4 +1,4 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
@@ -22,19 +22,26 @@ import java.util.zip.ZipOutputStream;
|
||||
* XML-части идут в [Content_Types].xml как Override, медиа — как Default по
|
||||
* расширению (дедупликация по расширению). Байты уходят в штатный пайплайн
|
||||
* docx4j (шаги 1–7 {@code WordPdfConverter}).</p>
|
||||
*
|
||||
* <p>Общий сборщик мостов: {@code internal.doc} (бинарный .doc) и
|
||||
* {@code internal.xlsx} (SpreadsheetML) — отсюда public вне пакета.</p>
|
||||
*/
|
||||
final class DocxWriter {
|
||||
public final class DocxPackageWriter {
|
||||
|
||||
/** Часть пакета кроме document.xml: zip-запись, content-type, тип связи, байты. */
|
||||
record Part(String entry, String contentType, String relType, byte[] content) {
|
||||
public 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\""
|
||||
/**
|
||||
* Пространства имён корня document.xml/hdr/ftr: w + r (rels) + DrawingML
|
||||
* + c (chart — нужно мосту .xlsx для {@code a:graphicData}/{@code c:chart}).
|
||||
*/
|
||||
public 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\"";
|
||||
+ " xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\""
|
||||
+ " xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"";
|
||||
|
||||
private static final String XML_DECL = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
|
||||
|
||||
@@ -48,7 +55,7 @@ final class DocxWriter {
|
||||
+ "Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" "
|
||||
+ "Target=\"word/document.xml\"/></Relationships>";
|
||||
|
||||
private DocxWriter() {
|
||||
private DocxPackageWriter() {
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,7 +66,7 @@ final class DocxWriter {
|
||||
* уже во время сборки тела, смещение {@code rIdN+1…} было бы
|
||||
* нестабильным).
|
||||
*/
|
||||
static byte[] write(String bodyXml, List<Part> parts, List<String> hyperlinkTargets) {
|
||||
public static byte[] write(String bodyXml, List<Part> parts, List<String> hyperlinkTargets) {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(1 << 14);
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bos, StandardCharsets.UTF_8)) {
|
||||
put(zip, "[Content_Types].xml", contentTypes(parts));
|
||||
@@ -76,7 +83,7 @@ final class DocxWriter {
|
||||
zip.closeEntry();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Не удалось собрать .docx из .doc", e);
|
||||
throw new IllegalStateException("Не удалось собрать .docx", e);
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
@@ -92,7 +99,7 @@ final class DocxWriter {
|
||||
}
|
||||
|
||||
/** XML-часть колонтитука: {@code <w:hdr>}/{@code <w:ftr>} с полным набором имён. */
|
||||
static byte[] storyPart(String rootElement, String paragraphsXml) {
|
||||
public static byte[] storyPart(String rootElement, String paragraphsXml) {
|
||||
return (XML_DECL + "<" + rootElement + " " + NAMESPACES + ">"
|
||||
+ paragraphsXml + "</" + rootElement + ">").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
@@ -148,7 +155,7 @@ final class DocxWriter {
|
||||
return xml.append("</Relationships>").toString();
|
||||
}
|
||||
|
||||
/** Атрибутный экранировщик Target (дубликат образец {@code Lists.escapeAttr}). */
|
||||
/** Атрибутный экранировщик Target (дубликат образец {@code internal.doc.Lists.escapeAttr}). */
|
||||
private static String escapeAttr(String s) {
|
||||
return s.replace("&", "&").replace("<", "<").replace("\"", """);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
import ru.pjandro.wordpdf.internal.DocxPackageWriter;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
@@ -132,11 +133,11 @@ public final class DocToDocx {
|
||||
file.wordDocument());
|
||||
Headers headers = Headers.read(file.table(), fib.fcPlcfHdd(), fib.lcbPlcfHdd(),
|
||||
fib.ccpText() + fib.ccpFtn());
|
||||
List<DocxWriter.Part> parts = new ArrayList<>();
|
||||
List<DocxPackageWriter.Part> parts = new ArrayList<>();
|
||||
if (lists.hasNumbering()) {
|
||||
// relId этой части из XML не нужен — docx4j находит numbering по типу
|
||||
// связи; id колонтитулов считаются после своего add, не сдвигаются
|
||||
parts.add(new DocxWriter.Part("word/numbering.xml", NUMBERING_CONTENT_TYPE,
|
||||
parts.add(new DocxPackageWriter.Part("word/numbering.xml", NUMBERING_CONTENT_TYPE,
|
||||
NUMBERING_REL_TYPE,
|
||||
lists.numberingXml().getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
@@ -167,9 +168,9 @@ public final class DocToDocx {
|
||||
Headers.Story hdr = headers.oddHeader(i);
|
||||
if (!hdr.empty()) {
|
||||
hdrNo++;
|
||||
parts.add(new DocxWriter.Part("word/header" + hdrNo + ".xml",
|
||||
parts.add(new DocxPackageWriter.Part("word/header" + hdrNo + ".xml",
|
||||
HEADER_CONTENT_TYPE, HEADER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:hdr", hdr.hasContent()
|
||||
DocxPackageWriter.storyPart("w:hdr", hdr.hasContent()
|
||||
? body.buildRange(hdr.cpStart(), hdr.contentEnd(), true)
|
||||
: "<w:p/>")));
|
||||
hdrRel[i] = "rId" + parts.size();
|
||||
@@ -177,9 +178,9 @@ public final class DocToDocx {
|
||||
Headers.Story ftr = headers.oddFooter(i);
|
||||
if (!ftr.empty()) {
|
||||
ftrNo++;
|
||||
parts.add(new DocxWriter.Part("word/footer" + ftrNo + ".xml",
|
||||
parts.add(new DocxPackageWriter.Part("word/footer" + ftrNo + ".xml",
|
||||
FOOTER_CONTENT_TYPE, FOOTER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:ftr", ftr.hasContent()
|
||||
DocxPackageWriter.storyPart("w:ftr", ftr.hasContent()
|
||||
? body.buildRange(ftr.cpStart(), ftr.contentEnd(), true)
|
||||
: "<w:p/>")));
|
||||
ftrRel[i] = "rId" + parts.size();
|
||||
@@ -188,9 +189,9 @@ public final class DocToDocx {
|
||||
Headers.Story firstHdr = headers.firstHeader(i);
|
||||
if (!firstHdr.empty()) {
|
||||
hdrNo++;
|
||||
parts.add(new DocxWriter.Part("word/header" + hdrNo + ".xml",
|
||||
parts.add(new DocxPackageWriter.Part("word/header" + hdrNo + ".xml",
|
||||
HEADER_CONTENT_TYPE, HEADER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:hdr", firstHdr.hasContent()
|
||||
DocxPackageWriter.storyPart("w:hdr", firstHdr.hasContent()
|
||||
? body.buildRange(firstHdr.cpStart(), firstHdr.contentEnd(),
|
||||
true)
|
||||
: "<w:p/>")));
|
||||
@@ -199,9 +200,9 @@ public final class DocToDocx {
|
||||
Headers.Story firstFtr = headers.firstFooter(i);
|
||||
if (!firstFtr.empty()) {
|
||||
ftrNo++;
|
||||
parts.add(new DocxWriter.Part("word/footer" + ftrNo + ".xml",
|
||||
parts.add(new DocxPackageWriter.Part("word/footer" + ftrNo + ".xml",
|
||||
FOOTER_CONTENT_TYPE, FOOTER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:ftr", firstFtr.hasContent()
|
||||
DocxPackageWriter.storyPart("w:ftr", firstFtr.hasContent()
|
||||
? body.buildRange(firstFtr.cpStart(), firstFtr.contentEnd(),
|
||||
true)
|
||||
: "<w:p/>")));
|
||||
@@ -211,7 +212,7 @@ public final class DocToDocx {
|
||||
}
|
||||
// hyperlinks наполняются внутри build (body-pass); rels пишутся после
|
||||
String bodyXml = body.build(secs, hdrRel, ftrRel, firstHdrRel, firstFtrRel);
|
||||
return DocxWriter.write(bodyXml, parts, body.hyperlinks());
|
||||
return DocxPackageWriter.write(bodyXml, parts, body.hyperlinks());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -257,7 +258,7 @@ public final class DocToDocx {
|
||||
/** Data-поток (.doc) для BLIP по sprmCPicLocation. */
|
||||
private final byte[] dataStream;
|
||||
/** Части пакета (колонтитуки + media); id связи = rId{позиция+1}. */
|
||||
private final List<DocxWriter.Part> parts;
|
||||
private final List<DocxPackageWriter.Part> parts;
|
||||
private final Deque<Boolean> fieldStack = new ArrayDeque<>();
|
||||
/** Флаг «поле открыло w:hyperlink», параллельно {@link #fieldStack}. */
|
||||
private final Deque<Boolean> linkStack = new ArrayDeque<>();
|
||||
@@ -279,7 +280,7 @@ public final class DocToDocx {
|
||||
|
||||
DocxBody(PieceTable pieces, ChpxIndex chpx, PapxIndex papx, FontTable fonts,
|
||||
Styles styles, Lists lists, int ccpText, byte[] dataStream,
|
||||
List<DocxWriter.Part> parts) {
|
||||
List<DocxPackageWriter.Part> parts) {
|
||||
this.pieces = pieces;
|
||||
this.chpx = chpx;
|
||||
this.papx = papx;
|
||||
@@ -864,13 +865,13 @@ public final class DocToDocx {
|
||||
return;
|
||||
}
|
||||
int imageNo = 1;
|
||||
for (DocxWriter.Part p : parts) {
|
||||
for (DocxPackageWriter.Part p : parts) {
|
||||
if (p.entry().startsWith("word/media/")) {
|
||||
imageNo++;
|
||||
}
|
||||
}
|
||||
String entry = "word/media/image" + imageNo + "." + pic.extension();
|
||||
parts.add(new DocxWriter.Part(entry, pic.contentType(), IMAGE_REL_TYPE, pic.data()));
|
||||
parts.add(new DocxPackageWriter.Part(entry, pic.contentType(), IMAGE_REL_TYPE, pic.data()));
|
||||
String relId = "rId" + parts.size();
|
||||
runs.append(markupOpen()).append("<w:r>").append(rPr).append("<w:drawing>")
|
||||
.append("<wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\">")
|
||||
|
||||
@@ -1411,7 +1411,7 @@ class WordPdfConverterTest {
|
||||
* содержат — крафт POIFS, дубль хелперов DocToDocxFormattingTest):
|
||||
* инструкция → внешняя rels-связь документа, результат → содержимое
|
||||
* w:hyperlink, FOP кладёт поверх кликабельную аннотацию с /URI.
|
||||
* Регрессия — internal.doc.DocxBody#hyperlinkUrl + DocxWriter#write.
|
||||
* Регрессия — internal.doc.DocxBody#hyperlinkUrl + DocxPackageWriter#write.
|
||||
*/
|
||||
@Test
|
||||
void docHyperlink_linkAnnotationClickable() throws Exception {
|
||||
|
||||
+1
-1
@@ -1564,7 +1564,7 @@ class DocToDocxFormattingTest {
|
||||
* Поле HYPERLINK: инструкция → w:hyperlink r:id="hl0" + внешняя связь
|
||||
* TargetMode="External" (экранирование & в Target), результат поля —
|
||||
* содержимое ссылки; текст инструкции и URL в вывод не попадают.
|
||||
* Регрессия — DocxBody#hyperlinkUrl + DocxWriter#documentRels.
|
||||
* Регрессия — DocxBody#hyperlinkUrl + DocxPackageWriter#documentRels.
|
||||
*/
|
||||
@Test
|
||||
void hyperlink_quotedUrl_becomesExternalLink() throws IOException {
|
||||
|
||||
Reference in New Issue
Block a user