I have an excel template the I am filling with PhpSpreadsheet, which works flawlessly. However, when I try to then save it as a pdf, the scaling is wrong and the content does not fit on the page. I have tried using Tcpdf, Mpdf, and Dompdf, all with similar results. Mpdf has given the closest output so far, however the scaling is still incorrect.
I have tried setting the margins (that seems to have no effect), as well as setting FitToPage, FitToWidth and FitToHeight to true.
Any ideas on what how to fix it? Ideally, I would like to use Tcpdf, as I am using it for other purposes.
Here is the code I’m using:
// XLSX
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
$spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load(THIS_LIB_PATH_UP.'templates/1/rent2.xlsx');
$sheet = $spreadsheet->getActiveSheet();
$sheet->getPageMargins()
->setLeft(0)
->setRight(0)
->setTop(0)
->setBottom(0)
->setHeader(0)
->setFooter(0);
$sheet->getPageSetup()->setFitToWidth(1);
$sheet->getPageSetup()->setFitToHeight(1);
$sheet->getPageSetup()->setPaperSize(PhpOfficePhpSpreadsheetWorksheetPageSetup::PAPERSIZE_A4);
$sheet->getPageSetup()->setFitToPage(true);
// Date
$sheet->setCellValue('F4', date('d-m-Y'));
// Receipt Number
$sheet->setCellValue('F6', 'Receipt No. '.rand(0,100));
// FROM
$sheet->setCellValue('B10', 'Owner');
$sheet->setCellValue('B11', 'The');
$sheet->setCellValue('B12', 'Address');
$sheet->setCellValue('B13', 'Mobile');
$sheet->setCellValue('B14', '[email protected]');
// TO
$sheet->setCellValue('D10', 'Tenant');
$sheet->setCellValue('D11', 'Address');
$sheet->setCellValue('D12', '[email protected]');
$sheet->setCellValue('D13', 'Mobile');
// Description / Total
$sheet->setCellValue('B20', "Rent");
$sheet->setCellValue('F20', rand(0,500));
// Payment Method
$sheet->setCellValue('C34', 'Bank Transfer');
$writer = new Xlsx($spreadsheet);
$filename = THIS_LIB_PATH_UP.'templates/1/'.date('Y-m-d_H-i-s');
$writer->save($filename.'.xlsx');
// Open the xlsx file for pdf export
$writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, 'Tcpdf');
$writer->save($filename.'.pdf');
echo 'Done';```
[The excel template][1]
[Excel directly exported to PDF (Expected)][2]
[TcPDF output][3]
[DomPDF Output][4]
[Mpdf Output][5]
[1]: https://i.stack.imgur.com/YBL8z.png
[2]: https://i.stack.imgur.com/xVl0X.png
[3]: https://i.stack.imgur.com/6jDIi.png
[4]: https://i.stack.imgur.com/y1bDb.png
[5]: https://i.stack.imgur.com/jCLPq.png
Any help would be greatly appreciated, thanks!