如何将存储在Google Drive上的Google文档文件(文档模板)转换为PDF并下载?

2024-09-28 22:02:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我被困在这几个小时了。我有一个可以用python编辑的模板。其思想是复制、编辑、转换、下载文件,然后从驱动器中删除文件,只留下空模板。我已经阅读了文档并尝试了不同的方法,但我想不出来

编辑: 到目前为止我的代码

SCOPES = ['https://www.googleapis.com/auth/drive']


DOCUMENT_ID = '1ZgaYCra-7m_oWIBWK9RoMssYNTAsQLa1ELI1vyBB73c'


def main():
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

     service = build('docs', 'v1', credentials=creds)

    text1 = 'test'

requests1 = [
    {
        'insertText': {
            'location': {
                'index': 110,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 98,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 83,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 72,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 49,
            },
            'text': text1
        }
    },
]

result = service.documents().batchUpdate(
    documentId=DOCUMENT_ID, body={'requests': requests1}).execute()

如果name='main': main()


Tags: andthetexttoken编辑indexmainlocation
1条回答
网友
1楼 · 发布于 2024-09-28 22:02:46

我相信你的现状和目标如下

  • 您有一个Google文档作为模板文档
  • 您希望使用googleapis for python实现以下流程。
    1. 复制模板文档
    2. 更新复制的文档
    3. 将更新后的文档下载为PDF文件
    4. 删除复制的文档

修改点:

  • 您的脚本将更新现有的Google文档。因此,为了实现您的目标,需要准备其他流程
  • 要复制模板文档,请将文档下载为PDF文件并删除文档,驱动器API的使用如下所示。并且,当文档更新时,将使用Docs API。
    1. 复制模板文档。
      • 在这种情况下,将使用驱动器API
    2. 更新复制的文档。
      • 在这种情况下,将使用Docs API,脚本将使用yoru脚本
    3. 将更新后的文档下载为PDF文件。
      • 在这种情况下,将使用驱动器API
    4. 删除复制的文档。
      • 在这种情况下,将使用驱动器API

当您的脚本被修改时,它将变成如下所示

修改的脚本:

在这个修改过的脚本中,它假设从脚本中使用了credentials=creds中的creds。在使用此脚本之前,请设置变量

templateDocumentId = '###' # Please set the Document ID.
outputPDFFilename = 'sample.pdf' # Please set the output PDF filename.

drive = build('drive', 'v3', credentials=creds)
docs = build('docs', 'v1', credentials=creds)

# 1. Copy template Document.
copiedDoc = drive.files().copy(fileId=templateDocumentId, body={'name': 'copiedTemplateDocument'}).execute()
copiedDocId = copiedDoc.get('id')
print('Done: 1. Copy template Document.')

# 2. Update copied Document.
text1 = 'test'
requests1 = [
    {
        'insertText': {
            'location': {
                'index': 110,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 98,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 83,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 72,
            },
            'text': text1
        }
    },
    {
        'insertText': {
            'location': {
                'index': 49,
            },
            'text': text1
        }
    },
]
result = docs.documents().batchUpdate(documentId=copiedDocId, body={'requests': requests1}).execute()
print('Done: 2. Update copied Document.')

# 3. Download the updated Document as PDF file.
request = drive.files().export_media(fileId=copiedDocId, mimeType='application/pdf')
fh = io.FileIO(outputPDFFilename, mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print('Download %d%%.' % int(status.progress() * 100))
print('Done: 3. Download the updated Document as PDF file.')

# 4. Delete the copied Document.
drive.files().delete(fileId=copiedDocId).execute()
print('Done: 4. Delete the copied Document.')

注:

  • 为了下载该文件,还使用了import iofrom googleapiclient.http import MediaIoBaseDownload
  • 在这个答案中,它假设requests1for service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests1}).execute()的请求主体工作正常,正如您所期望的那样。所以请小心这个

参考文献:

相关问题 更多 >