Advertisement
tomasr78

Convert Word document to PDF, C# example

Jul 11th, 2014
1,553
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1. using (var client = new WebClient())
  2.             {                
  3.  
  4.                 Console.WriteLine("Please choose a Word document to convert to PDF. All conversion will be done at http://www.convertapi.com server!");
  5.  
  6.                 var openFileDialog = new OpenFileDialog { Filter = "Word document(*.doc;*.docx)|*.doc;*.docx"};
  7.                 if (openFileDialog.ShowDialog()!=DialogResult.OK) return;                              
  8.                 var fileToConvert = openFileDialog.FileName;
  9.                 Console.WriteLine("Converting the file {0} Please wait.", fileToConvert);
  10.                
  11.                 var data = new NameValueCollection();
  12.                 data.Add("OutputFormat","jpg");
  13.                 data.Add("OutputFileName", "MyFile"); //Optional
  14.  
  15.                 //!!!MANDATORY!!!
  16.                 data.Add("ApiKey", "YourApiKey"); //API Key must be set if you purchased membership with credits. Please login to your control panel to find out your API Key http://www.convertapi.com/prices
  17.                
  18.                 try
  19.                 {                    
  20.                     client.QueryString.Add(data);
  21.                     var response = client.UploadFile("http://do.convertapi.com/word2pdf", fileToConvert);                    
  22.                     var responseHeaders = client.ResponseHeaders;                    
  23.                     var path = Path.Combine(@"C:\", responseHeaders["OutputFileName"]);
  24.                     File.WriteAllBytes(path, response);
  25.                     Console.WriteLine("The conversion was successful! The word file {0} converted to PDF and saved at {1}", fileToConvert, path);
  26.                 }
  27.                 catch (WebException e)
  28.                 {
  29.                     Console.WriteLine("Exception Message :" + e.Message);
  30.                     if (e.Status == WebExceptionStatus.ProtocolError)
  31.                     {
  32.                         Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
  33.                         Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
  34.                     }
  35.  
  36.                 }
  37.  
  38.  
  39.             }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement