如何将base64图像插入fpdf?

时间:2018-07-12 19:04:51

标签: php fpdf

我已经看到了各种各样的答案,但是无论出于什么原因,我似乎都无法让他们工作。

首先,我要从数据库中提取文件:

try {
    $getQuery = "SELECT * FROM firstForm WHERE id =:id";
    $statement = $db->prepare($getQuery);
    $statement->execute(array(':id' => 2));

    if($row = $statement->fetch()) {
        $fileName = $row['pic'];
    }
}

当我回显$ fileName时,它会产生“ data:image / png; base64 ...”

如何转换$ fileName,以便可以在fpdf中使用它,就像这样:

$pdf = new FPDF('P','in','A4'); // orientation (portrait), inches, ??
$pdf->SetMargins(0.5,0.5,0.5);  // l, t, rs

$pdf->AddPage();
$pdf->Cell(4,3,'', 1, 2, 'C'); // w, h, text, border width, ???, align
$pdf->Image($fileName);
$pdf->Output();

2 个答案:

答案 0 :(得分:0)

尽管如James所言,答案print BASE64 coded image into a FPDF document提供了一个很好的解决方案。您可以将以下代码另存为image.php,然后将该图像(设置为$_GET['id'])添加到pdf中:$pdf->Image('/image.php?id=2');。调用image.php之前,请确保检查数据库中是否存在该图像。

<?php
if ($_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']) { // Only allow requests from server.
    header($_SERVER["SERVER_PROTOCOL"] . "  791 The Internet shut down due to copyright restrictions", true, 791);
    die();
}

if (empty($_GET['id'])) {
    die('Handle this.');
}

// get your $db object in here.
$getQuery = "SELECT * FROM firstForm WHERE id =:id";
$statement = $db->prepare($getQuery);
$statement->execute(array(':id' => 2));

if ($row = $statement->fetch()) {
    $data = $row['pic'];
} else {
    // This shouldn't happening, you should be checking whether firstForm with the id you're calling the image for exists.
}

$exploded = explode(';', $data);
$mimetype = substr($exploded[0], 5);
$data = explode(',', $exploded[1])[1];

header('Content-type: ' . $mimetype);
echo base64_decode($data);

您创建的pdf文件如下所示:

$pdf = new FPDF('P','in','A4'); // orientation (portrait), inches, ??
$pdf->SetMargins(0.5,0.5,0.5);  // l, t, rs

$pdf->AddPage();
$pdf->Cell(4,3,'', 1, 2, 'C'); // w, h, text, border width, ???, allign
$pdf->Image('/image.php?id=2');
$pdf->Output();

答案 1 :(得分:0)

所以,我知道了。答案就在此SO答案print BASE64 coded image into a FPDF document中,并且可以正常工作。

问题在于图像如何存储在数据库中。无论出于何种原因,我都将它存储为BLOB。

感谢您尝试@Nielles。