PHP向存储在数据库中的现有PDF添加徽标(MySQL)

时间:2018-12-03 08:20:47

标签: php pdf fpdf fpdi

我正在做一个基本系统,工作人员将上传带有一些说明的pdf文件,并将此数据存储在MySQL数据库中。

如果一切正常,管理员将查看此pdf文件并单击批准。

图像将被插入带有批准徽标的pdf文件中。

我使用fpdf和fpdi类来执行此操作,如果PDF文件存储在实际路径中,则设法做到这一点,如下代码所示。

const elements= (<HTMLCollection>document.getElementsByClassName('your_class_name_without_dot'));

console.log(elements)

但是,当我尝试使用$ pdf-> setSourceFile($ string)或其他实际文件(例如字符串(数据库)或URL中的PDF $ content)时,我无法做到这一点。

<?php

use setasign\Fpdi\Fpdi;

require_once('fpdf/fpdf.php');
require_once('fpdi2/src/autoload.php');

// initiate FPDI
$pdf = new Fpdi();
// add a page
$pdf->AddPage();
// set the source file
$pdf->setSourceFile('PdfDocument.pdf');
// import page 1
$tplIdx = $pdf->importPage(1);
// use the imported page and place it at position 10,10 with a width of 100 mm
$pdf->useTemplate($tplIdx, 10, 10, 100);

// now write some text above the imported page
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(255, 0, 0);
$pdf->SetXY(30, 30);
$pdf->Write(0, 'This is just a simple text');

$pdf->Output();

我的问题是如何从MySQL字符串导入PDF,以便由fpdf和fpdi或任何其他免费的PDF类进行编辑。

注意:到目前为止,我尝试使用stream_wrapper_register时没有任何运气。如在此链接 https://www.setasign.com/support/faq/miscellaneous/using-a-pdf-from-a-php-variable-instead-of-a-file/

请帮助我举一个简单的例子,因为我对PDF类不是很熟悉。

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为麻烦的根源在于:

$stream = fopen('data:text/plain,' . urlencode("http://localhost/pdf/getPDF.php?fid=2"), 'rb');

PHP的fopen函数返回文件指针,但没有提供所需的PDF文件名。

所以稍后致电

$pageCount = $pdf->setSourceFile($stream);

$ stream不是带有PDF文件名的字符串。

如果您的http://localhost/pdf/getPDF.php?fid=2 URL返回PDF的文件名,请尝试使用file_get_contents来获取该值,如下所示:

$pdf_file = file_get_contents('http://localhost/pdf/getPDF.php?fid=2');

然后致电

$pdf->setSourceFile($pdf_file);

答案 1 :(得分:0)

您不应使用其他HTTP请求来从数据库访问文件!

FPDI 2允许您通过StreamReader类从任何来源进行读取:

// use a resource
$fh = fopen('a/path/to/a.pdf', 'rb');
$pdf->setSourceFile(new StreamReader($fh));
// same as
$pdf->setSourceFile($fh);
// don't forget to call fclose($fh);

// use a path
$path = 'a/path/to/a.pdf';
$pdf->setSourceFile(StreamReader::createByFile($path));
// same as
$pdf->setSourceFile($path);

// use a string
$pdfString = '%%PDF-1.4...';
$pdf->setSourceFile(StreamReader::createByString($pdfString));

因此,请勿调用外部脚本,而应在数据库中查询PDF并将其通过,例如作为字符串。

PS:You cannot edit a PDF with FPDI