skip to Main Content

I need to fill the existing Excel sheet regularly and export it to PDF. But I can’t do it so that the content fits the page.

$spreadsheet = IOFactory::load(Storage::path('Time&Attendance Template.xltx'));
$sheet = $spreadsheet->getActiveSheet();
$pdfWriter = new Tcpdf($spreadsheet);

$sheet->getCell('A1')->setValue(Str::random());
$pdfWriter->setPaperSize(PageSetup::PAPERSIZE_A4);
$pdfWriter->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
$pdfWriter->save($file = Storage::path('test.pdf'));

Result:

enter image description here

The same file in Excel online without any scaling settings fits on one PDF page:

enter image description here

PS. I tried mpdf and dompdf generators. They get lines of fonts so wrong, not close enough to the original for me.

Also I don’t get why vertical align doesn’t work. TCPDF seems to be ignoring vertical align of the cell.

2

Answers


    1. Manually adjust cell and font sizes:

      $spreadsheet->getActiveSheet()->getColumnDimension(‘A’)->setWidth(10);

    2. Wrap text in cells:

      $spreadsheet->getActiveSheet()->getDefaultStyle()->getAlignment()->setWrapText(true);

    This should solve your problem

    Login or Signup to reply.
  1. You need to work on three things to fit the content into a single page:

    1. Setup the Print Area
    2. Scale the Content/Sheet
    3. Adjust Margins and Orientation

    You need to include this line which allows you to export the spreadsheet to a PDF using the Mpdf engine

    use PhpOfficePhpSpreadsheetWriterPdfMpdf as PdfWriter;
    

    Here is the updated code:

    $spreadsheet = IOFactory::load(Storage::path('Time&Attendance Template.xltx'));
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->getCell('A1')->setValue(Str::random());
    
    // Set the print area
    $sheet->getPageSetup()->setPrintArea('A1:Z50'); // Adjust this range as needed
    
    // Fit to one page
    $sheet->getPageSetup()->setFitToWidth(1);
    $sheet->getPageSetup()->setFitToHeight(1);
    
    // Set paper size and orientation
    $sheet->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4);
    $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
    
    // Set margins if needed
    $sheet->getPageMargins()->setTop(0.5);
    $sheet->getPageMargins()->setRight(0.5);
    $sheet->getPageMargins()->setLeft(0.5);
    $sheet->getPageMargins()->setBottom(0.5);
    
    $pdfWriter = new PdfWriter($spreadsheet);
    $pdfWriter->save($file = Storage::path('test.pdf'));
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search