簡體   English   中英

如何將存儲在 Google Drive 上的 Google Docs 文件(文檔模板)轉換為 PDF 並下載?

[英]How do I convert Google Docs file (Template for Document) Stored on Google Drive to PDF and download it?

現在被困了幾個小時。 我有一個可以用 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()

如果名稱== '主要': main()

我相信你現在的情況和你的目標如下。

  • 您有一個 Google 文檔作為模板文檔。
  • 您希望使用針對 python 的 googleapis 實現以下流程。
    1. 復制模板文檔。
    2. 更新復制的文檔。
    3. 將更新后的文檔下載為 PDF 文件。
    4. 刪除復制的文檔。

修改點:

  • 您的腳本會更新現有的 Google 文檔。 所以為了實現你的目標,需要准備其他流程。
  • 為了復制模板文檔,下載文檔為 PDF 文件並刪除文檔,驅動器 API 使用如下。 並且,當更新文檔時,將使用文檔 API。
    1. 復制模板文檔。
      • 在這種情況下,使用驅動器 API。
    2. 更新復制的文檔。
      • 在這種情況下,使用 Docs API 並且使用 yoru script 中的腳本。
    3. 將更新后的文檔下載為 PDF 文件。
      • 在這種情況下,使用驅動器 API。
    4. 刪除復制的文檔。
      • 在這種情況下,使用驅動器 API。

當你的腳本被修改后,它變成如下。

修改后的腳本:

在這個修改后的腳本中,它假設creds of credentials=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
  • 在這個答案中,它假設您的 request1 requests1主體service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests1}).execute()可以正常工作。 所以請注意這一點。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM