Preserve QPowerPoint text styling

This commit is contained in:
Курнат Андрей
2026-06-01 07:08:32 +03:00
parent 36d6b2958d
commit 5a968dea72
6 changed files with 228 additions and 9 deletions
+56
View File
@@ -240,6 +240,58 @@ describe("powerPointOffice helpers", () => {
expect(exportedSlideXml).toContain("FCE4D6");
});
it("импортирует и экспортирует цвет и размер текста слайда", 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", slideXmlWithTextStyles("Заголовок", "Подзаголовок"));
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: "Заголовок",
subtitle: "Подзаголовок",
titleColor: "C2410C",
titleFontSize: 34,
subtitleColor: "0F766E",
subtitleFontSize: 22
});
const exportedBlob = await exportPptxBlob({
title: "Текст.pptx",
slides: [
{
id: "slide-1",
title: "Заголовок",
subtitle: "Подзаголовок",
notes: "",
theme: "classic",
titleColor: "C2410C",
titleFontSize: 34,
subtitleColor: "0F766E",
subtitleFontSize: 22
}
]
});
const exportedZip = await JSZip.loadAsync(await exportedBlob.arrayBuffer());
const exportedSlideXml = await exportedZip.file("ppt/slides/slide1.xml")?.async("string");
expect(exportedSlideXml).toContain("C2410C");
expect(exportedSlideXml).toContain("0F766E");
expect(exportedSlideXml).toContain('sz="3400"');
expect(exportedSlideXml).toContain('sz="2200"');
});
it("нормализует пробелы в импортированном тексте", () => {
expect(normalizeWhitespace(" Строка\tс \n пробелами ")).toBe("Строка с пробелами");
});
@@ -255,6 +307,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 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: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:rPr><a:t>${subtitle}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
}
function slideXmlWithPicture(title: string) {
return `<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><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:pic><p:nvPicPr><p:cNvPr id="4" name="Picture 1" descr="Логотип"/></p:nvPicPr><p:blipFill><a:blip r:embed="rIdImage"/></p:blipFill><p:spPr><a:xfrm><a:off x="914400" y="1828800"/><a:ext cx="2743200" cy="1371600"/></a:xfrm></p:spPr></p:pic></p:spTree></p:cSld></p:sld>`;
}
+63 -7
View File
@@ -11,6 +11,12 @@ export interface ExportablePowerPointDeck {
slides: Slide[];
}
interface SlideTextBlock {
text: string;
color?: string;
fontSize?: number;
}
type XmlParserConstructor = new (options?: Record<string, unknown>) => { parse: (xml: string) => unknown };
type ZipEntry = {
async(type: "string"): Promise<string>;
@@ -49,7 +55,7 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
slidePaths.map(async ({ path, index }) => {
const slideXml = await readRequiredZipText(zip, path, "Не удалось прочитать слайд PowerPoint.");
const parsedSlide = parser.parse(slideXml);
const slideTextBlocks = extractTextBlocks(parsedSlide);
const slideTextBlocks = extractSlideTextBlocks(parsedSlide);
const images = await extractSlideImages(zip, parser, parsedSlide, path, index);
const notesPath = await slideNotesPath(zip, parser, path);
const notesXml = notesPath ? await readOptionalZipText(zip, notesPath) : await readOptionalZipText(zip, `ppt/notesSlides/notesSlide${index}.xml`);
@@ -58,11 +64,15 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
return {
id: `pptx-slide-${index}`,
title: slideTextBlocks[0] || `Слайд ${index}`,
subtitle: slideTextBlocks.slice(1).join("\n"),
title: slideTextBlocks[0]?.text || `Слайд ${index}`,
subtitle: slideTextBlocks.slice(1).map((block) => block.text).join("\n"),
notes,
theme: "classic" as const,
...(backgroundColor ? { backgroundColor } : {}),
...(slideTextBlocks[0]?.color ? { titleColor: slideTextBlocks[0].color } : {}),
...(slideTextBlocks[0]?.fontSize ? { titleFontSize: slideTextBlocks[0].fontSize } : {}),
...(slideTextBlocks[1]?.color ? { subtitleColor: slideTextBlocks[1].color } : {}),
...(slideTextBlocks[1]?.fontSize ? { subtitleFontSize: slideTextBlocks[1].fontSize } : {}),
images
};
})
@@ -98,6 +108,10 @@ export async function exportPptxBlob(deck: ExportablePowerPointDeck): Promise<Bl
for (const sourceSlide of deck.slides) {
const colors = themeColors[sourceSlide.theme] ?? themeColors.classic;
const titleColor = normalizeHexColor(sourceSlide.titleColor) || colors.title;
const subtitleColor = normalizeHexColor(sourceSlide.subtitleColor) || colors.subtitle;
const titleFontSize = normalizeFontSize(sourceSlide.titleFontSize) || 30;
const subtitleFontSize = normalizeFontSize(sourceSlide.subtitleFontSize) || 18;
const slide = pptx.addSlide();
slide.background = { color: normalizeHexColor(sourceSlide.backgroundColor) || colors.background };
sourceSlide.images?.forEach((image, index) => {
@@ -121,9 +135,9 @@ export async function exportPptxBlob(deck: ExportablePowerPointDeck): Promise<Bl
w: 11.9,
h: 0.75,
fontFace: "Arial",
fontSize: 30,
fontSize: titleFontSize,
bold: true,
color: colors.title,
color: titleColor,
margin: 0.04,
breakLine: false
});
@@ -133,8 +147,8 @@ export async function exportPptxBlob(deck: ExportablePowerPointDeck): Promise<Bl
w: 11.5,
h: 4.35,
fontFace: "Arial",
fontSize: 18,
color: colors.subtitle,
fontSize: subtitleFontSize,
color: subtitleColor,
valign: "top",
fit: "shrink",
breakLine: false
@@ -155,6 +169,29 @@ export function extractTextBlocks(xmlNode: unknown): string[] {
return blocks.map(normalizeWhitespace).filter(Boolean);
}
function extractSlideTextBlocks(slideXml: unknown): SlideTextBlock[] {
const textBodies = recordsByKey(slideXml, "txBody");
const blocks = textBodies
.map((textBody) => {
const text = normalizeWhitespace(extractTextBlocks(textBody).join("\n"));
if (!text) {
return null;
}
const runProperties = firstRecordByKey(textBody, "rPr");
const color = runTextColor(runProperties);
const fontSize = runTextFontSize(runProperties);
return {
text,
...(color ? { color } : {}),
...(fontSize ? { fontSize } : {})
};
})
.filter((block): block is SlideTextBlock => Boolean(block));
return blocks.length > 0 ? blocks : extractTextBlocks(slideXml).map((text) => ({ text }));
}
export function listSlidePaths(
zip: ZipArchive,
presentationXml?: unknown,
@@ -350,6 +387,25 @@ function normalizeHexColor(value?: string) {
return /^[0-9A-F]{6}$/.test(raw) ? raw : "";
}
function runTextColor(runProperties: Record<string, unknown>) {
const solidFill = childRecord(runProperties, "solidFill");
const srgbColor = childRecord(solidFill, "srgbClr");
return normalizeHexColor(stringValue(srgbColor.val ?? srgbColor["@_val"]));
}
function runTextFontSize(runProperties: Record<string, unknown>) {
const rawSize = numberAttribute(runProperties, "sz");
return rawSize ? normalizeFontSize(rawSize / 100) : undefined;
}
function normalizeFontSize(value?: number) {
if (!Number.isFinite(value) || !value || value <= 0) {
return undefined;
}
return Math.round(value * 2) / 2;
}
function numberAttribute(record: Record<string, unknown>, name: string) {
const value = Number.parseFloat(stringValue(record[name] ?? record[`@_${name}`]));
return Number.isFinite(value) ? value : undefined;