Converting excel to pdf using PHP

依然范特西╮ 提交于 2020-03-11 14:52:33

问题


I am using PHPExcel to create an excel file! I need to save it as .xlsx file and to have a .pdf file

With PHPExcel my pdf appears in a strange format, like this: Result

But I want something like this (this was manually generated, "save as pdf"): What I Want

Do you know a simple way to convert the excel to 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:


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.

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


来源:https://stackoverflow.com/questions/39333973/converting-excel-to-pdf-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!