FPDI/FPDF: Watermark and Print Multiple Pages

前端 未结 3 1021
你的背包
你的背包 2021-02-03 15:42

I modified this stack question: Applying watermarks on pdf files when users try to download the files but I encountered an error, though there was a comment that says on how to

3条回答
  •  醉酒成梦
    2021-02-03 16:14

    In case anyone wants to use FPDF AND create the pdf on the fly without having to load it from a file here's how I did it. You will instantiate your PDF object with this class instead of the FPDF class. This should be run AFTER the pdf is created in memory but BEFORE it is output:

    pages); $i++) {
                $this->page = $i;
                $this->ApplyWaterMark();
            }
        }
    
        private function ApplyWaterMark()
        {
            //Put the watermark
            $this->SetFont('Arial','B',60);
            $this->SetTextColor(255,192,203);
            $this->RotatedText(15,280,'D O N O T F I L E - S A M P L E ',50);
            $this->SetTextColor(0,0,0);
        }
    
        private function RotatedText($x, $y, $txt, $angle)
        {
            //Text rotated around its origin
            $this->rotate($angle,$x,$y);
            $this->Text($x,$y,$txt);
            $this->Rotate(0);
        }
    
        private function Rotate($angle,$x=-1,$y=-1)
        {
            if($x==-1)
                $x=$this->x;
            if($y==-1)
                $y=$this->y;
            if($this->angle!=0)
                $this->_out('Q');
            $this->angle=$angle;
            if($angle!=0)
            {
                $angle*=M_PI/180;
                $c=cos($angle);
                $s=sin($angle);
                $cx=$x*$this->k;
                $cy=($this->h-$y)*$this->k;
                $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',$c,$s,-$s,$c,$cx,$cy,-$cx,-$cy));
            }
        }
    
        function _endpage()
        {
            if($this->angle!=0)
            {
                $this->angle=0;
                $this->_out('Q');
            }
            parent::_endpage();
        }
    }
    ?>
    

    I had a class called Document that I put everything in for abstraction. Here is the output function from it. I created a class level variable called "applyWaterMark" to control whether or not the watermark is applied to the document.

      protected function OutputDocument() {
        if($this->applyWaterMark) {
          $this->pdf->ApplyWaterMarkToAllPages();
        }    
        $this->pdf->Output();
      }
    

提交回复
热议问题