You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spire.Doc安装后无法运行:DOCX转PDF遇RuntimeError问题求助

问题

在Colab中实现docx转pdf功能,执行以下命令安装依赖:

%pip install Spire.Doc
%pip install plum-dispatch

运行以下代码时:

from spire.doc import *
from spire.doc.common import *

inputFile = "example-docs/document.docx"
outputFile = "document.pdf"

#Create word document
document = Document()
document.LoadFromFile(inputFile)

# Create a ToPdfParameterList object
parameters = ToPdfParameterList()

# Embed all used fonts in Word into PDF
parameters.IsEmbeddedAllFonts = True

#Save the file to a PDF file
document.SaveToFile("WordToPdfWithFontsEmbedded.pdf", parameters, FileFormat.PDF)
document.Close()

#Save the document to a PDF file.
# document.SaveToFile(outputFile, FileFormat.PDF)
# document.Close()

触发如下错误:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-2-707d9ebcb6c3> in <cell line: 15>()
     13 
     14 # Embed all used fonts in Word into PDF
---> 15 parameters.IsEmbeddedAllFonts = True
     16 
     17 #Save the file to a PDF file

1 frames
/usr/local/lib/python3.10/dist-packages/spire/doc/common/__init__.py in CallCFunction(func, *args, **kwargs)
    103     args = list(args) +[data]
    104 
--> 105     result = func(*args, **kwargs)
    106     modified_value = cast(data, POINTER(c_uint64)).contents.value
    107     if old_value != modified_value:

RuntimeError: ffi_prep_cif_var failed

原因分析

该错误是因为Spire.Doc的Python版本在Colab的Python 3.10+环境中,底层FFI(外部函数接口)调用存在兼容性问题——设置IsEmbeddedAllFonts属性时,参数类型或调用约定不匹配,导致用于准备C函数调用的ffi_prep_cif_var工具执行失败。

修复方案

方法1:跳过字体嵌入,直接转换

若不需要强制嵌入字体,可注释掉设置IsEmbeddedAllFonts的代码,使用基础转PDF逻辑:

from spire.doc import *
from spire.doc.common import *

inputFile = "example-docs/document.docx"
outputFile = "document.pdf"

document = Document()
document.LoadFromFile(inputFile)
# 直接保存为PDF,不使用字体嵌入参数
document.SaveToFile(outputFile, FileFormat.PDF)
document.Close()

方法2:安装兼容版本的Spire.Doc

尝试安装更早版本的Spire.Doc,该版本在Python 3.10环境下FFI调用更稳定:

%pip install Spire.Doc==12.8.4
%pip install plum-dispatch

安装完成后重新运行原代码测试字体嵌入功能。

方法3:替换为适配Colab的转换工具

若Spire.Doc的兼容性问题无法解决,可换用python-docx配合libreoffice实现转换:

  1. 安装依赖:
%pip install python-docx
!apt-get install libreoffice
  1. 执行转换:
import subprocess

inputFile = "example-docs/document.docx"
outputFile = "document.pdf"

# 调用libreoffice命令行完成转换
subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", inputFile, "--outdir", "."])

内容的提问来源于stack exchange,提问作者MickWise

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:40:23