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;
}
Related
I get error:
Fatal error: Uncaught PhpOffice\PhpSpreadsheet\Exception: Column
string index can not be longer than 3 characters in
/var/www/html/domain.com/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php:305
Stack trace: #0
/var/www/html/domain.com/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php(1430):
PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString() #1
/var/www/html/domain.com/exceltests.php(393):
PhpOffice\PhpSpreadsheet\Worksheet\Worksheet->getColumnDimension() #2
{main} thrown in
/var/www/html/domain.com/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php
on line 305
And this is the line #393 in my file:
$spreadsheet->getActiveSheet()->getColumnDimension("B$i")->setWidth(90);
EDIT More code:
$blob = returnItemImageOnly($pdo, $row["item"]);
if($blob){
$spreadsheet->getActiveSheet()->getColumnDimension("B$i")->setWidth(90);
$spreadsheet->getActiveSheet()->getRowDimension("$i")->setRowHeight(80);
$type = $blob['type'];
$image = base64_encode($blob['image']);
$imgdata = base64_decode($image);
$mimetype = getImageMimeType($imgdata);
$fname = "tmp/".rand(). ".".$mimetype;
$forUnlink[] = $fname;
file_put_contents($fname, $imgdata);
$drawing = new PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setPath($fname);
$drawing->setCoordinates("B$i");
$drawing->setResizeProportional(false);
$drawing->setWidth(75);
$drawing->setHeight(75);
$drawing->setOffsetX(34);
$drawing->setOffsetY(15);
$drawing->setWorksheet($sheet);
}
$spreadsheet->getActiveSheet()->mergeCells("B$i:C$i");
I searched for possible issues but no luck!
Maybe someone had the same issue?
Thanks in advance!
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!!!
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
I have a script that generates a PDF in Zend. I copied the script from converting image to pdf to another directory on the server. I now get the error:
Fatal error: Uncaught exception 'Zend_Pdf_Exception' with message 'Cannot create image resource.
File not found.' in /kalendarz/Zend/Pdf/Resource/ImageFactory.php:38
Stack trace:
#0 /kalendarz/Zend/Pdf/Image.php(124): Zend_Pdf_Resource_ImageFactory::factory('data/0116b4/cro...')
#1 /kalendarz/cms.php(56): Zend_Pdf_Image::imageWithPath('data/0116b4/cro...')
#2 {main} thrown in /kalendarz/Zend/Pdf/Resource/ImageFactory.php on line 38
Code of website, example link to image (http://tinyurl.com/8srbfza):
else if($_GET['action']=='generate') {
//1 punkt typograficzny postscriptowy (cyfrowy) = 1/72 cala = 0,3528 mm
function mm_to_pt($size_mm) {
return $size_mm/0.3528;
}
require_once("Zend/Pdf.php");
$pdf = new Zend_Pdf();
$page_w = mm_to_pt(100);
$page_h = mm_to_pt(90);
$page = $pdf->newPage($page_w.':'.$page_h.':');
$pdf->pages[] = $page;
$imagePath= 'data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg'; //to nie jest miniaturka
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$left = mm_to_pt(0);
$right = mm_to_pt(100);
$top = mm_to_pt(90);
$bottom = mm_to_pt(0);
$page->drawImage($image, $left, $bottom, $right, $top);
$pdfData = $pdf->render();
header("Content-Disposition: inline; filename=".$_GET['id'].".pdf");
header("Content-type: application/x-pdf");
echo $pdfData;
die();
}
Zend_Pdf_Image::imageWithPath expects a valid file and uses is_file function call to check the file existence.
First of all, use absolute path to the image, instead of using the relative one. You can specify the absolute path by referring to your APPLICATION_PATH. For example,
APPLICATION_PATH . '/../public/data
If APPLICATION_PATH is not already defined in your code, paste this code in your public/index.php
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
Then, check if 'data/'.$GET['id'].'/crop'.$_GET['id'].'.jpg' exists. Also, check if the file has proper permissions to be accessed by PHP.
Note : Use the Zend request object instead of the $_GET.
Use an absolute path:
$imagePath = '/kalendarz/data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg';
or:
$imagePath = APPLICATION_PATH.'/../data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg';
you might also want to put some validation on $_GET['id'].
I'm having a very problematic error with phpthumb: http://phpthumb.gxdlabs.com/
So basically, I have a form which uploads a profile picture. The uploading seems to work because it uploads the image in the directory. The problem is that it doesn't generate the thumbnails but I'm sure that all the variables and names are correct. It gives me the following error. Specifically 'Image file not found':
Fatal error: Uncaught exception 'Exception' with message 'Image file not found: ����' in {PATH}\phpthumb\ThumbBase.inc.php:193 Stack trace: #0 {PATH}\phpthumb\ThumbBase.inc.php(172): ThumbBase->triggerError('Image file not ...') #1 {PATH}\phpthumb\ThumbBase.inc.php(110): ThumbBase->fileExistsAndReadable() #2 {PATH}\phpthumb\GdThumb.inc.php(96): ThumbBase->__construct('??????JFIF?????...', false) #3 G:\EasyPHP\www\YourSlab\phpthumb\ThumbLib.inc.php(127): GdThumb->__construct('??????JFIF?????...', Array, false) #4 {PATH}\edit_profile.php(74): PhpThumbFactory::create('??????JFIF?????...') #5 {PATH}\edit_profile.php(80): generateThumbnail->createthumbnail(25) #6 {PATH}\edit_profile.php(118): set_profile_info('Mico Abrina', '1', 'asdf', 'asdf', '', 'asdf', 'asdf', '', '05', '4', '1996', 'G:\EasyPHP\tmp\...') #7 {main} thrown in {PATH}\phpthumb\ThumbBase.inc.php on line 193
I think its because I'm generating the thumbnails right after uploading it. How do I make it work?
<?php
//upload images
if (file_exists($profile_pic)) {
$src_size = getimagesize($profile_pic);
if ($src_size['mime'] === 'image/jpeg'){
$src_img = imagecreatefromjpeg($profile_pic);
} else if ($src_size['mime'] === 'image/png') {
$src_img = imagecreatefrompng($profile_pic);
} else if ($src_size['mime'] === 'image/gif') {
$src_img = imagecreatefromgif($profile_pic);
} else {
$src_img = false;
}
if ($src_img !== false) {
$md5sessionid = md5($_SESSION['user_id'].'asdf');
imagejpeg($src_img, "profile_pic/$md5sessionid.jpg");
//end of uploading images
//image thumbnail creation class
class generateThumbnail {
public function createthumbnail($size) {
$md5sessionidsecret = md5($_SESSION['user_id'].'asdf');
$md5sessionidthumb = md5($md5sessionidsecret.''.$size);
$path_to_thumb_pic = 'profile_pic/'.$md5sessionidthumb.'.jpg';
$profile_pic = file_get_contents('profile_pic/'.$md5sessionidsecret.'.jpg');
$thumb_profile_pic = PhpThumbFactory::create($profile_pic);
$thumb_profile_pic->adaptiveResize($size, $size);
$thumb_profile_pic->save($path_to_thumb_pic);
}
}
//make the thumbnails
$createThumbnail = new generateThumbnail();
$createThumbnail->createthumbnail(25);
$createThumbnail->createthumbnail(75);
$createThumbnail->createthumbnail(175);
}
}
?>
It appears that PhpThumbFactory::create() takes a file path as its first argument, unless you specify true for the third isDataStream argument. That is why you are getting the strange output in the exception where it says Image File Not Found.
You could do a few things to fix it:
// Either skip the file_get_contents call and pass the file path directly
$thumb_profile_pic = PhpThumbFactory::create('profile_pic/'.$md5sessionidsecret.'.jpg');
// or set the 3rd parameter isDataStream to true
$profile_pic = file_get_contents('profile_pic/'.$md5sessionidsecret.'.jpg');
$thumb_profile_pic = PhpThumbFactory::create($profile_pic, array(), true);