You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用FPDF添加PDF水印时遇PDF::setSourceFile()未定义错误求助

解决方法

问题根源

setSourceFile() 是FPDI(PDF导入工具库)的专属方法,不属于原生FPDF或其rotation扩展。你当前只引入了rotation.php,没有集成FPDI,所以会触发方法未定义的错误。

具体修复步骤

  1. 获取并引入FPDI库
    下载FPDI的核心文件(fpdi.php),和你的fpdf.php、rotation.php放在同一目录下。

  2. 调整rotation.php的继承关系
    打开rotation.php,找到类定义行:

    class PDF_Rotate extends FPDF {
    

    修改为:

    class PDF_Rotate extends FPDI {
    

    这样PDF_Rotate就继承了FPDI的所有方法,包括setSourceFile()。

  3. 完善PDF导入与水印添加逻辑
    你的原代码仅调用了setSourceFile(),但没有导入并渲染原PDF的页面,修改后的完整代码如下:

    <?php
    require('fpdf.php');
    require('fpdi.php');
    require('rotation.php');
    
    class PDF extends PDF_Rotate{
        function Header(){
            // 添加水印
            $this->SetFont('Arial','B',50);
            $this->SetTextColor(255,192,203);
            $this->RotatedText(35,190,'W a t e r m a r k   d e m o',45);
        }
        function RotatedText($x, $y, $txt, $angle){
            // 绕原点旋转文本
            $this->Rotate($angle,$x,$y);
            $this->Text($x,$y,$txt);
            $this->Rotate(0);
        }
    }
    
    $pdf = new PDF();
    $pages_count = $pdf->setSourceFile('teste.pdf'); 
    // 循环导入原PDF的每一页
    for ($page_num = 1; $page_num <= $pages_count; $page_num++) {
        $template_id = $pdf->importPage($page_num);
        $pdf->AddPage();
        // 渲染原PDF页面
        $pdf->useTemplate($template_id);
    }
    $pdf->Output();
    ?>
    

关键说明

  • FPDI负责导入现有PDF页面,rotation扩展负责实现文本旋转水印,两者结合才能完成需求。
  • 调用AddPage()时会自动触发Header()方法,所以水印会自动添加到每一页。

内容的提问来源于stack exchange,提问作者Antharaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:36:26