Convert image to pdf php - php

I am using csxi to make scanning for documnets as image, but I have to upload pdf files to server. How can I convert image to PDF in php ? or is there any way to make csxi scan documents as PDF not image

If you have ImageMagick installed on your machine you could use the ImageMagick bindings for PHP to execute some simple PHP code to do this task:
$im=new Imagick('my.png');
$im->setImageFormat('pdf');
$im->writeImage('my.pdf');
Alternatively if you don't have ImageMagick available you could use a commercial API such as Zamzar which supports image to PDF conversion via PHP (more info in the docs).
Code to use this would be:
<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_API_KEY";
$sourceFilePath = "my.png";
$targetFormat = "pdf";
$sourceFile = curl_file_create($sourceFilePath);
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>

Wrap your image inside HTML and use some HTML to PDF converter like fpdf or mpdf

You can use convertapi service, easy to install:
composer require convertapi/convertapi-php
require_once('vendor/autoload.php');
use \ConvertApi\ConvertApi;
//get api key: https://www.convertapi.com/a/si
ConvertApi::setApiSecret('xxx');
$result = ConvertApi::convert('pdf', ['File' => '/dir/test.png']);
# save to file
$result->getFile()->save('/dir/file.pdf');
to convert multiple files and other options check https://github.com/ConvertAPI/convertapi-php

