unable to read pdf file using imagick - php

I'm trying to convert a pdf file to a jpeg. But I cant even get the simplest example to work.
<?php
if (!extension_loaded('imagick'))
die('Imagick is not installed');
else
echo 'Imagick installed<hr>';
$inputFile="test.pdf";
if(file_exists($inputFile)){
echo "$inputFile exists.<br>";
}
else{
die("$inputFile doesnt exist.");
}
$imagick = new Imagick();
$imagick->readImage($inputFile);
$imagick = $imagick->flattenImages();
$imagick->writeFile('test.jpg');
?>
The first test says the file exists but imagaick is not able to read the file.
Fatal error: Uncaught exception 'ImagickException' with message
'unable to open image `test.pdf': No such file or directory #
error/blob.c/OpenBlob/2646' in C:\xampp\htdocs\img\index.php:14 Stack trace: #0
C:\xampp\htdocs\img\index.php(14): Imagick->__construct('test.pdf') #1 {main} thrown in
C:\xampp\htdocs\img\index.php on line 14
What am I doing wrong ?

The problem is in your path to pdf file,
simply use $_SERVER['DOCUMENT_ROOT']
$inputFile = $_SERVER['DOCUMENT_ROOT']."/test.pdf";

Related

PhpSpreadsheet Fatal Error "Could not find zip member"

Hi am using PhpSpreadsheet, and here is my code:
switch ($file_extension) {
case 'xlsx':
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
break;
case 'xls':
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
break;
default:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
break;
}
$spreadsheet = $reader->load($_FILES['file']['tmp_name']);
Now I am uploading excelsheet using Ajax, from two source -
From Local Device: var fileName = $(this).find('input[type=file]').prop('files')[0]; //with tmp_name = C:\xampp\tmp\php742D.tmp
From Google Drive: var fileName = new File([res.body], doc.name, { type: doc.mimeType }) //with tmp_name = C:\xampp\tmp\php1F2A.tmp
So, when my php code executing $spreadsheet = $reader->load($_FILES['file']['tmp_name']) this line giving fatal error:
Fatal error: Uncaught
PhpOffice\PhpSpreadsheet\Reader\Exception: Could not find zip member
zip://C:\xampp\tmp\php2854.tmp#_rels/.rels in
C:\xampp\htdocs\myWebapp\GET-OCR\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Shared\File.php:159
Stack trace:
#0 C:\xampp\htdocs\myWebapp\GET-OCR\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Reader\Xlsx.php(393):
PhpOffice\PhpSpreadsheet\Shared\File::assertFile('C:\xampp\tmp\ph...',
'_rels/.rels')
#1 C:\xampp\htdocs\myWebapp\GET-OCR\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Reader\BaseReader.php(166):
PhpOffice\PhpSpreadsheet\Reader\Xlsx->loadSpreadsheetFromFile('C:\xampp\tmp\ph...')
#2 C:\xampp\htdocs\myWebapp\GET-OCR\controller\ajax-req.php(81): PhpOffice\PhpSpreadsheet\Reader\BaseReader->load('C:\xampp\tmp\ph...')
#3 {main} thrown in C:\xampp\htdocs\myWebapp\GET-OCR\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Shared\File.php
on line 159
I checked https://stackoverflow.com/a/50476471/3340665 & PhpSpreadsheet: Permissions | ZipArchive::close(): Failure to create temporary file But no help.

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!!!

PHPExcel Appending to file error

I am trying to create Excel File and appending data to it from a webpage. Excel file is created corrected and data is also saved in it, but when I try to load the file again and append data to it. it gives a Fatal error
Uncaught exception 'PHPExcel_Writer_Exception' with message 'File
zip:///home/timespk/public_html/htmlParser/index.xlsx#xl/media/b1b39dadf76812b4c58e06ea6ddf57841.png
does not exist' in
/home/timespk/public_html/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php:216
Stack trace: #0
/home/timespk/public_html/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php(164):
PHPExcel_Writer_Excel2007_ContentTypes->_getImageMimeType('zip:///home/tim...')
1 /home/timespk/public_html/Classes/PHPExcel/Writer/Excel2007.php(224):
PHPExcel_Writer_Excel2007_ContentTypes->writeContentTypes(Object(PHPExcel),
false) #2 /home/timespk/public_html/htmlParser/index.php(216):
PHPExcel_Writer_Excel2007->save('/home/timespk/p...') #3 {main} thrown
in
/home/timespk/public_html/Classes/PHPExcel/Writer/Excel2007/ContentTypes.php
on line 216
Can anyone tell what I am doing wrong here?
This is the code that I am using to save Image to Excel file
$objPHPExcel2->getActiveSheet()->getColumnDimension('A')->setWidth(22);
$image = file_get_contents($imgSrc);
file_put_contents('image' . $highestRow . '.jpg', $image);
$gdImage = imagecreatefromjpeg('image' . $highestRow . '.jpg');
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setHeight(150);
$objDrawing->setCoordinates('A'. $highestRow);
$objDrawing->setWorksheet($objPHPExcel2->getActiveSheet());
I believe that I've found proper solution to this problem which works with PHPExcel_Worksheet_Drawing:
https://stackoverflow.com/a/23951597/925196

PHP library object error

