Automatische Größenanpassung von Bildern mit TCPDFAuto-fit images onto current page using TCPDF

Recently I had to fit images onto the current page of a dynamically generated PDF document using the functionality provided by the (superb) TCPDF toolkit.

Due to the fact that I had to include HTML content in the PDFs I was bound to use the writeHTML function. The HTML content was basically structured using plain old <div> containers, that again were seperated into

  1. title
  2. text and
  3. image

sections. The idea was to dynamically add the title and the text content and use the remaining space to auto-fit the image onto the current page, thus not causing a page-break.

Using the functions provided by TCPDF, my idea was to basically calculate the current Y-offset after including the PDF-header, title and text sections and calculate the optimal image height based on the beginning of the footer section.

The following code snippets presents a working prototype. Hereby, $pdf is an instance of TCPDF and the constant MY_PDF_FOOTER_YOFFSET refers to the custom value of the footer height (represented by a negative y-offset).

$pageDimensions = $pdf->getPageDimensions();
$yOffset = ceil($pdf->GetY());
$beginFooter = floor($pageDimensions['hk'] + MY_PDF_FOOTER_YOFFSET - 15);
$maxImgHeight = floor($beginFooter - $yOffset);

In case you are wondering about the -15 in the calculation of the beginning of the footer area – I was using an additional image description section right below the image, with a height of (around) 15mm.

Concluding, this functionality can be easily put into a separate function to calculate the optimal (auto-fitting) image size for your (dynamically) generated PDF documents.

2 thoughts on “Automatische Größenanpassung von Bildern mit TCPDFAuto-fit images onto current page using TCPDF

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.