如何使用Python在Google Drive API中操作PDF

时间:2014-07-08 13:55:15

标签: python pdf google-drive-api

我必须在驱动器上拆分PDF。所以我想知道是否有办法在Drive API上操作PDF。 有没有人知道如何制作这些行动中的至少一种

  • 分割
  • 获取页数
  • 剪切页面
  • ...

1 个答案:

答案 0 :(得分:1)

这是一个解决方案,用于在Drive中显示PDF文件的页数,将其拆分为每个页面的单独PDF,然后将新创建的PDF插回到Drive中。

要执行以下代码,您需要在Google Developer Console中定义项目。如果您还没有https://console.developers.google.com/project,可以在{{3}}创建一个新的。

创建项目后,单击它以打开项目仪表板。转到APIS & Auth> Credentials并为已安装的应用程序创建新的OAuth客户端ID(如果您还没有此项目的ID)。将下面的代码中的client_id,client_secret和redirect_uri分别替换为Client ID,Client Secret和列出的第一个重定向URI。

该程序将首先在您的网络浏览器中打开一个页面,以获取创建新OAuth令牌所需的验证码。然后,它将在驱动器中询问PDF文件的fileId,将显示此PDF的页数,并将每个页面作为单独的PDF插入驱动器中。

from cStringIO import StringIO
import os
import webbrowser

from apiclient.discovery import build
from apiclient.http import MediaInMemoryUpload
import httplib2
from oauth2client.client import OAuth2WebServerFlow
import pyPdf


CLIENT_ID = 'client_id'
CLIENT_SECRET = 'client_secret'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'redirect_url'


class GoogleDriveManager(object):

  def __init__(self):
    # Create new Google Drive credentials.
    flow = OAuth2WebServerFlow(
        CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    webbrowser.open(authorize_url)
    code = raw_input('Enter verification code: ').strip()
    self._credentials = flow.step2_exchange(code)

  def GetFile(self, file_id):
    http = httplib2.Http()
    http = self._credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
    url = drive_service.files().get(fileId=file_id).execute()['downloadUrl']
    return http.request(url, "GET")[1]

  def GetFileName(self, file_id):
    http = httplib2.Http()
    http = self._credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
    return drive_service.files().get(fileId=file_id).execute()['title']

  def InsertFile(self, file_name, data, mimeType):
    http = httplib2.Http()
    http = self._credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
    media_body = MediaInMemoryUpload(
        data, mimetype='text/plain', resumable=True)
    body = {
      'title': file_name,
      'mimeType': mimeType
    }
    drive_service.files().insert(body=body, media_body=media_body).execute()


if __name__ == '__main__':
  # Create a drive manager.
  drive_manager = GoogleDriveManager()
  file_id = raw_input('Enter the file id of the pdf file: ').strip()
  file_name, ext = os.path.splitext(drive_manager.GetFileName(file_id))
  # Download the pdf file.
  pdf_data = drive_manager.GetFile(file_id)
  pdf = pyPdf.PdfFileReader(StringIO(pdf_data))
  print "Number of pages: %d" % pdf.getNumPages()
  for i in xrange(pdf.getNumPages()):
    writer = pyPdf.PdfFileWriter()
    writer.addPage(pdf.getPage(i))
    page_data = StringIO()
    writer.write(page_data)
    drive_manager.InsertFile(
        file_name + '-' + str(i) + ext, page_data.getvalue(), 'application/pdf')