I am having an issue with imagick php library.
I am doing a recursive search in my file system and look for any pdf files.
$it = new RecursiveDirectoryIterator("/test/project");
$display = Array ('pdf');
foreach(new RecursiveIteratorIterator($it) as $file){
if (in_array(strtolower(array_pop(explode('.', $file))), $display))
{
if(file_exists($file)){
echo $file; //this would echo /test/project/test1.pdf
$im = new Imagick($file);
$im->setImageFormat("jpg");
file_put_contents('test.txt', $im);
}
}
}
However, I am getting an error saying
Fatal error: Uncaught exception 'ImagickException' with message 'Can not process empty Imagick object' in /test.php:57
Stack trace:
#0 /test.php(57): Imagick->setimageformat('jpg')
#1 {main}
thrown in /test.php on line 57
line 57 is $im->setImageFormat("jpg");
However, if I replace my $im = new Imagick($file) with $im = new Imagick('/test/project/test1.pdf'), the error is gone.
I don't know why this is happening. Can someone give me a hint for this issue? Thanks so much
According to this, the .jpg files' format is JPEG.
Note 1:
Your $file variable is an object SplFileInfo, but you are using it always like a string. Use RecursiveDirectoryIterator::CURRENT_AS_PATHNAME flag in RecursiveDirectoryIterator's constructor, to be a real string.
Note 2:
You can filter the iterator entries with RegexIterator, f.ex.: new RegexIterator($recursiveIteratorIterator, '/\.pdf$/') (after Note 1). Or, you can use GlobIterator too for searching only pdf files.
As #pozs pointed out
Note 1: Your $file variable is an object SplFileInfo, but you are
using it always like a string.
Here's a code snippet which gets you the filename as string and has an optimized method to get the file extension:
<?php
$display = array ('pdf');
$directoryIterator = new RecursiveDirectoryIterator('./test/project');
// The key of the iterator is a string with the filename
foreach (new RecursiveIteratorIterator($directoryIterator) as $fileName => $file) {
// Optimized method to get the file extension
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
if (in_array(strtolower($fileExtension), $display)) {
if(file_exists($fileName)){
echo "{$fileName}\n";
// Just do what you want with Imagick here
}
}
Maybe try this approach from : PDF to JPG conversion using PHP
$fp_pdf = fopen($pdf, 'rb');
$img = new imagick();
$img->readImageFile($fp_pdf);
It also seems from reading other posts that GhostScript is faster?

Fatal error: Uncaught exception 'com_exception' with message. while converting ppt to jpg

When I run blow code:
/*** PPT to Image conversion ***/
$ppt_file = 'E:\wamp\www\temp/a.pptx';
$app = new COM("PowerPoint.application") or die("Unable to instantiate PowerPoint");
$app->Visible = true;
$app->Presentations->Open($ppt_file);
$app->Presentations[1]->SaveAs("E:/tmp/outdir",18);
$app->Presentations[1]->Close();
$app->Quit();
$app = null;
It gives me one exception :
Fatal error: Uncaught exception 'com_exception' with message 'Source: Microsoft Office PowerPoint 2007Description: PowerPoint could not open the file.' in E:\wamp\www\temp\video_conversion.php:107 Stack trace: #0 E:\wamp\www\temp\video_conversion.php(107): variant->Open('E:\wamp\www\tem...') #1 {main} thrown in E:\wamp\www\temp\video_conversion.php on line 107
I am unable to figure out what is the problem.
This is kind of issue is due to the following factors.
PHP.ini settings
Folder Permission
allow open is not enabled in the server
allowed upload size
Within your error, you see the following message: PowerPoint could not open the file.' in E:\wamp\www\temp\video_conversion.php:107
Does the PHP user have permissions to the file E:\wamp\www\temp/a.pptx?
Try correcting your slashes: E:\wamp\www\temp\a.pptx as / normally refers to an option or argument.
At the end of the day, it appears to be a permissions error, a location issue or alike which is preventing access to that file. Can you open the file with fopen or file_get_contents?
Try this with com class:
COM class Reference: - http://us2.php.net/manual/en/class.com.php
<html>
<head>
<title>ShotDev.Com Tutorial</title>
</head>
<body>
<?
$ppApp = new COM("PowerPoint.Application");
$ppApp->Visible = True;
$strPath = realpath(basename(getenv($_SERVER["SCRIPT_NAME"]))); // C:/AppServ/www/myphp
$ppName = "MySlides.ppt";
$FileName = "MyPP";
//*** Open Document ***//
$ppApp->Presentations->Open(realpath($ppName));
//*** Save Document ***//
$ppApp->ActivePresentation->SaveAs($strPath."/".$FileName,17); //'*** 18=PNG, 19=BMP **'
//$ppApp->ActivePresentation->SaveAs(realpath($FileName),17);
$ppApp->Quit;
$ppApp = null;
?>
PowerPoint Created to Folder <b><?=$FileName?></b>
</body>
</html>
Or try this :
$powerpnt = new COM("powerpoint.application") or die("Unable to instantiate Powerpoint");
$presentation = $powerpnt->Presentations->Open(realpath($file), false, false, false) or die("Unable to open presentation");
foreach($presentation->Slides as $slide)
{
$slideName = "Slide_" . $slide->SlideNumber;
$exportFolder = realpath($uploadsFolder);
$slide->Export($exportFolder."\\".$slideName.".jpg", "jpg", "600", "400");
}
$powerpnt->quit();

Categories