1

Im trying out the Convertapi in a Windows store App project, and i want to send a .docx file and get a pdf file in return, im trying to do a post but im not sure how its done, this is what i have so far, but its not working.

    private async Task GeneratePdfContract(string path) {
try {
    var data = new List < KeyValuePair < string, string >> {
            new KeyValuePair < string, string > ("Api", "5"),
                new KeyValuePair < string, string > ("ApiKey", "419595049"),
                new KeyValuePair < string, string > ("File", "" + stream2),

        };

    await PostKeyValueData(data);

} catch (Exception e) {

    Debug.WriteLine(e.Message);
}

}

private async Task PostKeyValueData(List < KeyValuePair < string, string >> values) {
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://do.convertapi.com/Word2Pdf", new FormUrlEncodedContent(values));
var responseString = await response.Content.ReadAsStringAsync();

}

How should i do my post to send a .docx file and get a .pdf file in return?

Edit:

private async Task GeneratePdfContract(string path)
    {
        try
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                using (var multipartFormDataContent = new MultipartFormDataContent())
                {
                    var values = new[]
        {
            new KeyValuePair<string, string>("ApiKey", "413595149")
        };

                    foreach (var keyValuePair in values)
                    {
                        multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
                    }

                    StorageFolder currentFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataDirectory);

                    StorageFile outputFile = await currentFolder.GetFileAsync("file.docx");

                    byte[] fileBytes = await outputFile.ToBytes();


                    //multipartFormDataContent.Add(new ByteArrayContent(FileIO.ReadBufferAsync(@"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');

                    multipartFormDataContent.Add(new ByteArrayContent(fileBytes));

                    const string requestUri = "http://do.convertapi.com/word2pdf";

                    var response = await client.PostAsync(requestUri, multipartFormDataContent);
                    if (response.IsSuccessStatusCode)
                    {
                        var responseHeaders = response.Headers;
                        var paths = responseHeaders.GetValues("OutputFileName").First();
                        var path2 = Path.Combine(@"C:\", paths);



                        StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"C:\Users\Thought\AppData\Local\Packages\xxxxx_apk0zz032bzya\LocalState\Data\");
                        await FileIO.WriteBytesAsync(sampleFile, await response.Content.ReadAsByteArrayAsync());


                    }
                    else
                    {
                        Debug.WriteLine("Status Code : {0}", response.StatusCode);
                        Debug.WriteLine("Status Description : {0}", response.ReasonPhrase);
                    }

                }
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
        }

    }

@Tomas tried to adapt your answer a bit since there doesn't seem to be a "File.ReadAllBytes" on windows store apps, im getting this response tho :\ enter image description here

1
  • I think you need to be using MultipartFormDataContent and not FormUrlEncodedContent. Check here and here for examples. For the File content (based on my Fiddling of that page request), the Content-Disposition needs to be form-data; name-"File"; filename="<filename>" (replace <filename>). Content-Type may need to be application/msword, not sure. Commented Oct 21, 2014 at 20:36

1 Answer 1

2

You can't pass file stream as string to HttpClient. Just use WebClient.UploadFile method which also support asynchronous uploads.

using (var client = new WebClient())
            {                

                var fileToConvert = "c:\file-to-convert.docx";


                var data = new NameValueCollection();                

                data.Add("ApiKey", "413595149"); 

                try
                {                    
                    client.QueryString.Add(data);
                    var response = client.UploadFile("http://do.convertapi.com/word2pdf", fileToConvert);                    
                    var responseHeaders = client.ResponseHeaders;                    
                    var path = Path.Combine(@"C:\", responseHeaders["OutputFileName"]);
                    File.WriteAllBytes(path, response);
                    Console.WriteLine("The conversion was successful! The word file {0} converted to PDF and saved at {1}", fileToConvert, path);
                }
                catch (WebException e)
                {
                    Console.WriteLine("Exception Message :" + e.Message);
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                        Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    }

                }


            }

The example using HttpClient()

    using (var client = new System.Net.Http.HttpClient())
    {
        using (var multipartFormDataContent = new MultipartFormDataContent())
        {
            var values = new[]
            {
                new KeyValuePair<string, string>("ApiKey", "YourApiKey")
            };

            foreach (var keyValuePair in values)
            {
                multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
            }

            multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(@"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');

            const string requestUri = "http://do.convertapi.com/word2pdf";

            var response = await client.PostAsync(requestUri, multipartFormDataContent);
            if (response.IsSuccessStatusCode)
            {
                var responseHeaders = response.Headers;
                var paths = responseHeaders.GetValues("OutputFileName").First();
                var path = Path.Combine(@"C:\", paths);
                File.WriteAllBytes(path, await response.Content.ReadAsByteArrayAsync());
            }
            else
            {
                Console.WriteLine("Status Code : {0}", response.StatusCode);
                Console.WriteLine("Status Description : {0}", response.ReasonPhrase);
            }

        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

im working in a Windows Store App, wich doesn't seem to have the WebClient, any chance for anwser with httpclient or some other alternative?
The answer updated with HttpClient.PostAsync example.
oh wait nevermind i see my mistake :) this is incomplete "multipartFormDataContent.Add(new ByteArrayContent(fileBytes)); "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.