Amarula
Amarula

Reputation: 162

Trying to convert docx file to another format(pdf) using Drive API

I was trying to convert .docx file to .pdf using drive api, which sounds reasonable since you can do it manually. Here is my code:

 FilesResource.CreateMediaUpload request;
        using (var stream = new System.IO.FileStream(@"test.docx",
            System.IO.FileMode.Open))
        {
            request = driveService.Files.Create(
                fileMetadata, stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            request.Fields = ""id, webViewLink, webContentLink, size";
            var x = request.Upload();
            Console.WriteLine(x);
        }
        var file = request.ResponseBody;

Afterwards, I am getting id of this file and trying to do:

  var downloadRequest = driveService.Files.Export(file.Id, "application/pdf");

which fails with error: "Export only supports Google Docs" Ofc! I suppose it hasn't yet become "Google DOC", however, this format is supported for conversion as mentioned here and here.

Ok, I've noticed if you go to the drive and open the file manually it will become google doc file and also will get new ID. The export on this ID will work just fine. However, doing something manually isn't acceptable approach for our needs. Tried another approach, you can use direct link with &export=pdf parameter to convert google doc file.

https://docs.google.com/document/d/FILE_ID/export?format=doc

But passing FILEID to that link doesn't work in this case(works with "DOC" file just fine) Tried doing something similiar to stackoverflow answer. No way.

So. Is there any way to trigger File to become Google DOC and wait till it converts? Is there any other way? Thanks in advance!

Upvotes: 0

Views: 3737

Answers (1)

Amarula
Amarula

Reputation: 162

Thanks to @bash.d I was able to convert from docx to pdf.

Actually one have to use v2 of API and its "Insert" method.

https://developers.google.com/drive/v2/reference/files/insert#examples

use the code from this link and specify

request.Convert = true;

after that I used

 var downloadRequest = driveService.Files.Export(file.Id, "application/pdf");

and voilà! It worked! Takes about 30 seconds to convert file in my case.

Upvotes: 2

Related Questions