You don't have to go for export options in the API since the pdf file is just available in the drive and there is no conversion happening from Google doc format to any convertion format like pdf. That's why you are getting NPE
on getting export links. You can download the file by placing a Http Get request through API directly as shown below
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
You have to create a FileOutputStream
instead of ByteArrayOutputStream
to create a file with the InputStream
. Below snippet may help
OutputStream outputStream = new FileOutputStream(new File("/home/input.pdf"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
Ensure that you flush the OutputStream
and close both the streams after use.
Note : I got to this detailed answer after discussion with OP in chat. To make it simple, OP used ByteArrayOutputStream
instead of FileOutputStream
to create the pdf file. Hope this helps someone passes by!