使用PHP将excel转换为pdf

时间:2016-09-05 15:45:45

标签: php excel pdf laravel-5 phpexcel

我正在使用PHPExcel创建一个excel文件!我需要将其保存为.xlsx文件并拥有.pdf文件

使用PHPExcel,我的pdf以奇怪的格式出现,如下所示: Result

但我想要这样的东西(这是手动生成的,“另存为pdf”): What I Want

您知道将excel转换为pdf的简单方法吗?

$objReader = \PHPExcel_IOFactory::createReader("Excel2007");
$objPHPExcel = $objReader->load(Some_Path);
$objPHPExcel->setActiveSheetIndex(0);        


$objPHPExcel->getActiveSheet()
        ->setCellValue('B8', "testing");


//Write Excel 
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('testing.xlsx');

// Write PDF
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->save('testing.pdf');

1 个答案:

答案 0 :(得分:0)

如果使用PHP for Windows PC,请考虑Excel对象库COM interface。这是一个仅限Windows的扩展,通常在PC上安装PHP。

此方法允许您执行Excel VBA可以执行的任何操作,包括调用ExportAsFixedFormat方法输出PDF文件。请注意,此方法可以在WorkbookWorksheet个对象上运行(遵循预设/默认打印页面设置),甚至图表范围

// EXCEL APP OBJECT
$xlapp =  new COM("Excel.Application") or Die ("Did not instantiate Excel");

// WORKBOOK AND WORKSHEET OBJECTS
$wbk = $xlapp->Workbooks->Open("C:\\Path\\To\\Workbook.xlsx");    
$wks = $wbk->Worksheets(1);

// SET CELL VALUE
$wks->Range("B8")->Value = "testing";

// OUTPUT WORKSHEET TO PDF
$xlTypePDF = 0;
$xlQualityStandard = 0;

try {
    $wks->ExportAsFixedFormat($xlTypePDF, "C:\\Path\\To\\Output.pdf", $xlQualityStandard);

} catch(com_exception $e) {  
    echo $e->getMessage()."\n";
    exit;

}

// OPEN WORKBOOK TO SCREEN
$xlapp->Visible = true;

// END PROCESS / FREE RESOURCES
$xlapp = NULL;
unset($xlapp);