且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP将Excel转换为pdf

更新时间:2023-10-22 13:27:34

考虑一个 COM界面到Excel对象库(如果使用Windows PC的PHP).这是仅Windows的扩展,通常随PC一起安装PHP.

Consider a COM interface to the Excel object library if using PHP for Windows PC. This is a Windows-only extension and usually ships with PHP installation on PCs.

这种方法实际上使您可以执行Excel VBA可以执行的任何操作,包括调用ExportAsFixedFormat方法以输出PDF文件.请注意,该方法可以在工作簿工作表对象(遵守预设/默认打印页面设置),甚至图表范围.

This approach allows you to do practically anything Excel VBA can do including calling the ExportAsFixedFormat method to output PDF files. Do note this method can be run on Workbook or Worksheet objects (adhering to preset/default print page settings), even Chart and Range.

// 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);