Here, Php 7.4, Laravel 7+, ImageMagick-7.1.0-Q16, and Ghostscript gs10.00.0 is used.
If any files are contained in the folder JpgToPdf then delete them. And so on.
/**
* jpg To pdf WEB
*
* #method convertJpgToPdf
*/
public function convertJpgToPdf(Request $request)
{
try {
//get list of files
$files = Storage::files('JpgToPdf');
/*get count of files and ,
* check if any files contain
* if any files contains
* then
* get the files name
* delete one by one
*/
if(count($files) >1 )
{
foreach($files as $key => $value)
{
//get the file name
$file_name = basename($value);
//delete file from the folder
File::delete(storage_path('app/JpgToPdf/'. $file_name));
}
}
if ($request->has('jpeg_file'))
{
$getPdfFile = $request->file('jpeg_file');
$originalname = $getPdfFile->getClientOriginalName();
$path = $getPdfFile->storeAs('JpgToPdf', $originalname);
}
// file name without extension
$filename_without_ext = pathinfo($originalname, PATHINFO_FILENAME);
//get the upload file
$storagePath = storage_path('app/JpgToPdf/' . $originalname);
$imagick = new Imagick();
$imagick->setResolution(300, 300);
$imagick->readImage($storagePath);
$imagick->setImageCompressionQuality( 100 );
$imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$imagick->writeImage( storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
return response()->download(storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
} catch (CustomModelNotFoundException $exception) {
// Throws error exception
return $exception->render();
}
}

For just a few images, do it manually and easily with the Chrome web browser. You wont need an internet connection.
Save the following with .html extension in the same folder of your image:
<html>
<body>
<img src="image.jpg" width="100%">
</body>
</html>
Open the html file with Google Chrome,
Crtl + P, to open the print dialog
Choose Save as PDF, to save it locally
Alternatively, you could send a copy to your smatphone via Google Cloud Print

Related

Need to retrieve the uploaded image from folder and send the image as form data to api

I have uploaded an image to a local folder using the below code using ajax and php after some cropping and image zooming functionality.
After this function, the cropped image is sanded to a local folder called upload. But the image is processed with base64 encode and decode model. I want to send the cropped/saved image to an api with out base64 data all I want is send the image as form data/file.
The code that used for image upload is image data is sent as form data and is base64 encoded format
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function(){
var base64data = reader.result;
formData.append('image', base64data);
$.ajax({
url:'<?php echo get_template_directory_uri(); ?>/upload.php?>',
method:'POST',
data:formData
and in upload.php
if(isset($_REQUEST['image'])) {
$data = $_REQUEST['image'];
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$image_name = 'upload/' . time() . '.png';
file_put_contents($image_name, $data);
}
i want to take this image from folder and send this data to an api as file/multipart formdata with out encryption/decrypted format
Please help me to solve this. Thank you in advance.
Once you have the image on your drive you can use curl with curlFile option for the purpose. Docs for curl and curlFile
From the docs you can see its usage
/**
* #param string $file -> full file path
* #return CURLFile
*/
function makeCurlFile($file)
{
## Create the curl file for upload
$mime = mime_content_type($file);
$info = pathinfo($file); # or simply use $name = basename($file);
$name = $info['basename'];
$output = new CURLFile($file, $mime, $name);
return $output;
}
$file = '/path/to/your/upload/directory/picture.png';
$ch = curl_init("https://example.com/api_url");
$photo = makeCurlFile($file);
## Construct your post data in an array
$postData = [
'fileObject' => $photo, # fileObject is the name of the file which your api is expecting
'desc' => 'your custom description' # Any other field that need to be sent along with the file, use as many needed
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
}
curl_close($ch);
Note:
This applies to php >= 5.5.0. For versions prior to that you cannot use curlFile and need to use # and build the body of the content manually. Read this answer or here to see how its done.
I have not set the Content-Type header. cUrl appends this header automatically as it deems fit. At least in my case whenever we ask curl to post an array it uses the Content-Type multipart/form-data. If there is an issue you will need to check headers are setup correctly.
CURLOPT_SAFE_UPLOAD A comment in the docs (here) suggest we set the CURLOPT_SAFE_UPLOAD to true for all versions >= 5.5. However, the docs is silent on the issue except this page. So I am assuming the default for this for versions >= 5.6 is true and hence you do not need to explicitly set it when using curlFile. For at least php 7.2 I can confirm it works without setting this to true.
Uploads using the #file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to false. CURLFile should be used instead.
Make use of curl_error and curl_getinfo to debug

Facebook PHP upload file from memory

I'm reading an image from my S3 bucket in AWS and want to upload it to Facebook.
This is the reading function:
/**
* Get a file from the s3 storage
*/
private function uploadPicture() {
$picture = new FacebookPicture();
$file = $this->s3Manager->getFile($this->subEndPoint,$this->verb);
$picture->pictureContent = $file["Body"];
$facebookAlbum = new FacebookAlbum();
$facebookAlbum->album = new Album();
$facebookAlbum->album->facebookAccessToken = "myAccessToken";
$facebookAlbum->id = "myAlbumId";
$facebookManager = new FacebookManager();
$facebookManager->uploadPicture($facebookAlbum,$picture);
}
This is the uploading to Facebook function
/**
* #param $facebookAlbum FacebookAlbum the album to upload the picture to
* #param $picture FacebookPicture the picture to upload
*/
public function uploadPicture($facebookAlbum,$picture)
{
$this->facebook->setAccessToken($facebookAlbum->album->facebookAccessToken);
$this->facebook->setFileUploadSupport(true);
$args = array();
$args["message"] = $picture->description;
$args["source"] = "#" . $picture->pictureContent;
$data = $this->facebook->api('/'. $facebookAlbum->id . '/photos', 'post', $args);
var_dump($data);
}
I keep getting :
curl_setopt_array(): The usage of the #filename API for file uploading is deprecated. Please use the CURLFile class instead in <b>acebook-php-sdk-master/src/base_facebook.php</b> on line <b>1005</b><br />
I think that the problem is that the image content is saved in the memory.
How can I use the variable in my memory in order to post it to Facebook ?
#filename has been deprecated in PHP >= 5.5.0 as stated here under the CURLOPT_POSTFIELDS description , So thats the reason why you got the error .
you have your answer here at this stack overflow thread, where different solutions are discussed . Also here is a snippet from RFC for the code.
Currently, cURL file uploading is done as:
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = '#/path/to/file';
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $args);
This API is both invonvenient and insecure, it is impossible to send
data starting with '#' to the POST, and any user data that is being
re-sent via cURL need to be sanitized so that the data value does not
start with #. In general, in-bound signalling usually vulnerable to
all sorts of injections and better not done in this way.
Instead of using the above method, the following should be used to
upload files with CURLOPT_POSTFIELDS:
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = new
CurlFile('filename.png', 'image/png'); curl_setopt($curl_handle,
CURLOPT_POSTFIELDS, $args);

Download file from google drive api to my server using php

1 - I have configure google picker and it is working fine and I select the file from picker and get the file id.
2 - After refresh token etc all process I get the file metadata and get the file export link
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
3 - After that I use this
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200)
{
$content = $httpRequest->getResponseBody();
print_r($content);
} else {
// An error occurred.
return null;
}
and get this response
[responseBody:protected] => PK��DdocProps/app.xml���
�0D���k�I[ѫ��m
��!����A={���}�
2G�Z�g�V��Bľ֧�n�Ҋ�ap!����fb�d����k}Ikc�_`t<+�(�NJ̽�����#��EU-
�0#���P����........
4 - I use some cURL functions to get file from google drive and save it to server. IN server directory a file created but cropped. I use this code
$downloadExpLink = $file->getExportLinks();
$downloadUrl = $downloadExpLink['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
//$downloadUrl value is
/*https://docs.google.com/feeds/download/documents/export/Export?id=1CEt1ya5kKLtgK************IJjDEY5BdfaGI&exportFormat=docx*/
When I put this url into browser it will download file successfully but when I use this url to fetch file with cURL or any php code and try to save it on server it saves corrupted file.
$ch = curl_init();
$source = $downloadUrl;
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "test/afile5.docx";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
It result a corrupted file stored on server but whe I use this code to get any file other then google drive I download it successfully on server.
Can any one please help that how to download file from $downloadUrl to my server using php ?

Generating JPG's from office files (.doc .ppt etc) using PHP

I'm building an application where people can upload files and share them with other people. Part of what we are looking to do is allow people to preview the file on-line.
Is there a strait forward way to generate a jpgs for the first X amount of pages from a document? We could then place these jpgs in the web page allowing the user to preview.
I have looked at installing open office on the server but was hoping there was a php library somewhere that does the same job.
Can anybody help?
Cheers
Btw, doesnt have to be jpg, any image file would be fine (actually even pdf would be ok)
Try this with com class:
You can use com class for convert office file to jpg
COM class Reference: -
http://us2.php.net/manual/en/class.com.php
or below code is convert ppt to jpg format
<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();
?>
or convert word to jpg
<?php
// starting word
$word = new COM("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}\n";
//bring it to front
$word->Visible = 1;
//open an empty document
$word->Documents->Add();
//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");
//closing word
$word->Quit();
//free the object
$word = null;
?>
You cannot use Office Interop to automate such a task, see Microsoft reasons for that here:
https://support.microsoft.com/en-us/kb/257757
The best approach is to use a powerful library such as Aspose.Slides (compatibility with ppt, pptx, powerful manipulation) that are designed to be used as an API.
You can consume Aspose.Slides from PHP by means of the NetPhp library. There is an example here:
http://www.drupalonwindows.com/en/blog/powerpoint-presentation-images-php-drupal-example
The relevant piece of code is this one, it has some Drupal specific stuff, but you can see how it goes and make it work on other places:
protected function processFilePowerpoint(array $file, array &$files) {
/** #var \Drupal\wincachedrupal\NetPhp */
$netphp = \Drupal::service('netphp');
$runtime = $netphp->getRuntime();
$runtime->RegisterAssemblyFromFile("libraries/_bin/aspose/Aspose.Slides.dll", "Aspose.Slides");
$runtime->RegisterAssemblyFromFullQualifiedName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing");
$destination = strtr(PresentacionSlide::UPLOAD_LOCATION, ['[envivo_presentacion:id]' => $this->entity->id()]);
file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$sourcefile = drupal_realpath($file['tmppath']);
$presentation = $runtime->TypeFromName("Aspose.Slides.Presentation")->Instantiate($sourcefile);
$format = $runtime->TypeFromName("System.Drawing.Imaging.ImageFormat")->Png;
$x = 0;
/** #var \NetPhp\Core\NetProxyCollection */
$slides = $presentation->Slides->AsIterator();
foreach ($slides as $slide) {
$x++;
$bitmap = $slide->GetThumbnail(1, 1);
$destinationfile = $destination . "\\slide_{$x}.png";
$bitmap->Save(drupal_realpath($destinationfile), $format);
$files[] = PresentacionSlide::fromFile($destinationfile);
}
$presentation->Dispose();
}
For a PHP-specific option you could use PHPWord - this library is written in PHP and provides classes to read from and write to different document file formats (including .doc and .docx), but it won't give you the ability to convert from the full range of Office files.
To convert any Office file on any platform you could use a file conversion API like Zamzar. It can convert from all Office formats (DOC / DOCX / PPT / PPTX / XLS / XLSX) into images (JPG, PNG, GIF etc) and PDF.
Code to call from PHP would be as follows (more info in the docs).
<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_KEY";
$sourceFilePath = "/tmp/my.doc"; // Or DOCX/PPT/PPTX/XLS/XLSX
$targetFormat = "jpg";
$sourceFile = curl_file_create($sourceFilePath);
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>

how to send / get files via web-services in php

is this possible ?
what is the correct way to send files ?
thanks
I don't if you want your webservice to upload/download files. Anyway you can use curl(http://fr.php.net/curl ) to upload/download file from other webserver.
To get some file uploaded to the webservice from the user it's pretty much the same as gettings it from a form, please use the superglobal variable:$_FILES (doc) to get upload files.
for uploading from php to a webservice
$fullflepath = 'C:\temp\test.jpg';
$upload_url = 'http://www.example.com/uploadtarget.php';
$params = array(
'photo'=>"#$fullfilepath",
'title'=>$title
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);
the webservice to get a file
$uploads_dir = '/uploads';
foreach ($_FILES["photo"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["photo"]["tmp_name"][$key];
$name = $_FILES["photo"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
PS: sorry for some reason stackoverflow doesn't like to make a link of $_FILES ... so I have linked the superglobals page instead
You use this php program based on nusoap : http://biclim.com/WSClients.action
You can debug the response of your php service and check the file upload from iphone using this app - http://itunes.apple.com/us/app/rest-client/id503860664?ls=1&mt=8
It was really helpful to debug serverside code.
Hello Here Example Image upload
<?php
$path="aa/";// Set your path to image upload
if(!is_dir($path)){
mkdir($path);
}
$roomPhotoList = $_POST['image'];
$random_digit=date('Y_m_d_h_i_s');
$filename=$random_digit.'.jpg';
$decoded=base64_decode($roomPhotoList);
file_put_contents($path.$filename,$decoded);
?>
it can be quick image upload code in php for ios and android

Categories