<?php
/**
* 文件类型处理
*/
namespace modules\Sms\controllers;
use modules\Sms\common\SmssController;
use app\models\Attachment;
class RsController extends SmssController
{
/**
* @param $fileid
* @return string
* @throws \Exception
* @example 'uploads/rs/2018/0629/9.pdf';
*/
public function actionIndex()
{
try {
$fileid = 2658502;
$info = $this->fileInfo($fileid);
//处理路径
$filepath = substr($info['filepath'], strpos($info['filepath'], 'uploads'));
if (!$filepath) {
throw new \Exception('路径有误');
}
if ('pdf' == $info['fileext']) {
return $this->renderPartial('index', ['dir' => $filepath]);
}
//if exists
$pdfdir = preg_replace('/\.[^\.]+$/', '.pdf', $filepath);
$alldir = '/home/save/web/mis/' . $pdfdir;
if (file_exists($alldir)) {
return $this->renderPartial('index', ['dir' => $pdfdir]);
}
$res = $this->changeType($filepath);
if (!$res) {
throw new \Exception($res);
}
return $this->renderPartial('index', ['dir' => $res]);
} catch (\Exception $e) {
$this->error($e->getMessage());
}
}
/**
* @param $dir 需被转换类型的文件路径
* @throws \Exception
*/
protected function changeType($dir)
{
try {
$pdir = pathinfo($dir);
if (!$pdir['extension']) {
throw new \Exception('错误的文件路径');
}
exec('source /etc/profile');
$cmd = '/home/java/bin/java -jar /home/save/web/mis/uploads/jodconverter/lib/jodconverter-cli-2.2.2.jar /home/save/web/mis/' . $dir . ' /home/save/web/mis/' . $pdir['dirname'] . '/' . $pdir['filename'] . '.pdf';
exec($cmd, $output, $return_var);
if (0 == $return_var) {
return $dir = $pdir['dirname'] . '/' . $pdir['filename'] . '.pdf';
}
throw new \Exception('转换失败');
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}
/**
* 获取附件信息
* @param $fileid
*/
protected function fileInfo($fileid)
{
if (!$fileid || !is_numeric($fileid)) {
throw new \Exception('参数错误');
}
$attachment_model = new Attachment();
$info = $attachment_model->getOne('id=:id', [':id' => $fileid]);
if (!$info) {
throw new \Exception('未查询到简历信息');
}
return $info;
}
}
二,模板文件
<!DOCTYPE html>
<html style="height: 100%">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<iframe src="<?php echo Yii::$app->urlManager->createUrl('/pdf/web/viewer.html');?>?file=../../<?=$dir;?>" style="height: 100%;width: 100%"></iframe>
</body>
</html>
三,将pdf.js文件夹中所需要的两个文件夹拷贝到web可访问的目录