本文主要是介绍通过phpoffice将word与excel文件转成PDF文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.首先需要对应的库
composer require phpoffice/phpword
composer require phpoffice/phpspreadsheet
composer require mpdf/mpdf
2.相关代码如下
<?phpnamespace common;use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpSpreadsheet\IOFactory as SpreadIoFactory;
use PhpOffice\PhpPresentation\IOFactory as PowerpointIoFactory;
use common\PDF;/*** 提供Office管理服务* @name Office.php* @package jypp* @category model* @link http://www.chanekeji.com* @author mengchen* @version 1.0* @copyright CHANGE INC* @since 2023-02-15*/
class Office
{ /*** word转pdf* @param string $wordPath * @param string $fileName*/public function wordToPdf($wordPath = '',$fileName = 'output'){ // 设置具体存放路径$basePath = sprintf('%spublic/upload/pdf/%s',ROOT_PATH,date('Ymd'));$path = sprintf('%s/%s.pdf',$basePath,$fileName);if (!file_exists($basePath)) {mkdir($basePath, 0755, true); //创建目录}// 创建一个新的 PHPWord 实例$phpWord = new PhpWord();Settings::setPdfRendererPath(sprintf('%svendor/mpdf/mpdf',ROOT_PATH));//设置转换pdf的类库名(DomPDF、MPDF、TCPDF)需要下载对应的类库Settings::setPdfRendererName('MPDF');// 从 Word 文档中加载内容$wordReader = IOFactory::createReader('Word2007');$phpWord = $wordReader->load($wordPath);// 用 PHPWord 创建 PDF 文件$xmlWriter = IOFactory::createWriter($phpWord, 'PDF');$xmlWriter->save($path);if(file_exists($path)){$pdf = new PDF();$pngs = $pdf->pdfToPng($path);if(count($pngs) > 0){unlink($path);return $pngs;}return [];}else{return [];}}/*** excel转pdf* @param string $wordPath * @param string $fileName*/public function excelToPdf($excelPath = '',$fileName = 'output'){ // 设置具体存放路径$basePath = sprintf('%spublic/upload/pdf/%s',ROOT_PATH,date('Ymd'));$path = sprintf('%s/%s.pdf',$basePath,$fileName);if (!file_exists($basePath)) {mkdir($basePath, 0755, true); //创建目录}/*第一步:打开excel文件*/$Excelreader = SpreadIoFactory::createReaderForFile($excelPath);$ExcelObj= $Excelreader ->load($excelPath);//打开后的excel对象/*第二步:另存为pdf文件*/$PDFWriter = SpreadIoFactory::createWriter($ExcelObj,'Mpdf');$PDFWriter ->save($path);if(file_exists($path)){$pdf = new PDF();$pngs = $pdf->pdfToPng($path);if(count($pngs) > 0){unlink($path);return $pngs;}return [];}else{return [];}}
}
这篇关于通过phpoffice将word与excel文件转成PDF文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!