-
-
Save projektorius96/1d39bc622e2dfb7777cfcc5afd65e79b to your computer and use it in GitHub Desktop.
This is a sample code to upload a PDF file to Google Drive with OCR in Apps Script. uploadPdfOcr function returns a File object. To run the code provide a developer key for an API Console project with Drive API service enabled.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function uploadPdfOcr() { | |
authorize(); | |
var key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // <-- developer key | |
var file = UrlFetchApp.fetch("http://somewhere.com/path/file.pdf").getBlob(); | |
var metadata = { title: file.getName() } | |
var params = {method:"post", | |
oAuthServiceName: "drive", | |
oAuthUseToken: "always", | |
contentType: "application/pdf", | |
contentLength: file.getBytes().length, | |
payload: file.getBytes() | |
}; | |
var uploadRequest = UrlFetchApp.fetch("https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&ocr=true&key="+key, params); | |
var uploadResponse = Utilities.jsonParse(uploadRequest.getContentText()); | |
var params = {method:"put", | |
oAuthServiceName: "drive", | |
oAuthUseToken: "always", | |
contentType: "application/json", | |
payload: Utilities.jsonStringify(metadata) | |
}; | |
var metaRequest = UrlFetchApp.fetch("https://www.googleapis.com/drive/v2/files/"+uploadResponse.id+"?key="+key, params) | |
return DocsList.getFileById(uploadResponse.id); | |
} | |
function convert(fileId) { | |
authorize(); | |
var key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // <-- developer key | |
var params = {method:"post", | |
oAuthServiceName: "drive", | |
oAuthUseToken: "always" | |
}; | |
var uploadRequest = UrlFetchApp.fetch("https://www.googleapis.com/drive/v2/files/"+fileId+"/copy?convert=true&key="+key, params); | |
var uploadResponse = Utilities.jsonParse(uploadRequest.getContentText()); | |
return DocsList.getFileById(uploadResponse.id); | |
} | |
function authorize() { | |
var oauthConfig = UrlFetchApp.addOAuthService("drive"); | |
var scope = "https://www.googleapis.com/auth/drive"; | |
oauthConfig.setConsumerKey("anonymous"); | |
oauthConfig.setConsumerSecret("anonymous"); | |
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope); | |
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken"); | |
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment