Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel: "Impossible to read file" error Converting Excel to PDF (.xlsx to .pdf)

I have a xlsx with only one spreadsheet. I use PHPExcel to convert it to a pdf through the following code:

        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        require_once 'phpExcel/PHPExcel/IOFactory.php';
        require_once 'phpExcel/PHPExcel.php';

        $inputFileName = 'doc/ModUnico';
        $excel2 = PHPExcel_IOFactory::createReader('Excel2007');
        $excel2 = $excel2->load($inputFileName.'.xlsx');
        $excel2->setActiveSheetIndex(0);
        $excel2->getActiveSheet()->setCellValue('H5', '4');
        $objWriter = PHPExcel_IOFactory::createWriter($excel2, 'Excel2007');
        $objWriter->save($inputFileName.'_.xlsx');


        $objPHPexcel = PHPExcel_IOFactory::load($inputFileName.'_.xlsx');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment;filename="test.pdf"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPexcel, 'PDF');
        $objWriter->writeAllSheets();
        $objWriter->setPreCalculateFormulas(false);
        $objWriter->save('php://output');

The problem is that when i try to open the returned file i get the error message "Impossible to read file".

EIDT: Renderer added

        $rendererName = PHPExcel_Settings::PDF_RENDERER_MPDF;
        $rendererLibrary = 'mpdf.php';
        $rendererLibraryPath = dirname(__FILE__).'/MPDF57/' . $rendererLibrary;


        if (!PHPExcel_Settings::setPdfRenderer(
            $rendererName,
            $rendererLibraryPath
            )) {
                die(
                    'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
                    '<br />' .
                    'at the top of this script as appropriate for your directory structure'
                );
        }
like image 217
Emaborsa Avatar asked Nov 10 '22 10:11

Emaborsa


1 Answers

I think Mark is on to something. When I run into errors like this, I start at the top and work down. i.e. Is the intermediate xlsx file correct?

I would probably also write some test code with REALLY simple xls files, or csv files that uses the PHPExcel library, and you should figure out what's wrong while you try to get those to work. Same with the pdf renderer, I would try a different one (if one is available).

Joey

like image 134
Joey Novak Avatar answered Nov 14 '22 21:11

Joey Novak