Failed to Display PDF BLOB and write text watermark using FPDF - php

I am using FPDF/FPDI to merge a PDF from database with an image as a header of the PDF. Searching for solution but no solution found yet so I post it here.
Here is my viewpdf.php code:
<?php
session_start();
require"../system/sistem.php";
dbConnect();
//take data gambar
$result13 = mysqli_query($dbconn,"SELECT * FROM gambar WHERE id_gambar=".$_SESSION['id_gambar']."" ) or error( mysqli_error() );
$show13=mysqli_fetch_assoc($result13);
$id_gambar = $show13['id_gambar'];
$tipe_gambar = $show13['tipe_gambar'];
$ukuran_gambar = $show13['ukuran_gambar'];
$gambar = base64_decode($show13['gambar']);
$nama_gambar = $show13['nama_gambar'];
use setasign\Fpdi\Fpdi;
require('rotation.php');
require_once('src/autoload.php');
class PDF extends PDF_Rotate
{
// Page footer
function Footer()
{
// Position at 1.5 cm from bottom
$this->SetY(-15);
}
function RotatedText($x, $y, $txt, $angle)
{
//Text rotated around its origin
$this->Rotate($angle,$x,$y);
$this->Text($x,$y,$txt);
$this->Rotate(0);
}
}
//echo $gambar;
$pdf=new PDF();
$pdf = new FPDI();
$pdf->AddPage();
$pdf->SetFont('Arial','',12);
//$pdf->setSourceFile('document.pdf');
$pdf->setSourceFile('$gambar');
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('Arial','I',8);
$pdf->SetTextColor(25,192,203);
$pdf->SetY(264);
$pdf->Write(10,'Approved by YONATAN R.CHRISTIAN','http://athena.wgo-nigeria.com/');
$pdf->Output();
?>
It doesn't load the PDF from the database. and can't see text watermark.
This is view error:
Warning: fopen($gambar): failed to open stream: No such file or
directory in
C:\xampp\htdocs\approval\blob\src\PdfParser\StreamReader.php on line
43
Fatal error: Uncaught InvalidArgumentException: No stream given. in
C:\xampp\htdocs\approval\blob\src\PdfParser\StreamReader.php:105 Stack
trace: #0
C:\xampp\htdocs\approval\blob\src\PdfParser\StreamReader.php(44):
setasign\Fpdi\PdfParser\StreamReader->__construct(false, true) #1
C:\xampp\htdocs\approval\blob\src\FpdiTrait.php(172):
setasign\Fpdi\PdfParser\StreamReader::createByFile('$gambar') #2
C:\xampp\htdocs\approval\blob\src\FpdiTrait.php(211):
setasign\Fpdi\Fpdi->getPdfReaderId('$gambar') #3
C:\xampp\htdocs\approval\blob\watermark.php(50):
setasign\Fpdi\Fpdi->setSourceFile('$gambar') #4 {main} thrown in
C:\xampp\htdocs\approval\blob\src\PdfParser\StreamReader.php on line
105

Related

Why isn't it possible for Imagick class to convert pdf files to image files?

I would like to convert a pdf file to images in PHP.
I have got some exception like this:
Fatal error: Uncaught ImagickException: UnableToOpenBlob './sample.pdf': No such file or directory # error/blob.c/OpenBlob/3533 in D:\Task\Clients\James\toImage\toImage.php:4 Stack trace: #0 D:\Task\Clients\James\toImage\toImage.php(4): Imagick->readImage('./sample.pdf') #1 {main} thrown in D:\Task\Clients\James\toImage\toImage.php on line 4
I wrote some code like as follows.
<?php
$pdf_url = ('./sample.pdf');
$imagick = new Imagick();
$imagick->readImage($pdf_url);
$imagick->resizeImage( 200, 200, imagick::FILTER_LANCZOS, 0);
$imagick->setImageFormat( "png" );
$imagick->writeImage('pdfAsImage.png');
Please help me!
Here is the code I have ever used before.
Use the full path to the image, for example:
$image = new Imagick($_SERVER['DOCUMENT_ROOT'] . '/pdfs/sample.pdf');
It should work like a charm!!!

php page not loading after use

