Spire.PDF for Python调用PdfDocument.Close()触发AttributeError错误
PDF转SVG成功但触发AttributeError错误的解决方法
环境信息
- Python 3.12
- spire.pdf==9.8.0
- plum-dispatch==1.7.4
- 已安装spire.pdf_11.3二进制文件
问题代码
改编自官方教程的代码如下:
from spire.pdf.common import * from spire.pdf import * myfile = 'c:/atelier/myimage.pdf' doc = PdfDocument() doc.LoadFromFile(myfile) doc.SaveToFile('c:/atelier/ToSVG.svg', FileFormat.SVG) doc.Close()
错误现象
执行代码后,ToSVG.svg文件能正常生成,但触发以下错误(由doc.Close()语句引发):
Exception ignored in: <function PdfDocument.del at 0x00000172D7233740>
Traceback (most recent call last):
File "C:\Users\suzanne\AppData\Local\Programs\Python\Python312\Lib\site-packages\spire\pdf\PdfDocument.py", line 48, in del
AttributeError: 'NoneType' object has no attribute 'PdfDocument_Dispose'
原因分析
调用doc.Close()后,PdfDocument对象的底层资源已经被释放,但Python垃圾回收机制在清理该对象时,__del__方法会再次尝试调用资源释放逻辑,此时相关资源已变为None,从而触发AttributeError。
解决方案
有两种简单的解决方式:
方式1:移除doc.Close()语句
Spire.PDF的SaveToFile执行完成后,无需手动调用Close(),对象的__del__方法会自动处理资源释放,修改后代码:
from spire.pdf.common import * from spire.pdf import * myfile = 'c:/atelier/myimage.pdf' doc = PdfDocument() doc.LoadFromFile(myfile) doc.SaveToFile('c:/atelier/ToSVG.svg', FileFormat.SVG)
方式2:使用上下文管理器(with语句)
利用Python的上下文管理器自动管理对象生命周期,避免手动调用Close()的问题,代码如下:
from spire.pdf.common import * from spire.pdf import * myfile = 'c:/atelier/myimage.pdf' with PdfDocument() as doc: doc.LoadFromFile(myfile) doc.SaveToFile('c:/atelier/ToSVG.svg', FileFormat.SVG)
两种方式都能确保正常生成SVG文件且不会触发错误。
内容的提问来源于stack exchange,提问作者Suzanne
相关产品推荐
相关产品推荐

