Generating JPG's from office files (.doc .ppt etc) using PHP

Viewed 18306

I'm building an application where people can upload files and share them with other people. Part of what we are looking to do is allow people to preview the file on-line.

Is there a strait forward way to generate a jpgs for the first X amount of pages from a document? We could then place these jpgs in the web page allowing the user to preview.

I have looked at installing open office on the server but was hoping there was a php library somewhere that does the same job.

Can anybody help?

Cheers


Btw, doesnt have to be jpg, any image file would be fine (actually even pdf would be ok)

3 Answers

For a PHP-specific option you could use PHPWord - this library is written in PHP and provides classes to read from and write to different document file formats (including .doc and .docx), but it won't give you the ability to convert from the full range of Office files.

To convert any Office file on any platform you could use a file conversion API like Zamzar. It can convert from all Office formats (DOC / DOCX / PPT / PPTX / XLS / XLSX) into images (JPG, PNG, GIF etc) and PDF.

Code to call from PHP would be as follows (more info in the docs).

<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_KEY";
$sourceFilePath = "/tmp/my.doc"; // Or DOCX/PPT/PPTX/XLS/XLSX
$targetFormat = "jpg";

$sourceFile = curl_file_create($sourceFilePath);    
$postData = array(
  "source_file" => $sourceFile,
  "target_format" => $targetFormat
);

// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);

// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>
Related