I have a problem by including a pdf merge system
I have tried a lot of code from git, but nothing works.
Now I have seen that if I comment out the lines with the use:
than the page can load if the use lines are in the code the page will not load.
if (isset($_POST["merge"]))
{
//use setasign\Fpdi;
//use setasign\fpdf;
require_once '../buchhaltung/vendor/autoload.php';
require_once '../buchhaltung/vendor/setasign/fpdf/fpdf.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(2);
date_default_timezone_set('UTC');
$start = microtime(true);
$pdf = new Fpdi\Fpdi();
//$pdf = new Fpdi\TcpdfFpdi('L', 'mm', 'A3');
if ($pdf instanceof \TCPDF) {
$pdf->SetProtection(['print'], '', 'owner');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
}
$files = [
' $_SESSION["filePath0"]',
' $_SESSION["filePath1"]',
];
foreach ($files as $file) {
$pageCount = $pdf->setSourceFile($file);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$pdf->AddPage();
$pageId = $pdf->importPage($pageNo, '/MediaBox');
//$pageId = $pdf->importPage($pageNo, Fpdi\PdfReader\PageBoundaries::ART_BOX);
$s = $pdf->useTemplate($pageId, 10, 10, 200);
}
}
$file = uniqid().'.pdf';
$pdf->Output('I', 'simple.pdf');
//$pdf->Output('output/'.$file, 'I');
}
But if I comment this lines out I get this fault:
Fatal error: Uncaught Error: Class "Fpdi\Fpdi" not found in /home/.sites/707/site3898181/web/buchhaltung/belegAdd.php:28 Stack trace: #0 {main} thrown in /home/.sites/707/site3898181/web/buchhaltung/belegAdd.php on line 28
Does someone have an idea what I am doing wrong?
The function of the Page should :
Upload multiple pdf files to the ftp (work)
if upload more than one file -> merge to one file and last store the path of the file into DB (this part I have in a other file (copy and paste))
only the merge does not work

PHP and FPDI/FPDF: Fatal error: Uncaught Exception: FPDF error: Incorrect output destination

I have a PDF file, and I want to add a new page with FPDI/FPDF
Fatal error: Uncaught Exception: FPDF error: Incorrect output
destination: outfiles/111111.pdf in C:\wamp\www\pdf\fpdi\fpdf.php on
line 271 ( ! ) Exception: FPDF error: Incorrect output destination:
outfiles/111111.pdf in C:\wamp\www\pdf\fpdi\fpdf.php on line 271
require_once('fpdi/fpdf.php');
require_once('fpdi/fpdi.php');
foreach(glob('infiles/*.pdf') as $file)
{
$filename = basename($file);
$fileout = 'outfiles/' . $filename;
//echo $fileout;
$out = new FPDI();
$pagecount = $out->setSourceFile($file);
for($i = 1; $i <= $pagecount; $i++)
{
$tpl = $out->importPage($i);
$out->addPage($format);
$out->useTemplate($tpl);
if($i < $pagecount)
{
$out->addPage($format);
}
}
$out->Output($fileout);
}
The Output() method requires the first parameter to be the destination and the snd parameter the filename.
So just change the line to:
$out->Output('F', $fileout);
Additionally you should know that you cannot modify a PDF document with FPDI but you import the pages into a reusable structure. Your resulting PDF is a completely new PDF document and you'd not added new pages to the original one.

PDF to Images generate

I have PDF with 25 pages, I want to convert it into images with all pages.
My code:
First I have found number of pages.
$tmpfname= 'test_pdf.pdf';
$path = "/var/www/my_path";
$numberOfPages = $this->count_pages($tmpfname);
$numberOfPages = intval($numberOfPages); // Number of pages eg.25
Loop for convert pdf to images
for($i=0;$i<=$numberOfPages;$i++){
$im = new imagick( $tmpfname.'['.$i.']' );
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->resizeImage('1024','800', Imagick::FILTER_UNDEFINED, 0.9, true);
$im->setCompressionQuality(100);
$im->setImageFormat('jpeg');
$im->writeImage($path.'/'.$i.'.jpg');
$im->clear();
$im->destroy();
}
Function for find number of pages
function count_pages($pdfname) {
$pdftext = file_get_contents($pdfname);
$num = preg_match_all("/\/Page\W/",$pdftext, $dummy);
return $num;
}
PDF uploaded ok, and also converted images from PDF. But got this type of error after completed process:
Fatal error: Uncaught exception 'ImagickException' with message
'Postscript delegate failed /var/www/php/flipbook/uploads/flipbooks/61/test_pdf.pdf':
# error/pdf.c/ReadPDFImage/663' in /var/www/php/flipbook/application/controllers/admin/flipbooks.php:83
Stack trace: #0 /var/www/php/flipbook/application/controllers/admin/flipbooks.php(83):
Imagick->__construct('/var/www/php/fl...')
#1 [internal function]: Flipbooks->create()
#2 /var/www/php/flipbook/system/core/CodeIgniter.php(359): call_user_func_array(Array, Array)
#3 /var/www/php/flipbook/index.php(210): require_once('/var/www/php/fl...')
#4 {main} thrown in /var/www/php/flipbook/application/controllers/admin/flipbooks.php on line 83
Any buddy can help me very appreciate...
If nothing else, you have an off by one error:
for($i=0;$i<=$numberOfPages;$i++){
//..
}
This attempts to print numberOfPages + 1 pages as the index starts at zero.
I got the perfect solution from here
My new code
$tmpfname= 'test_pdf.pdf';
$path = "/var/www/my_path";
$numberOfPages = $this->count_pages($tmpfname);
$numberOfPages = intval($numberOfPages); // Number of pages eg.25
// Saving every page of a PDF separately as a JPG thumbnail
$images = new Imagick("test_pdf.pdf");
foreach($images as $i=>$image) {
// Providing 0 forces thumbnail Image to maintain aspect ratio
$image->thumbnailImage(1024,0);
$image->writeImage($path.'/'.$i.'.jpg');
}
$images->clear();
function count_pages($pdfname) {
$pdftext = file_get_contents($pdfname);
$num = preg_match_all("/\/Page\W/",$pdftext, $dummy);
return $num;
}

