In order to convert DOCX file to PDF file directly, LIBRE OFFICE should be installed in your system.
LibreOffice is an OpenOffice's successor that allows command line conversion using the LibreOffice conversion engine. The advantage of LibreOffice is that it preserves the formatting like I wanted and generally worked great.
Here is the ctp:
<?php
echo $this->Form->create('User', array('url'=>array('controller'=>'users', 'action'=>'convertpdf'),'enctype'=>'multipart/form-data', 'inputDefaults' => array('label' => false,'div' => false))) ;
echo $this->Form->input('user_file',array('type'=>'file'));
echo $this->Form->submit('Submit',array('class'=>'btnNew'));
?>
Here is the code:
public function convertpdf(){
if ($this->request->is('post')) {
if ($this->request->data['User']['user_file']!='' && is_array($this->request->data['User']['user_file'])) {
$imgData = array();
$imgData['file'] = $this->request->data['User']['user_file'];
$imgData['name']=$this->data['User']['user_file']['name'];
$filepath = WWW_ROOT . 'file/temp/';
move_uploaded_file($imgData['file']['tmp_name'],$filepath.$imgData['name']);
$result = shell_exec('export HOME='.$filepath.' && soffice --headless --convert-to pdf --outdir '.$filepath.' '.$filepath.$imgData['name']);
print_r($result);
unlink($filepath.$imgData['name']);
die;
}
}
}
When user selects a file and submit the request firstly we move the file to a folder (here folder is file/temp). After that i have used shell_exec() which executes the command via shell and converts the DOCX file to pdf.
The command line that converts file is this:
'export HOME='.$filepath.' && soffice --headless --convert-to pdf --outdir '.$filepath.' '.$filepath.$imgData['name']
After converting the file i have deleted the DOCX file from the folder.
1 Comment(s)