12380網(wǎng)站建設情況總結海外銷售平臺有哪些
poi生成的ppt,powerPoint打開提示內容錯誤解決方案
最近做了ppt的生成,使用poi制作ppt,出現(xiàn)一個問題。微軟的powerPoint打不開,提示錯誤信息
通過xml對比工具發(fā)現(xiàn)只需要刪除幻燈片的某些標簽即可解決。
用的是XML Notepand
分析思路:
1.把poi生成的pptx用wps打開,正常,但是poi生成的pptx在powerPoint打不開。嘗試用wps另存一份,ok,wps另存后的ppt,powerPoint可以打開了。然后ppt的大小也有了變化,肯定是wps對這個ppt做了一些格式化操作。具體是啥呢,不清楚,只能用這個 XML Notepand 對比看看吧。
2. ppt本質上是xml的壓縮包集合。我們對ppt進行解壓。
3.里面的東西挺多了,我自己也不怎么懂,但是我想既然是ppt的某個幻燈片打不開,那我就對比一下能幻燈片,看看poi生成的ppt和wps另存后的ppt的幻燈片有哪些區(qū)別。
我們進入這個目錄
4.這個就是放置幻燈片的位置。
我們通過這個XML Notepand 進行一個對比觀察,
我們先用xml notePand打開poi生成的一個幻燈片,我打開的是wsp另存的解壓后的第4個幻燈片,ppt\slides\slide4.xml
然后選擇這個,再次選擇一個poi生成的ppt,選擇同一個幻燈片,進行一個對比
然后進行兩個文件對比
最后對比發(fā)現(xiàn)這個標簽可能不可以被powerPoint正確識別,我們就把這個標簽刪除
<p:custDataLst><p:tags r:id="rId1"/>
</p:custDataLst>
最關鍵的來了,直接上代碼
package com.ruoyi.ppt.utilsService;import com.ruoyi.ppt.aopCustom.customAnnotations.LogExecutionTime;
import com.ruoyi.ppt.config.ThreadPoolDealTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.w3c.dom.*;import javax.annotation.Resource;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;@Slf4j
@Component
public class PptXmlFormate {@Resourceprivate ThreadPoolDealTask threadPoolDealTask;@LogExecutionTime("PPT XML標簽調整耗時")public void xmlFormate(String pptxFilePath, String useFont) {useFont = StringUtils.isBlank(useFont) ? "宋體" : useFont;// 使用 try-with-resources 自動關閉臨時文件和 Zip 流try {// 創(chuàng)建臨時文件來存儲更新后的 PPTX 文件File tempFile = File.createTempFile("pptx_temp" + UUID.randomUUID(), ".zip");tempFile.deleteOnExit();// 讀取 PPTX 文件并更新 XMLtry (FileInputStream fis = new FileInputStream(pptxFilePath);ZipInputStream zis = new ZipInputStream(fis);FileOutputStream fos = new FileOutputStream(tempFile);ZipOutputStream zos = new ZipOutputStream(fos)) {ZipEntry entry;Map<String, ByteArrayOutputStream> updatedFiles = new HashMap<>();// 遍歷 PPTX 文件中的每個條目while ((entry = zis.getNextEntry()) != null) {String entryName = entry.getName();ByteArrayOutputStream entryData = new ByteArrayOutputStream();// 讀取條目內容byte[] buffer = new byte[1024];int len;while ((len = zis.read(buffer)) > 0) {entryData.write(buffer, 0, len);}// 僅處理幻燈片 XML 文件if (entryName.startsWith("ppt/slides/slide") && entryName.endsWith(".xml")) {// 解析 XMLtry (ByteArrayInputStream bais = new ByteArrayInputStream(entryData.toByteArray());ByteArrayOutputStream updatedXml = new ByteArrayOutputStream()) {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();factory.setNamespaceAware(true);DocumentBuilder builder = factory.newDocumentBuilder();Document document = builder.parse(bais);// 異步任務,并確保異常捕獲CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {// 刪除標簽String custDataLstXpath = "//*[local-name()='custDataLst']";removeNodesUsingXPath(document, custDataLstXpath);}, threadPoolDealTask.getThreadPoolExecutor());// 捕獲并處理異步任務中的異常future.exceptionally(ex -> {log.error("處理 XML 異步任務時發(fā)生錯誤: {}", ex.getMessage(), ex);return null;}).join(); // 等待任務完成// 寫入修改后的 XML 內容TransformerFactory transformerFactory = TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");DOMSource source = new DOMSource(document);StreamResult result = new StreamResult(updatedXml);transformer.transform(source, result);updatedFiles.put(entryName, updatedXml);}} else {// 對于其他條目,保持原樣updatedFiles.put(entryName, entryData);}}// 寫入更新后的 PPTX 文件for (Map.Entry<String, ByteArrayOutputStream> fileEntry : updatedFiles.entrySet()) {String entryName = fileEntry.getKey();ByteArrayOutputStream fileData = fileEntry.getValue();zos.putNextEntry(new ZipEntry(entryName));fileData.writeTo(zos);zos.closeEntry();}zos.finish();}// 將臨時文件移動到原始 PPTX 文件路徑,替換原文件Files.move(tempFile.toPath(), new File(pptxFilePath).toPath(), StandardCopyOption.REPLACE_EXISTING);} catch (IOException e) {log.error("處理文件時發(fā)生 IO 錯誤: {}", e.getMessage(), e);} catch (Exception e) {log.error("處理過程中發(fā)生錯誤: {}", e.getMessage(), e);}}public void removeNodesUsingXPath(Document document, String xpathExpression) {XPath xPath = XPathFactory.newInstance().newXPath();// 設置命名空間前綴和 URINamespaceContext nsContext = new NamespaceContext() {public String getNamespaceURI(String prefix) {switch (prefix) {case "a":return "http://schemas.openxmlformats.org/drawingml/2006/main";case "p":return "http://schemas.openxmlformats.org/presentationml/2006/main";default:return XMLConstants.NULL_NS_URI;}}public String getPrefix(String namespaceURI) {return null;}public Iterator getPrefixes(String namespaceURI) {return null;}};xPath.setNamespaceContext(nsContext);try {NodeList nodes = (NodeList) xPath.evaluate(xpathExpression, document, XPathConstants.NODESET);for (int i = nodes.getLength() - 1; i >= 0; i--) { // 從后向前遍歷Node node = nodes.item(i);Node parentNode = node.getParentNode();if (parentNode != null) {parentNode.removeChild(node);}}} catch (Exception e) {log.error("Error removing nodes using XPath: {}", e.getMessage());}}}
注意哈,這里使用了線程池,不需要的可以刪除,需要的話不會配置的,這里也給出代碼
package com.ruoyi.ppt.config;import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;@Slf4j
@Configuration
@Data
public class ThreadPoolDealTask {private volatile ThreadPoolExecutor threadPool;// 自定義 ThreadFactory,為線程池中的線程指定名稱private ThreadFactory createThreadFactory(String poolName) {AtomicInteger counter = new AtomicInteger(0);return r -> {Thread thread = new Thread(r);thread.setName(poolName + "-thread-" + counter.incrementAndGet());return thread;};}// 懶加載線程池,只有在第一次使用時才會創(chuàng)建 用于 業(yè)務處理public void initializeThreadPool() {if (this.threadPool == null) {synchronized (this) {if (this.threadPool == null) { // 雙重檢查鎖定this.threadPool = new ThreadPoolExecutor(2,10,30L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(50),createThreadFactory("CustomThreadPool"), // 使用自定義的 ThreadFactorynew ThreadPoolExecutor.CallerRunsPolicy());// 啟用核心線程超時this.threadPool.allowCoreThreadTimeOut(false);}}}}public ThreadPoolExecutor getThreadPoolExecutor() {return this.threadPool;}// 輸出任務隊列狀態(tài)private void printQueueStatus() {if (threadPool instanceof ThreadPoolExecutor) {ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool;System.out.println("Submitting task to thread: " + Thread.currentThread().getName());System.out.println("當前任務隊列大小: " + executor.getQueue().size());System.out.println("當前任務隊列大小: " + executor.getQueue().size());System.out.println("當前活動線程數(shù): " + executor.getActiveCount());System.out.println("當前線程池大小: " + executor.getPoolSize());}}// 提交任務并返回Future對象public <T> Future<T> submitTask(Callable<T> task) {initializeThreadPool(); // 確保線程池已初始化return threadPool.submit(task);}// 提交Runnable任務并返回Futurepublic Future<?> submitTask(Runnable task) {initializeThreadPool(); // 確保線程池已初始化return threadPool.submit(task);}// 優(yōu)雅地關閉線程池public void shutdown() {if (threadPool != null) {threadPool.shutdown();try {// 等待現(xiàn)有任務執(zhí)行完畢if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {threadPool.shutdownNow(); // 強制關閉// 等待任務響應中斷if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {System.err.println("線程池未能在指定時間內關閉");}}} catch (InterruptedException ie) {// 在當前線程被中斷時,也強制關閉線程池threadPool.shutdownNow();// 保留中斷狀態(tài)Thread.currentThread().interrupt();} finally {threadPool = null; // 關閉后將線程池引用置為空}}}}
現(xiàn)在解決了xml的標簽問題,
最后只需要生成后的ppt地址,傳入這個方法,執(zhí)行一次標簽刪除即可
處理前效果:
處理后效果: