谷歌表格API导出PDF为1.4版本致文本截断,需导出1.7版本
解决Google Sheets API导出PDF版本1.4导致文本截断的问题
通过Google Sheets API导出PDF时,生成的文件版本为1.4,行尾部分字符被截断;但手动打印或下载PDF时,文件版本为1.7且无截断问题,表格内显示正常。当前使用的导出代码如下:
export_url = f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/export?format=pdf" export_options = { "format": "pdf", "portrait": True, # Set to False for landscape orientation "fitw": True, # Adjust the sheet to fit on a page "sheetnames": False, # Hide sheet names "horizontal_alignment": "CENTER", # Set sheet in the center horizontally "vertical_alignment": "MIDDLE", # Set sheet in the center vertically "scale": 4, # 1 = 100% scaling "size": "A4", # Page size options } response = requests.get(export_url, params=export_options) with open(pdf_path, "wb") as f: f.write(response.content)
解决方案
1. 补充手动导出的默认参数,升级PDF版本
手动导出PDF时,Google会自动携带一些额外参数,这些参数能让导出的PDF版本升级到1.7,同时优化排版避免截断。修改export_options添加这些参数:
export_options = { "format": "pdf", "portrait": True, "fitw": True, "sheetnames": False, "printtitle": False, # 隐藏文档标题 "pagenum": "UNDEFINED", # 不显示页码 "attachment": True, # 以附件模式导出,和手动下载逻辑一致 "horizontal_alignment": "CENTER", "vertical_alignment": "MIDDLE", "scale": 4, "size": "A4", "fzr": False, # 禁用行冻结(避免冻结行导致排版异常) "gridlines": False, # 隐藏网格线(可选,根据需求调整) }
添加这些参数后,API导出的PDF会和手动导出保持一致,版本升级为1.7,同时解决文本截断问题。
2. 调整缩放比例适配页面
如果上述参数无效,尝试调整scale参数降低缩放比例,避免内容被过度压缩导致截断:
export_options = { # 其他参数不变 "scale": 3, # 改为75%缩放(1=100%,2=75%,3=50%,4=25%) "fitw": True, }
3. 检查表格排版设置
确保表格中需要换行的单元格已开启自动换行功能,列宽设置足够容纳内容。可以在Google Sheets界面手动调整后再导出,也可以通过API设置单元格的自动换行属性。
内容的提问来源于stack exchange,提问作者Akshat Shah
相关产品推荐
相关产品推荐

