python-3.xgoogle-drive-apiexport-to-pdf

Setting pdf export options in google drive for python


I am downloading a google spreadsheet as a pdf using this command.

    response = files_service.files().export_media( fileId=spreadsheet_id,                                                   mimeType='application/pdf').execute()

    with open("download.pdf", "wb") as wer:
        wer.write(response)

Which downloads the file as pdf. However, I need to set the orientation to landscape, custom margins, and custom footer. How do I set it with google drive API v3?

Thanks


Solution

  • If my understanding is correct, how about this sample script? In order to export the custom PDF file, this sample script uses requests.get(). Please think of this as just one of them.

    About access token:

    In this sample script, the access token is used. From your script, you are using files_service.files().export_media(). So I thought that you have already used service = build('drive', 'v3', credentials=creds) as shown in Quickstart. In this case, you can retrieve the access token as follows.

    accessToken = creds.token
    

    Sample script:

    When you use this script, please replace your script to the following script. In this sample script, the orientation to landscape, custom margins and the page number at the footer can be set.

    accessToken = creds.token
    spreadsheetId = '### Spreadsheet ID ###'
    sheetId = '0' # sheetId
    url = ('https://docs.google.com/spreadsheets/d/' + spreadsheetId + '/export?'
           + 'format=pdf'  # export as PDF
           + '&portrait=false'  # landscape
           + '&top_margin=0.00'  # Margin
           + '&bottom_margin=0.00'  # Margin
           + '&left_margin=0.00'  # Margin
           + '&right_margin=0.00'  # Margin
           + '&pagenum=RIGHT'  # Put page number to right of footer
           + '&gid=' + sheetId  # sheetId
           + '&access_token=' + accessToken)  # access token
    r = requests.get(url)
    with open('downloadedPDFfile.pdf', 'wb') as saveFile:
        saveFile.write(r.content)
    print('Done.')
    

    Note:

    Reference:

    If this was not the result you want, I apologize.