Python实现Google Sheet标签PDF导出与本地打印及格式问题解决
解决方案:Google Sheets标签导出与打印问题修复
问题修复总览
针对PDF格式异常、Claims标签空白、自定义尺寸触发TypeError这三个问题,以下是调整后的完整代码,同时附带问题根源的说明:
完整可运行代码
import os import requests import win32print import win32api from google.oauth2.service_account import Credentials from googleapiclient.discovery import build # Google Sheets API配置 SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] SERVICE_ACCOUNT_FILE = 'your-service-account-key.json' SPREADSHEET_ID = 'your-spreadsheet-id' # 打印机配置 ROLLO_PRINTER_NAME = "Rollo Printer" # 替换为你的Rollo打印机名称 LABEL_SHEET_NAME = "Label" CLAIMS_SHEET_NAME = "Claims" def get_google_sheets_service(): creds = Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) return build('sheets', 'v4', credentials=creds) def get_label_print_count(service): # 获取F2单元格的打印份数 result = service.spreadsheets().values().get( spreadsheetId=SPREADSHEET_ID, range=f"{LABEL_SHEET_NAME}!F2").execute() values = result.get('values', []) return int(values[0][0]) if values else 1 def export_sheet_to_pdf(sheet_name, is_landscape=True, page_size="4x6"): # 构建PDF导出URL url = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/export" # 4x6尺寸对应的参数(单位:点,1英寸=72点) page_width = 4 * 72 page_height = 6 * 72 params = { 'format': 'pdf', 'gid': get_sheet_gid(sheet_name), 'portrait': 'false' if is_landscape else 'true', 'fitw': 'true', # 适配页面宽度 'sheetnames': 'false', 'printtitle': 'false', 'pagenumbers': 'false', 'gridlines': 'false', 'fzr': 'false', # 不冻结行 'width': page_width, 'height': page_height, 'scale': '4', # 调整缩放比例,解决字体过小问题(可根据实际调整) 'top_margin': 0, 'bottom_margin': 0, 'left_margin': 0, 'right_margin': 0 } # 使用服务账号凭证请求PDF creds = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) headers = {'Authorization': f'Bearer {creds.token}'} response = requests.get(url, headers=headers, params=params) if response.status_code == 200: temp_pdf_path = f"{sheet_name}_temp.pdf" with open(temp_pdf_path, 'wb') as f: f.write(response.content) return temp_pdf_path else: raise Exception(f"导出{sheet_name}失败:{response.status_code}") def get_sheet_gid(sheet_name): # 获取指定工作表的GID service = get_google_sheets_service() spreadsheet = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute() for sheet in spreadsheet['sheets']: if sheet['properties']['title'] == sheet_name: return sheet['properties']['sheetId'] raise Exception(f"未找到工作表:{sheet_name}") def print_pdf(pdf_path, printer_name, copies=1): # 使用win32api打印PDF if not os.path.exists(pdf_path): raise Exception(f"PDF文件不存在:{pdf_path}") # 调用系统打印命令(假设已安装PDF阅读器关联) for _ in range(copies): win32api.ShellExecute( 0, "print", pdf_path, f'/d:"{printer_name}"', ".", 0 ) def main(): try: service = get_google_sheets_service() # 处理Label标签 label_copies = get_label_print_count(service) label_pdf = export_sheet_to_pdf(LABEL_SHEET_NAME, is_landscape=True) print_pdf(label_pdf, ROLLO_PRINTER_NAME, copies=label_copies) os.remove(label_pdf) # 处理Claims标签 claims_pdf = export_sheet_to_pdf(CLAIMS_SHEET_NAME, is_landscape=False) # 根据实际需求调整方向 print_pdf(claims_pdf, ROLLO_PRINTER_NAME, copies=1) os.remove(claims_pdf) print("打印任务已提交") except Exception as e: print(f"错误:{str(e)}") if __name__ == "__main__": main()
各问题的具体修复说明
1. PDF格式异常(横向/字体过小)
- 横向设置:在导出参数中通过
portrait: 'false'强制设置为横向,替代之前错误的landscape()调用方式,避免TypeError。 - 字体过小:添加
scale: '4'参数放大内容(可根据实际显示效果调整数值,范围1-4),同时设置fitw: 'true'让内容适配页面宽度。 - 4x6尺寸:直接通过
width和height参数设置页面尺寸(单位为点,1英寸=72点),同时将边距设为0,确保标签内容占满整个4x6区域。
2. Claims标签打印空白
- 修复了导出逻辑:确保
export_sheet_to_pdf函数正确获取Claims工作表的GID,避免因GID错误导致导出空白内容。 - 移除了可能限制导出范围的参数,确保整个工作表内容被导出(如果需要指定范围,可在
params中添加range参数,例如range: "Claims!A1:Z100")。
3. TypeError: landscape() takes 1 positional argument but 2 were given
- 原错误是因为错误调用了某个
landscape()方法并传递了多余参数,现在改为在PDF导出的URL参数中通过portrait字段控制方向,彻底避免该错误。
内容的提问来源于stack exchange,提问作者Anthony Madle
相关产品推荐
相关产品推荐

