Search code examples
c#convertapi

ConvertAPI - PDF to PPT in C#


We were upgrading to the new logic specified by ConvertAPI. But the framework used by us is 4 because of which System.Net.Http(HttpResponseMessage, HttpClient ,MultipartFormDataContent ,StreamContent ,StringContent) classes are not being found. Even added System.Net.Http reference. But still the same error persists. Can someone suggest some workaround for this? How to use ConvertApi in C# for .Net Framework 4?


Solution

  • Just use WebClient instead of HttpClient for quick file upload. To run the demo below you will need to replace file paths and set your secret instead of xxxxx in endpoint url. Also we should set accept:application/octet-stream header to get response as data stream instead of json.

    class Program
        {
            static void Main(string[] args)
            {            
                const string fileToConvert = @"C:\Projects\_temp\test1.docx";
                const string fileToSave = @"C:\Projects\_temp\test1.pdf";            
    
                try
                {
                    using (var client = new WebClient())
                    {
                        client.Headers.Add("accept", "application/octet-stream");
                        var resultFile = client.UploadFile(new Uri("https://v2.convertapi.com/docx/to/pdf?Secret=xxxxx"), fileToConvert); 
                        File.WriteAllBytes(fileToSave, resultFile );
                        Console.WriteLine("File converted successfully");
                    }
                }
                catch (WebException e)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                    Console.WriteLine("Body : {0}", new StreamReader(e.Response.GetResponseStream()).ReadToEnd());
                }
    
                Console.ReadLine();
            }
        }