【问题标题】:Error embedding pdf using fpdi in CodeIgniter 3在 CodeIgniter 3 中使用 fpdi 嵌入 pdf 时出错
【发布时间】:2021-03-13 16:59:31
【问题描述】:

提前谢谢...

我正在尝试使用 fpdi 和 tcpdf 库在 CodeIgniter 中使用以下代码生成 pdf...

<?php
use setasign\Fpdi;

require_once('tcpdf/tcpdf.php');
require_once('fpdi2/autoload.php');

class Pdf extends Fpdi\Tcpdf\Fpdi
{
    /**
     * "Remembers" the template id of the imported page
     */
    protected $logo;

    /**
     * Draw an imported PDF logo on every page
     */
    function Header()
    {
        if ($this->logo === null) {
            $this->setSourceFile(base_url().'assets/pdf/logo.pdf'); //Will work if these 3 lines are commented
            $this->logo = $this->importPage(1);                     //Will work if these 3 lines are commented
        }
        $size = $this->useImportedPage($this->logo, 130, 5, 60);    //Will work if these 3 lines are commented

        $this->SetFont('freesans', 'B', 20);
        $this->SetTextColor(0);
        $this->SetXY(PDF_MARGIN_LEFT, 5);
        $this->Cell(0, 30, 'TCPDF and FPDI');
    }
}

// initiate PDF
$pdf = new Pdf();
$pdf->SetMargins(PDF_MARGIN_LEFT, 40, PDF_MARGIN_RIGHT);
$pdf->SetAutoPageBreak(true, 40);

// add a page
$pdf->AddPage();

$pdf->Write(5, "hello world");

$pdf->Output('generated.pdf', 'I');

?>

如果我注释我在内联 cmets 中提到的行,它会运行并生成 pdf,但会生成错误:

类型:InvalidArgumentException 消息:给定流不可搜索!

当我取消注释这些行时。 该代码在我的本地服务器中运行在 codeigniter 之外。 我能够将 pdf 嵌入到另一个视图中,因此 pdf 不是问题,也不是从我的资产文件夹访问 pdf 的限制。 当我尝试加载外部字体时也会出现同样的问题。 控制器以这种方式调用视图...

class Projects extends CI_Controller{
        public function fpdi(){
            $this->load->view('projects/fpdi');
        }
}

非常感谢! (请注意,这是对问题的过度简化,我没有在视图中加载库,这只是为了使问题尽可能简洁以进行演示) edit-UPDATE 用 fpdf 尝试了同样的事情,但我仍然得到同样的错误“Given stream is not seekable”。

更新 2!感谢 Jan Slabon 的建议,我解决了这个问题,用 CodeIgniter 常量 FCPATH 替换了 base_url() 助手,因此路径是相对的,而不是 URL。显然这是 fopen 正常运行所必需的,fpdi 库使用它。

我不知道更多,我觉得这是一个不优雅的解决方案,但它现在有效!如果有人有更多信息,将不胜感激。

【问题讨论】:

  • 函数“base_url()”似乎返回了一个根本无法搜索的 URL。您应该使用本地路径而不是 URL。
  • @JanSlabon 如何在视图中使用本地路径?我做了一个小实验,我加载了一个图像,当源是本地的时它不会加载,但是当我使用 base_url() 时它会加载。嵌入的 pdf 也会发生同样的情况。谢谢!

标签: php codeigniter fpdi


【解决方案1】:

将源代码从 base_url() 更改为相对路径 FCPATH。 (问题底部有更多信息。)

【讨论】:

  • 这不是关于绝对路径或相对路径的问题,而是关于 URL 和文件的简单本地路径之间的区别。
  • 谢谢!当文件源是外部还是本地时,它是否与 fopen 的工作方式有关?
  • 没错!有关内置协议的概述,请参阅here,这些流需要为seekable 以进行 PDF 解析。
猜你喜欢
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多