Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matteusbarbosa/028e44e67865d3e2e2e3664fa709d05d to your computer and use it in GitHub Desktop.
Save matteusbarbosa/028e44e67865d3e2e2e3664fa709d05d to your computer and use it in GitHub Desktop.
Scale to fit and centre-align an image with FPDF
<?php
/* Caveat: I'm not a PHP programmer, so this may or may
* not be the most idiomatic code...
*
* FPDF is a free PHP library for creating PDFs:
* http://www.fpdf.org/
*/
require("fpdf.php");
class PDF extends FPDF {
const DPI = 96;
const MM_IN_INCH = 25.4;
const A4_HEIGHT = 297;
const A4_WIDTH = 210;
// tweak these values (in pixels)
const MAX_WIDTH = 800;
const MAX_HEIGHT = 500;
function pixelsToMM($val) {
return $val * self::MM_IN_INCH / self::DPI;
}
function resizeToFit($imgFilename) {
list($width, $height) = getimagesize($imgFilename);
$widthScale = self::MAX_WIDTH / $width;
$heightScale = self::MAX_HEIGHT / $height;
$scale = min($widthScale, $heightScale);
return array(
round($this->pixelsToMM($scale * $width)),
round($this->pixelsToMM($scale * $height))
);
}
function centreImage($img) {
list($width, $height) = $this->resizeToFit($img);
// you will probably want to swap the width/height
// around depending on the page's orientation
$this->Image(
$img, (self::A4_HEIGHT - $width) / 2,
(self::A4_WIDTH - $height) / 2,
$width,
$height
);
}
}
// usage:
$pdf = new PDF();
$pdf->AddPage("L");
$pdf->centreImage("path/to/my/image.jpg");
$pdf->Output();
?>
@matteusbarbosa
Copy link
Author

matteusbarbosa commented Apr 25, 2021

Fix:
#Width must be the second parameter provided to ->Image()
#follow docs: http://www.fpdf.org/en/doc/image.htm

    function centerImage($img, $vertical = false) {
        list($width, $height) = $this->resizeToFit($img);

        // you will probably want to swap the width/height
        // around depending on the page's orientation
        $this->Image(
            $img, (self::A4_WIDTH - $width) / 2,
            $vertical ? (self::A4_HEIGHT - $height) / 2 : null,
            $width,
            $height
        );
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment