使用PHP将Excel转换为pdf [英] Converting excel to pdf using PHP
问题描述
我正在使用PHPExcel创建一个Excel文件!我需要将其另存为.xlsx文件,并拥有一个.pdf文件
I am using PHPExcel to create an excel file! I need to save it as .xlsx file and to have a .pdf file
使用PHPExcel,我的pdf会以一种奇怪的格式显示,如下所示: 结果
With PHPExcel my pdf appears in a strange format, like this: Result
但是我想要这样的东西(这是手动生成的,另存为pdf"): 我想要什么
But I want something like this (this was manually generated, "save as pdf"): What I Want
您知道将excel转换为pdf的简单方法吗?
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');
推荐答案
考虑一个 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);
这篇关于使用PHP将Excel转换为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!