如何用Python在Google Drive API中处理PDF

1 投票
1 回答
931 浏览
提问于 2025-04-18 12:30

我需要在云端的PDF文件上进行分割。所以我想知道有没有办法通过Drive API来处理PDF文件。有没有人知道怎么做以下这些操作:

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

1 个回答

1

这里有一个解决方案,可以显示一个PDF文件在Drive中的页数,把它拆分成每一页的单独PDF文件,并将新创建的PDF文件重新放回Drive中。

要运行下面的代码,你需要在Google开发者控制台里定义一个项目。如果你还没有项目,可以在https://console.developers.google.com/project创建一个新的项目。

项目创建好后,点击它打开项目仪表板。接着去 APIS & Auth > Credentials,如果这个项目还没有的话,创建一个新的OAuth客户端ID,适用于安装的应用程序。然后在下面的代码中,把client_id、client_secret和redirect_uri分别替换成你的客户端ID、客户端密钥和第一个重定向URI。

程序会首先在你的网页浏览器中打开一个页面,以获取创建新OAuth令牌所需的验证代码。接下来,它会要求你输入Drive中某个PDF文件的fileId,显示这个PDF的页数,并将每一页作为单独的PDF文件放回你的Drive中。

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')

撰写回答