[PHP]自带的其他文档转PDF功能

363 阅读1分钟
<?php

    # doc、txt文件等
    function doc_to_pdf(){
        $doc = PUBLIC_PATH.'/uploads/1.doc';
        $pdf = PUBLIC_PATH.'/uploads/doc.pdf';
        try {
            if(!file_exists($doc)){
                return;
            }

            $word = new \COM("word.application") or die("Can't start Word!");
            $word->Visible=0;
            $word->Documents->Open($doc, false, false, false, "1", "1", true);

            $word->ActiveDocument->final = false;
            $word->ActiveDocument->Saved = true;
            $word->ActiveDocument->ExportAsFixedFormat(
                $pdf,
                17,                         // wdExportFormatPDF
                false,                      // open file after export
                0,                          // wdExportOptimizeForPrint
                3,                          // wdExportFromTo
                1,                          // begin page
                5,                          // end page
                7,                          // wdExportDocumentWithMarkup
                true,                       // IncludeDocProps
                true,                       // KeepIRM
                1                           // WdExportCreateBookmarks
            );
            $word->ActiveDocument->Close();
            $word->Quit();
        } catch (\Exception $e) {
            if (method_exists($word, "Quit")){
                $word->Quit();
            }
            return;
        }
    }

    function excel_to_pdf(){
        $xls = PUBLIC_PATH.'/uploads/1.xls';
        $pdf   = PUBLIC_PATH.'/uploads/excel.pdf';
        try {
            if(!file_exists($xls)){
                return;
            }
            $excel = new \COM("excel.application") or die("Unable to instantiate excel");
            $workbook = $excel->Workbooks->Open($xls, null, false, null, "1", "1", true);
            $workbook->ExportAsFixedFormat(0, $pdf);
            $workbook->Close();
            $excel->Quit();
        } catch (\Exception $e) {
            echo ("src:$xls catch exception:" . $e->__toString());
            if (method_exists($excel, "Quit")){
                $excel->Quit();
            }
            return;
        }
    }

    function ppt_to_pdf(){
        $ppt = PUBLIC_PATH.'/uploads/1.ppt';
        $pdf = PUBLIC_PATH.'/uploads/ppt.pdf';
        try {
            if(!file_exists($ppt)){
                return;
            }
            $ppt = new \COM("powerpoint.application") or die("Unable to instantiate Powerpoint");
            $presentation = $ppt->Presentations->Open($ppt, false, false, false);
            $presentation->SaveAs($pdf,32,1);
            $presentation->Close();
            $ppt->Quit();
        } catch (\Exception $e) {
            if (method_exists($ppt, "Quit")){
                $ppt->Quit();
            }
            return;
        }
    }