如何使用 Python 将渲染的 HTML 模板插入 Google 文档
问题内容
我面临一个挑战,即使用 python 以编程方式将 html 模板插入到 google 文档中。我知道 google 文档编辑器或 google 文档 api 中没有原生/内置功能可以解决我的问题,但我尝试了一些技巧来达到我的目标。这里我们忽略了我们应该插入文档中的“哪里”,现在只要成功插入就足够了。
我的方法是:
application/vnd.google-apps.document
,因为 google 文档会自动将 html 转换为文档。 (不完美,但有效)def insert_template_to_file(target_file_id, content): media = MediaIoBaseUpload(BytesIO(content.encode('utf-8')), mimetype='text/html', resumable=True) body = { 'name': 'document_test_html', 'mimeType': 'application/vnd.google-apps.document', 'parents': [DOC_FOLDER_ID] } try: 1. Create HTML as docs because it automatically convert html to docs content_file = driver_service.files().create(body=body, media_body=media).execute() content_file_id = content_file.get('id') 1. Collect html content from Google Docs after created doc = docs_service.documents().get(documentId=content_file_id, fields='body').execute() request_content = doc.get('body').get('content') 1. Insert the content from html to target file result = docs_service.documents().batchUpdate(documentId=target_file_id, body={'requests': request_content}).execute() print(result) 1. Delete html docs driver_service.files().delete(fileId=content_file_id).execute() print("Content inserted successfuly") except HttpError as error: 1. Delete html docs even if failed driver_service.files().delete(fileId=content_file_id).execute() print(f"An error occurred: {error}") 登录后复制