使用Gotenberg API结合Python Requests设置PDF页面属性失败求助
问题分析与解决方法
核心问题:参数传递方式错误
Gotenberg API处理Word/Excel转PDF的页面属性参数时,不能通过URL参数(params)或普通表单data传递,必须将这些参数作为multipart/form-data的表单字段,和待转换文件一同提交。
正确实现示例
Word文档转换(带页面属性)
针对Word文档,页面属性参数(如scale、singlePage)需作为表单字段传入:
import requests # Gotenberg服务地址 url = "http://localhost:3000/convert/office" # 待转换的Word文件 files = { "file": open("your_document.docx", "rb") } # 页面属性参数,注意值为字符串格式 form_data = { "scale": "1.2", # 缩放比例,1.0为原尺寸 "singlePage": "true" # 强制单页显示 } # 发送请求并保存结果 response = requests.post(url, files=files, data=form_data) with open("converted_word.pdf", "wb") as f: f.write(response.content)
Excel文档转换(带页面属性)
Excel的页面属性参数有专属命名,需使用excelSinglePage、excelScale这类字段:
import requests url = "http://localhost:3000/convert/office" files = { "file": open("your_spreadsheet.xlsx", "rb") } form_data = { "excelSinglePage": "true", # Excel专属单页显示参数 "excelScale": "0.9" # Excel文档缩放比例 } response = requests.post(url, files=files, data=form_data) with open("converted_excel.pdf", "wb") as f: f.write(response.content)
关键注意事项
- 参数值必须为字符串类型:比如传
"true"而非布尔值True,Gotenberg的表单解析仅识别字符串格式的布尔参数。 - 区分文档类型的参数命名:Word/PPT用
scale、singlePage;Excel必须用excelScale、excelSinglePage。 - 禁止用
params(URL后缀)或json参数传递:上传文件时请求编码为multipart/form-data,data参数会自动适配该编码格式,确保参数被正确解析。
内容的提问来源于stack exchange,提问作者Roo
相关产品推荐
相关产品推荐