combining tfpdf and fpdi

I am using following code
<?php
$hd1 = $_POST["hd1"];
require_once('fpdi.php');
require_once('fpdf.php');
require('tfpdf.php');
$pdf =& new FPDI();
$pagecount = $pdf->setSourceFile('template.pdf');
$tplIdx = $pdf->importPage(1);
$s = $pdf->getTemplatesize($tplIdx);
$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L', array($s['w'], $s['h']));
$pdf->useTemplate($tplIdx,0, 0, 0, 0, true);
$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
$pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true);
$pdf->SetFont('DejaVu', '', 14);
$pdf->Cell(50,10,$hd1,0,1);
// Select a standard font (uses windows-1252)
$pdf->SetFont('Arial', '', 14);
$pdf->Ln(10);
$pdf->Write(5, 'The file uses font subsetting.');
$pdf->Output('doc.pdf', 'I');
?>
I am getting error:
Fatal error: Class 'FPDF' not found in C:\xampp\htdocs\san\ak-form\pdf\fpdi_bridge.php on line 33
When I use following code from http://www.setasign.com/products/fpdi/demos/tfpdf-demo/
<?php
$hd1 = $_POST["hd1"];
// require tFPDF
require_once('tfpdf.php');
// map FPDF to tFPDF so FPDF_TPL can extend it
class FPDF extends tFPDF
{
/**
* "Remembers" the template id of the imported page
*/
protected $_tplIdx;
/**
* Draw an imported PDF logo on every page
*/
public function Header()
{
if (is_null($this->_tplIdx)) {
$this->setSourceFile("template.pdf");
$this->_tplIdx = $this->importPage(1);
}
$size = $this->useTemplate($this->_tplIdx, 130, 5, 60);
$this->SetFont('DejaVu', 'B', 16);
$this->SetTextColor(0);
$this->SetXY($this->lMargin, 5);
$text = 'tFPDF (v' . tFPDF_VERSION . ') and FPDI (v'
. FPDI::VERSION . ')';
$this->Cell(0, $size['h'], $text);
$this->Ln();
}
}
// just require FPDI afterwards
require_once('fpdi.php');
// initiate PDF
$pdf = new FPDI();
// Add some Unicode font (uses UTF-8)
$pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true);
$pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true);
// add a page
$pdf->AddPage();
$pdf->SetFont('DejaVu', '', 14);
// Select a standard font (uses windows-1252)
$pdf->SetFont('Arial', '', 14);
$pdf->Ln(10);
$pdf->Write(5, 'The file uses font subsetting.');
$pdf->Output('doc.pdf', 'I');
?>
And getting following error:
Warning: fopen(/home/content/w/i/s/wiseinmotion/html/test3/pdf/font/unifont/DejaVuSansCondensed.ttf): failed to open stream: No such file or directory in C:\xampp\htdocs\san\ak-form\pdf\font\unifont\ttfonts.php on line 496
Can't open file /home/content/w/i/s/wiseinmotion/html/test3/pdf/font/unifont/DejaVuSansCondensed.ttf
What is the correct way so that I can use exiting pdf and can use utf-8 font?
You're asking two different questions here:
why isn't FPDF defined in the first code sample, and
why can't it load my font in the second code sample.
I'm going to answer #2 first, because it's easy: the font file is not being found. Check your path and make sure the code is looking for the font in the right place.
Regarding #1: I suspect the issue comes down to your require_once statements. Specifically, you're requiring fpdf.php in your code when the example code does not. My guess is that there's a conflict there somewhere.
Rather than spending a lot of time looking around the libraries for a problem, I would start with the example code (which comes from the developer's website, so we're pretty sure it works - maybe not, but let's assume it does until proven otherwise). Assuming that code works (and all you need to do there is fix the path to your font), start with that and modify it to do what you want.

Categories