Advertisement
tomasr78

Convert Word document to PDF

Jul 11th, 2014
1,865
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.28 KB | None | 0 0
  1. <?php
  2. error_reporting(NULL);
  3. ini_set('display_errors', '0');
  4. function ParseHeader($header='')
  5. {
  6.     $resArr = array();
  7.     $headerArr = explode("\n",$header);
  8.     foreach ($headerArr as $key => $value) {
  9.         $tmpArr=explode(": ",$value);
  10.         if (count($tmpArr)<1) continue;
  11.         $resArr = array_merge($resArr, array($tmpArr[0] => count($tmpArr) < 2 ? "" : $tmpArr[1]));
  12.     }
  13.     return $resArr;
  14. }
  15.  
  16. function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message)
  17. {
  18.         try
  19.         {
  20.            
  21.             $rand=time();
  22.             $fileName = $rand."MyFile.pdf";
  23.              
  24.             $postdata =  array('OutputFileName' => 'MyFile.pdf', 'ApiKey' => $apiKey, 'file'=>"@".$fileToConvert);
  25.             $ch = curl_init("http://do.convertapi.com/word2pdf");
  26.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  27.             curl_setopt($ch, CURLOPT_HEADER, 1);
  28.             curl_setopt($ch, CURLOPT_POST, 1);
  29.             curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  30.             $result = curl_exec($ch);
  31.             $headers = curl_getinfo($ch);
  32.            
  33.             $header=ParseHeader(substr($result,0,$headers["header_size"]));
  34.             $body=substr($result, $headers["header_size"]);
  35.            
  36.             curl_close($ch);
  37.             if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 )
  38.             {
  39.                 // Check for Result = true
  40.                
  41.                 if (in_array('Result',array_keys($header)) ?  !$header['Result']=="True" : true)
  42.                 {
  43.                     $message = "Something went wrong with request, did not reach ConvertApi service.<br />";
  44.                     return false;
  45.                 }
  46.                 // Check content type
  47.                 if ($headers['content_type']<>"application/pdf")
  48.                 {
  49.                     $message = "Exception Message : returned content is not PDF file.<br />";
  50.                     return false;
  51.                 }
  52.                 $fp = fopen($pathToSaveOutputFile.$fileName, "wbx");
  53.                
  54.                 fwrite($fp, $body);
  55.  
  56.                 $message = "The conversion was successful! The word file $fileToConvert converted to PDF and saved at $pathToSaveOutputFile$fileName";
  57.                 return true;
  58.             }
  59.             else
  60.             {
  61.              $message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
  62.              return false;
  63.             }
  64.         }
  65.         catch (Exception $e)
  66.         {  
  67.             $message = "Exception Message :".$e.Message."</br>";
  68.             return false;
  69.         }
  70. }
  71. ?>
  72. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  73. <html xmlns="http://www.w3.org/1999/xhtml">
  74.     <head>
  75.         <title>
  76.             Conversion example of Word document to PDF using Rest API
  77.         </title>
  78.     </head>
  79. <body>
  80.     <div style="width: 600px; margin: auto;">
  81.         <h3>Conversion example of Word document to PDF using Rest API <a href="http://www.convertapi.com" target="_blanks">http://www.convertapi.com</a></h3>
  82.         <form method="post" action="" id="word2pdf_form" enctype="multipart/form-data">
  83.             Please choose Word document(docx or doc file) from your computer
  84.             <br />
  85.             <input type="file" name="FileUpload" id="FileUpload" style="width:600px;">
  86.             <br />
  87.             <br />
  88.             <a href="http://www.convertapi.com/prices" target="_blanks">Api Key(leave empty if you don't have one)</a>
  89.             <br />
  90.             <input name="txtApiKey" type="hidden" id="txtApiKey" value="" style="width:600px;">
  91.             <br />
  92.             <br />
  93.             <div style="text-align: center">
  94.                 <input type="submit" name="btnConvert" value="Convert" id="btnConvert">
  95.             </div>
  96.        
  97.         </form>
  98.         <br>
  99. <?php
  100.  
  101. if (isset($_FILES["FileUpload"]['name'])&&$_FILES['FileUpload']['size']>0&&$_FILES['FileUpload']['error']==0)
  102. {
  103.     $physicalPath = dirname(__FILE__)."/files/";
  104.    
  105.     if (!file_exists($physicalPath)) {
  106.             mkdir($physicalPath,0777);
  107.         }
  108.     $uploadedFile = $physicalPath.$_FILES["FileUpload"]['name'];
  109.    
  110.     $apiKey = $_REQUEST["txtApiKey"];
  111.    
  112.     if (!move_uploaded_file($_FILES["FileUpload"]["tmp_name"], $uploadedFile)) die("CANNOT MOVE {$_FILES['FileUpload']['name']}" . PHP_EOL);
  113.     $message = "";
  114.     chmod($uploadedFile,0755);
  115.     $result = CallToApi($uploadedFile, $physicalPath, $apiKey, &$message);
  116.     echo "<span id='lblStatus'".($result ? "" : "style='color:red'")." >" .$message."</span>";
  117. }
  118. else
  119. {
  120.     echo in_array("btnConvert", $_REQUEST) ? "<span id='lblStatus' style='color:Red;'>Please select Word document!</span>":"<span id='lblStatus'>Please select a Word document and click Convert button.</span>";
  121. }
  122. ?>
  123.    </div>
  124.  
  125. </body>
  126. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement