django网站利用服务器上的powerpoint或wps将pptx转换成图片实现在线预览
我自己的网站出现了一个问题那就是在预览大的pptx 时打不开我是用pptxjs实现预览的。为了解决这个问题我通过从网上查找资料用powerpoint或wps将pptx导出为图片然后预览图片很顺利地解决了这个问题。下面我将我的方法分享给大家希望能够对大家有所帮助。需要安装的包有pywin32,python-pptx,pillow。views.py中的预览函数代码如下import os import time import win32com.client import pythoncom from django.conf import settings from django.shortcuts import render def preview(request): ppt_rel request.GET.get(path, ) ppt_full os.path.join(settings.BASE_DIR, ppt_rel) ppt_dir os.path.dirname(ppt_full) ppt_name os.path.splitext(os.path.basename(ppt_full))[0] img_dir os.path.join(ppt_dir, ppt_name) image_list [] # 已有图片 → 路径100%正确 if os.path.isdir(img_dir): for img in sorted(os.listdir(img_dir)): if img.endswith((.png, .jpg, .jpeg)): # ✅ 强制补全根路径 / web_path os.path.join(img_dir, img).replace(settings.BASE_DIR, ).replace(\\, /) image_list.append(settings.MEDIA_URL web_path.replace(media/,)) return render(request, preview.html, {image_list: image_list}) os.makedirs(img_dir, exist_okTrue) try: pythoncom.CoInitialize() powerpoint win32com.client.Dispatch(PowerPoint.Application) try: powerpoint.WindowState 2 # 最小化 powerpoint.Visible 0 # 不可见 except: pass pres powerpoint.Presentations.Open(ppt_full, WithWindowFalse) total pres.Slides.Count # 导出所有页 for i in range(1, total 1): img_path os.path.join(img_dir, f{i}.png) pres.Slides(i).Export(img_path, PNG) time.sleep(0.2) # 安全关闭彻底解决 IUnknown 报错 pres.Close() powerpoint.Quit() # 销毁对象 释放COM del pres del powerpoint pythoncom.CoUninitialize() time.sleep(1) for img in sorted(os.listdir(img_dir)): if img.endswith((.png, .jpg, .jpeg)): # ✅ 强制补全根路径 / web_path os.path.join(img_dir, img).replace(settings.BASE_DIR, ).replace(\\, /) image_list.append(settings.MEDIA_URL web_path.replace(media/,)) except Exception as e: print(错误, e) return render(request, preview.html, {image_list: image_list})previewpptx.html代码如下!DOCTYPE html html head meta charsetutf-8 titlePPT预览/title style img { width: 100%; max-width: 1000px; display: block; margin: 20px auto; border: 1px solid #ccc; } /style /head body {% for img in image_list %} img src{{ img }} {% empty %} h3正在生成预览请刷新页面.../h3 {% endfor %} /body /htmlurls.py内容如下……path(preview/, views.preview),#预览pptx……