Categories
PHP

Word to PDF in PHP

Long time took me to find a nice way to convert DOC files to PDF from PHP, not any was enough good.

Finally I found a web service that is for free and you can use it from PHP.

livedocx

The steps to convert the file are really easy

  1. Sign in http://www.livedocx.com/ (is for free)
  2. No you can use the live demo of the site.
  3. All the files will be stored in the “box”

To use it in php is not so difficult either:

  • Download Zend Framework Minimal (18Mb unzipped!!!!!!)
  • Download and install the latest version ofphpLiveDocx (611Kb)
  • Configure it.
  • The script uploads the file twice, one in your server and another in phpLiveDocx (to convert it), later you need to wait a bit for the returning file.
  • The conversion works great and fast!
  • The uploaded file is not the “box”, better since then you can share the account for many things

Example usage in php

require_once dirname(__FILE__) . '/../../common.php';
require_once dirname(__FILE__) . '/../../Converter.php';

define('PATH_BASE', dirname(__FILE__) );
$inputFilename = PATH_BASE . DIRECTORY_SEPARATOR . 'your_word_file.doc';  // convert this file
$outputFormat  = 'pdf';                                           // into this format

$outputFilename = Converter::getFilename($inputFilename, $outputFormat);
printf('Converting %s to %s... ', basename($inputFilename), basename($outputFilename));
$convertedDocument = Converter::convert($inputFilename, $outputFormat);

if (false !== $convertedDocument) {
    file_put_contents($outputFilename, $convertedDocument);
    print("DONE.n");
} else {
    print("ERROR.n");
}

Convert example from wordsample2.doc to wordsample2.pdf

Hope you like this 😉