MPDF full page background

后端 未结 3 1588
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 16:32

I spent way too much time on this and I can\'t figure out a good 21th century solution.

Simply I have to generate a business card in PDF with a background image, but MPD

3条回答
  •  情话喂你
    2021-02-02 16:44

    In case anyone else needs a background-cover in mPDF and is not helped by background-image-resize, which breaks as soon as it is wrapped by a floated element. Floated elements are often necessary within mPdf because of the abscence of css compliance. Here is a more robust solution for a circled image, with bg-cover simulated.

    Get image orientation

    function getImageOrientation(string $imgPath){
    
      list($imgWidth,$imgHeight) = getimagesize($imgPath);
    
      $aspectRatio = $imgWidth / $imgHeight;
    
      if($aspectRatio >= 1){
          return array('landscape',$imgWidth,$imgHeight,$aspectRatio);
      }else{
          return array('portrait',$imgWidth,$imgHeight,$aspectRatio);
      }
    

    }

    Set own properties to simulate background-cover

    public static function returnCircledImage($imgPath, int $size){
    
        list($orientation,$imgWidth,$imgHeight, $aspectRatio) = getImageOrientation($imgPath);
    
        if($orientation == 'landscape'){
            $backgroundSize = 'auto 100%'; //fit height, keep aspect ratio
            $calculatedWidth = floor($size * $aspectRatio);
            $calculatedHeight = $size;
    
            //position center manually
            $dx = -floor(($calculatedWidth - $calculatedHeight) / 2);
            $dy = 0;
        }else{
            $backgroundSize = '100% auto'; //fit width, keep aspect ratio
            $calculatedWidth = $size;
            $calculatedHeight = floor($size * $aspectRatio);
    
            //position center manually
            $dx = 0;
            $dy = -floor(($calculatedHeight - $calculatedWidth) / 2);
        }
    
        return sprintf('
    
            
    ', $backgroundSize, $dx, $dy, $size, $size, $imgPath ); }

提交回复
热议问题