Preserve QPowerPoint hidden slides in PPTX

This commit is contained in:
Курнат Андрей
2026-06-01 19:28:38 +03:00
parent f4da4dc283
commit a2de721fc4
6 changed files with 161 additions and 8 deletions
+45
View File
@@ -307,6 +307,47 @@ describe("powerPointOffice helpers", () => {
expect(exportedSlideXml).toContain("FCE4D6");
});
it("импортирует и экспортирует скрытые слайды PPTX через атрибут show", async () => {
const zip = new JSZip();
zip.file(
"ppt/presentation.xml",
`<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst></p:presentation>`
);
zip.file(
"ppt/_rels/presentation.xml.rels",
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/></Relationships>`
);
zip.file("ppt/slides/slide1.xml", slideXmlWithShow("Скрытый слайд", "0"));
const importedBlob = await zip.generateAsync({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
});
const imported = await importPptxFile(new File([importedBlob], "Скрытый.pptx", { type: importedBlob.type }));
expect(imported.slides[0]).toMatchObject({ title: "Скрытый слайд", hidden: true });
const exportedBlob = await exportPptxBlob({
title: "Скрытый.pptx",
slides: [
{
id: "slide-1",
title: "Скрытый слайд",
subtitle: "",
notes: "",
theme: "classic",
hidden: true
}
]
});
const exportedZip = await JSZip.loadAsync(await exportedBlob.arrayBuffer());
const exportedSlideXml = (await exportedZip.file("ppt/slides/slide1.xml")?.async("string")) ?? "";
const reimported = await importPptxFile(new File([exportedBlob], "Скрытый.pptx", { type: exportedBlob.type }));
expect(exportedSlideXml).toContain('show="0"');
expect(reimported.slides[0].hidden).toBe(true);
});
it("импортирует и экспортирует цвет и размер текста слайда", async () => {
const zip = new JSZip();
zip.file(
@@ -380,6 +421,10 @@ function slideXmlWithBackground(title: string, color: string) {
return `<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:bg><p:bgPr><a:solidFill><a:srgbClr val="${color}"/></a:solidFill></p:bgPr></p:bg><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${title}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
}
function slideXmlWithShow(title: string, show: string) {
return `<p:sld show="${show}" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${title}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
}
function slideXmlWithTextStyles(title: string, subtitle: string) {
return `<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:rPr sz="3400"><a:solidFill><a:srgbClr val="C2410C"/></a:solidFill><a:latin typeface="Courier New"/></a:rPr><a:t>${title}</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:txBody><a:p><a:r><a:rPr sz="2200"><a:solidFill><a:srgbClr val="0F766E"/></a:solidFill><a:latin typeface="Times New Roman"/></a:rPr><a:t>${subtitle}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
}
+56 -4
View File
@@ -24,6 +24,14 @@ type ZipEntry = {
async(type: "base64"): Promise<string>;
};
type ZipArchive = { files?: Record<string, unknown>; file: (path: string) => ZipEntry | null };
type WritableZipArchive = {
file: {
(path: string): ZipEntry | null;
(path: string, data: string): WritableZipArchive;
};
generateAsync: (options: { type: "blob"; mimeType: string }) => Promise<Blob>;
};
type ZipConstructor = { loadAsync: (data: ArrayBuffer) => Promise<WritableZipArchive> };
const slidePathPattern = /^ppt\/slides\/slide(\d+)\.xml$/;
const slideRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide";
@@ -66,6 +74,7 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
? extractOrderedTextBodyTexts(orderedParser.parse(notesXml)).join("\n") || extractTextBlocks(parser.parse(notesXml)).join("\n")
: "";
const backgroundColor = slideBackgroundColor(parsedSlide);
const hidden = slideHidden(parsedSlide);
return {
id: `pptx-slide-${index}`,
@@ -73,6 +82,7 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
subtitle: slideTextBlocks.slice(1).map((block) => block.text).join("\n"),
notes,
theme: "classic" as const,
...(hidden ? { hidden } : {}),
...(backgroundColor ? { backgroundColor } : {}),
...(slideTextBlocks[0]?.color ? { titleColor: slideTextBlocks[0].color } : {}),
...(slideTextBlocks[0]?.fontSize ? { titleFontSize: slideTextBlocks[0].fontSize } : {}),
@@ -169,7 +179,8 @@ export async function exportPptxBlob(deck: ExportablePowerPointDeck): Promise<Bl
}
const result = await pptx.write({ outputType: "blob" });
return result instanceof Blob ? result : new Blob([result], { type: PPTX_MIME_TYPE });
const blob = result instanceof Blob ? result : new Blob([result], { type: PPTX_MIME_TYPE });
return deck.slides.some((slide) => slide.hidden) ? applyHiddenSlidesToPptxBlob(blob, deck.slides) : blob;
}
export function extractTextBlocks(xmlNode: unknown): string[] {
@@ -448,6 +459,38 @@ function slideBackgroundColor(slideXml: unknown) {
return normalizeHexColor(stringValue(srgbColor.val ?? srgbColor["@_val"]));
}
function slideHidden(slideXml: unknown) {
const slide = childRecord(slideXml, "sld");
return isFalseXmlBoolean(slide.show ?? slide["@_show"]);
}
async function applyHiddenSlidesToPptxBlob(blob: Blob, slides: Slide[]) {
const JSZip = await loadJsZip();
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
await Promise.all(
slides.map(async (slide, index) => {
if (!slide.hidden) {
return;
}
const path = `ppt/slides/slide${index + 1}.xml`;
const xml = await zip.file(path)?.async("string");
if (xml) {
zip.file(path, pptxSlideXmlWithHiddenState(xml));
}
})
);
return zip.generateAsync({ type: "blob", mimeType: PPTX_MIME_TYPE });
}
function pptxSlideXmlWithHiddenState(xml: string) {
return xml.replace(/<p:sld\b([^>]*)>/, (_match, attributes: string) => {
const withoutShow = attributes.replace(/\sshow="[^"]*"/, "");
return `<p:sld${withoutShow} show="0">`;
});
}
function normalizeHexColor(value?: string) {
const raw = value?.trim().replace(/^#/, "").toUpperCase() ?? "";
return /^[0-9A-F]{6}$/.test(raw) ? raw : "";
@@ -490,17 +533,26 @@ function numberAttribute(record: Record<string, unknown>, name: string) {
return Number.isFinite(value) ? value : undefined;
}
function isFalseXmlBoolean(value: unknown) {
const normalized = String(value ?? "").trim().toLowerCase();
return normalized === "0" || normalized === "false";
}
function emuToInches(value: number) {
return Math.max(0, Math.round((value / emuPerInch) * 1000) / 1000);
}
async function loadZip(file: File): Promise<ZipArchive> {
const moduleName = "jszip";
const jsZipModule = (await import(moduleName)) as { default?: { loadAsync: (data: ArrayBuffer) => Promise<ZipArchive> } };
const jsZip = jsZipModule.default ?? (jsZipModule as unknown as { loadAsync: (data: ArrayBuffer) => Promise<ZipArchive> });
const jsZip = await loadJsZip();
return jsZip.loadAsync(await readOfficeFileAsArrayBuffer(file));
}
async function loadJsZip(): Promise<ZipConstructor> {
const moduleName = "jszip";
const jsZipModule = (await import(moduleName)) as { default?: ZipConstructor } & ZipConstructor;
return jsZipModule.default ?? jsZipModule;
}
async function createXmlParser(): Promise<{ parse: (xml: string) => unknown }> {
const moduleName = "fast-xml-parser";
const parserModule = (await import(moduleName)) as { XMLParser: XmlParserConstructor };