Giter VIP home page Giter VIP logo

ilovepdf-php's People

Contributors

blankse avatar darwinonline avatar guillem-pdf avatar lcollazo-ilovepdf avatar leoschronicles avatar marcogrossisas avatar maztch avatar sharpie7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ilovepdf-php's Issues

maha?

download can't be processsed.

Calling the download method on an object only downloads the file to the local directory.

Hi
Calling the download method on an object only downloads the file to the local directory rather than downloading to the users browser/computer. I tried using readFile() but it doesn't seem to work. Am I missing something? Here's my code, everything works and I have no issues with anything except for the download.

<!DOCTYPE html>
<html>
	<body>
		<form action="pdf-to-jpg.php" method="post" enctype="multipart/form-data">
    		Select image to upload:
    		<input type="file" name="fileToUpload" id="fileToUpload">
    		<input type="submit" value="Upload PDF" name="submit">
		</form>
	</body>
</html>
<?php
require_once('ilovepdf/init.php');
use Ilovepdf\Ilovepdf;
$upload_directory = 'uploads/';
$upload_name = $_FILES['fileToUpload']['name'];
$upload_size = $_FILES['fileToUpload']['size'];
$upload_type = $_FILES['fileToUpload']['type'];
$upload_tmp = $_FILES['fileToUpload']['tmp_name'];
$upload_file = $upload_directory.$upload_name;
move_uploaded_file($upload_tmp, $upload_file);
try
{
	$ilovepdf = new Ilovepdf('project_public_bc71e476a92d1e98d8f30662523d605b_K1puUe100e70c76ef01f70cae1da3587dcbf8','secret_key_27d318df13715db4ec56bf66f4baaf00_Vdu4j2e7fb8c79ef537a7aebad4ba02208d55');
	$myTaskConvertPDF = $ilovepdf->newTask('pdfjpg');
	$file = $myTaskConvertPDF->addFile(dirname(__FILE__)."/".$upload_file);
	$myTaskConvertPDF->execute();
	$myTaskConvertPDF->download();
}
catch (\Ilovepdf\Exceptions\StartException $e) 
{
	echo "An error occured on start: " . $e->getMessage() . " ";
}
catch (\Ilovepdf\Exceptions\AuthException $e) 
{
	echo "An error occured on auth: " . $e->getMessage() . " ";
	echo implode(', ', $e->getErrors());
} 
catch (\Ilovepdf\Exceptions\UploadException $e) 
{
	echo "An error occured on upload: " . $e->getMessage() . " ";
	echo implode(', ', $e->getErrors());
} 
catch (\Ilovepdf\Exceptions\ProcessException $e) 
{
	echo "An error occured on process: " . $e->getMessage() . " ";
	echo implode(', ', $e->getErrors());
} 
catch (\Ilovepdf\Exceptions\DownloadException $e) 
{
	echo "An error occured on process: " . $e->getMessage() . " ";
	echo implode(', ', $e->getErrors());
} 
catch (\Exception $e) 
{
	echo "An error occured: " . $e->getMessage();
}
?>

Webhook is never triggered

I tried to run a task, that should trigger a webhook when finished (Like example webhook_send).

That is my code:

require_once('vendor/autoload.php');

use Ilovepdf\OfficepdfTask;

// Load my keys into $keys
$myTask = new OfficepdfTask($keys[0],$keys[1]);
$file1 = $myTask->addFile('my-test.ppt');
$myTask->setOutputFilename('outfile-office.pdf');

$myTask->setWebhook('http://my-url.de:20000/pdf-download-hook');

// We don't download here because with the webhook we ordered the files must be processed in background.
// Notification will be sent once it's ready

//   $myTask->execute(); // see info add "Own research"

Expected behavior:

  • WebHook-url should be triggered, when task is done.

Actual behavior:

  • WebHook is never triggered

Own reseach:

  • I noticed, that the method setWebhook() does not trigger any server-requests, so I tried to add
    $myTask->execute();
    because documentation says webhook should be send with POST https://{server}/v1/process. But the webhook still is not triggered.
  • the same script works fine, when I remove "setWebhook" and add a $myTask->download() at the end -> so I`m quite there are no issues with api key, internet connection or anything similar.
  • I sure my webhook url is reachable from public internet too

EDIT: When I add the same webhook as webhook into my global api config, it is called successfull, but dynamical adding webhooks via Task->setWebhook() seems to have no effect.

Add watermark text to center of the PDF is not working

Hello
Add watermark to the center of the PDF is not working. here are the Params that I am passing to the Request http://prntscr.com/h6wkz0

Here is the function for that.

    public function addWatermarkToPdf($files, $watermark_type='text', $watermark_text='', $watermark_image='', $fontSize=18, $fontColor='#000',
$fontFamily='courier', $range='all', $horizontalPosition='left', $verticalPosition='bottom', $opacity=50, $page_layer_pos='bottom', $watermark_rotation=35, $rotation=[], $name, $pkjFileName){
    $watermark = new WatermarkTask( $this->publicKey, $this->secretKey );
    foreach ($files as $key => $file) {
        $fileA = $watermark->addFile($file);
        $fileA->setRotation($rotation[$key] ? $rotation[$key] : 0);
    }
    // $fileA = $watermark->addFile($pdfFilePath);

    if($watermark_type=='text'){
        $watermark->setText($watermark_text);
        $watermark->setFontFamily($fontFamily);
        $watermark->setFontSize($fontSize);
        $watermark->setFontColor($fontColor);
    }
    else if(!empty($watermark_image)){
        $watermark->setMode('image');
        //$watermark->setImage($img);
        $image = $watermark->addFile($watermark_image);
        $watermark->setImage($image->server_filename);
    }

    // $watermark->setMosaic(true);
    $watermark->setPages($range);
    $watermark->setHorizontalPosition($horizontalPosition);
    $watermark->setVerticalPosition($verticalPosition);
    $watermark->setTransparency($opacity);
    $watermark->setLayer($page_layer_pos);
    $watermark->setRotation($watermark_rotation);

    $watermark->setOutputFilename($name);
    $watermark->setPackagedFilename($pkjFileName);
    // print_r($watermark);
    $watermark->execute();
    // print_r($watermark);
    return $watermark;
}

and on output response I an getting this PDF
https://www.tweak.com/wp-content/uploads/pdf/20539441-8_9953793_06-11-2017_watermark_text.pdf

Development issue

Fatal error: Uncaught exception 'Ilovepdf\Exceptions\AuthException' with message 'Unauthorized' in D:\xampp2\htdocs\pdf\vendor\ilovepdf\ilovepdf-php\src\Ilovepdf.php:182 Stack trace: #0 D:\xampp2\htdocs\pdf\vendor\ilovepdf\ilovepdf-php\src\Task.php(72): Ilovepdf\Ilovepdf->sendRequest('get', 'start/compress', 'v=php.1.1.6') #1 D:\xampp2\htdocs\pdf\vendor\ilovepdf\ilovepdf-php\src\Task.php(65): Ilovepdf\Task->start() #2 D:\xampp2\htdocs\pdf\vendor\ilovepdf\ilovepdf-php\src\CompressTask.php(26): Ilovepdf\Task->_construct('project_public...', 'secret_key_e679...', true) #3 D:\xampp2\htdocs\pdf\vendor\ilovepdf\ilovepdf-php\samples\compress_basic.php(12): Ilovepdf\CompressTask->_construct('project_public...', 'secret_key_e679...') #4 {main} thrown in D:\xampp2\htdocs\pdf\vendor\ilovepdf\ilovepdf-php\src\Ilovepdf.php on line 182

[Solved] couldn't open file

Hi, I'm trying to use your API but I have an issue, to add file to Task, It returns me a Message error like this..

An error occured: couldn't open file "uploads/_2017_08_10_08_24_55_Circular_12.pdf"

This is how I'm executing in my PHP.

$carpeta = "uploads/";
opendir($carpeta);
$destino = $carpeta.$_FILES['pdf']['name'];
copy($_FILES['pdf']['tmp_name'], $destino);
try {
$myTaskCompress = new CompressTask('project_public_0bbf***', 'secret_key_01f***');
$myTask = $myTaskCompress->newTask('split');
$file1 = $myTaskCompress->addFile($destino);
$myTaskCompress->execute();
$myTaskCompress->download();
} catch (\Ilovepdf\Exceptions\StartException $e) {
echo "An error occured on start: " . $e->getMessage() . " ";
// Authentication errors
} catch (\Ilovepdf\Exceptions\AuthException $e) {
echo "An error occured on auth: " . $e->getMessage() . " ";
echo implode(', ', $e->getErrors());
// Uploading files errors
} catch (\Ilovepdf\Exceptions\UploadException $e) {
echo "An error occured on upload: " . $e->getMessage() . " ";
echo implode(', ', $e->getErrors());
// Processing files errors
} catch (\Ilovepdf\Exceptions\ProcessException $e) {
echo "An error occured on process: " . $e->getMessage() . " ";
echo implode(', ', $e->getErrors());
// Downloading files errors
} catch (\Ilovepdf\Exceptions\DownloadException $e) {
echo "An error occured on process: " . $e->getMessage() . " ";
echo implode(', ', $e->getErrors());
// Other errors (as connexion errors and other)
} catch (\Exception $e) {
echo "An error occured: " . $e->getMessage();
}

SOLVED!

I managed to resolve the issue replacing this line:

$file1 = $myTaskCompress->addFile($destino);

For this one ๐Ÿ‘

$file = $myTaskCompress->addFile(dirname(__FILE__)."/".$destino);

Extra

And for complete the download I edited this line...

$myTaskCompress->download("uploads/");

This replace the PDF previously uploaded for the compressed PDF.

PDF to WORD

PDF to word not working as convert task is not available

cURL error 7

This is my code to convert html to PDF, but I get cURL error 7

$ilovepdf = new Ilovepdf('{public_key}','{secret_key}');

$myTaskHtmlpdf = $ilovepdf->newTask('htmlpdf');

$file = $myTaskHtmlpdf->addUrl($post_url);

$myTaskHtmlpdf->execute();

$myTaskHtmlpdf->download();

This is the error details

PHP Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 7: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api32.ilovepdf.com/v1/upload in /vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:210

upload timeout

Timeout are set to:

  • Request::timeout(null);
  • Request::timeout(10);
    Set values into properties, so they can be set

This task can't be processed. Check why in the params. (Elements cannot be blank.)

i use this code

<?php 
require_once("sources/ilovepdf/vendor/autoload.php");
use Ilovepdf\Ilovepdf;
use Ilovepdf\EditpdfTask;
use Ilovepdf\Editpdf\TextElement;
try { 
if(file_exists('C:/xampp/htdocs/websites/site1/1.pdf')){
set_time_limit(0);	
chmod('C:/xampp/htdocs/websites/site1/1.pdf', 0755);
$PDF = new Ilovepdf('project_public_....','secret_key_...');
$editTask = $PDF->newTask('editpdf');
$editTask->addFile('C:/xampp/htdocs/websites/site1/1.pdf');
$textElem = new TextElement();
$textElem->setText("Sample text")->setCoordinates(300, 600)
            ->setPages(2)
            ->setTextAlign("center")
            ->setFontFamily("Times New Roman")
            ->setFontColor("#FB8B24") // Orange
            ->setBold();;
$editTask->addElement($textElem);
$editTask->setOutputFilename('pdfa1');
$editTask->execute();
$editTask->download('sources/pdf_folder/');
}
}
 catch (\Exception $e) {
   echo '<pre>';
   print_r($e);
   echo '</pre>';
}
?>

and get error "This task can't be processed. Check why in the params. (Elements cannot be blank.)"
in params display this : ```
"[params:Ilovepdf\Exceptions\ExtendedException:private] => stdClass Object
(
[elements] => Array
(
[0] => Elements cannot be blank.
)

    )"
anybody know why this can mean and how fix? pdf file is correct and have no problem

Timeout Error, Unable to download compressed file

Hi All,

I tried to use this library, I'm getting the timeout exception. I debugged the issue upto some level and found that the issue is coming from the DownloadTask of the library and throws DownloadException as a time out.

Below is the sample code that I tried and error response that I'm getting:

$ilovepdf = new \Ilovepdf\Ilovepdf('public_key','secret_key'); // $ilovepdf->timeoutLarge = 60*60*60; // $ilovepdf->timeout = 60*60*60; $myTask = $ilovepdf->newTask('compress'); $file1 = $myTask->addFile('pdfs/08951505120104739-page_full.pdf'); try { \Ilovepdf\Request::timeout(60*60*60*10); // \Ilovepdf\Request::timeout(10); $myTask->execute(); $myTask->download(); echo "done"; } catch (\Ilovepdf\Exceptions\StartException $e) { echo "An error occured on start: " . $e->getMessage() . " "; // Authentication errors } catch (\Ilovepdf\Exceptions\AuthException $e) { echo "An error occured on auth: " . $e->getMessage() . " "; echo implode(', ', $e->getErrors()); // Uploading files errors } catch (\Ilovepdf\Exceptions\UploadException $e) { echo "An error occured on upload: " . $e->getMessage() . " "; echo implode(', ', $e->getErrors()); // Processing files errors } catch (\Ilovepdf\Exceptions\ProcessException $e) { echo "An error occured on process: " . $e->getMessage() . " "; echo implode(', ', $e->getErrors()); // Downloading files errors } catch (\Ilovepdf\Exceptions\DownloadException $e) { echo "An error occured on process: " . $e->getMessage() . " "; echo implode(', ', $e->getErrors()); // Other errors (as connexion errors and other) } catch (\Exception $e) { echo "An error occured: " . $e->getMessage(); }

Error that I'm getting:

An error occured: Operation timed out after 10019 milliseconds with 376283 out of 1617933 bytes received

Can anyone please help me to overcome from this problem?

Add image to Watermark is not working

Add image to Watermark is not working
getting null results

Here is the ILovePDFwatermark object
Ilovepdf\WatermarkTask Object
(
[mode] =>
[text] =>
[image] => /var/www/tweak.com/htdocs/wp-content/uploads/2017/10/A-letter2-11.png
[pages] => 1-3
[vertical_position] => bottom
[verticalPositionValues:Ilovepdf\WatermarkTask:private] => Array
(
[0] => bottom
[1] => middle
[2] => top
)

[horizontal_position] => left
[horizontalPositionValues:Ilovepdf\WatermarkTask:private] => Array
    (
        [0] => left
        [1] => center
        [2] => right
    )

[vertical_position_adjustment] => 
[horizontal_position_adjustment] => 
[mosaic] => 1
[rotation] => 0
[font_family] => 
[fontFamilyValues:Ilovepdf\WatermarkTask:private] => Array
    (
        [0] => Arial
        [1] => Arial Unicode MS
        [2] => Verdana
        [3] => Courier
        [4] => Times New Roman
        [5] => Comic Sans MS
        [6] => WenQuanYi Zen Hei
        [7] => Lohit Marathi
    )

[font_style] => 
[font_size] => 
[font_color] => 
[transparency] => 80
[layer] => above
[layerValues:Ilovepdf\WatermarkTask:private] => Array
    (
        [0] => above
        [1] => below
    )

[task] => v02rjq6jhcc56ykf6856cbb3sA4fm56vhsA1zv6z8dlsbk2w7nhxgktv27l0wj8ycrgtbmbv1zwhl2qstt9ymAcsd72dvbrlA4d3v4m2wrpbcj3kgvh7grfh6rglwkv5j6tzds9bj0Alzqwkz9snj25qhq
[files] => Array
    (
        [0] => Ilovepdf\File Object
            (
                [server_filename] => 00640bcdf3fce4200eca99d4af934a7b5506cd05de3b886d915a85c2d46b8a11.pdf
                [filename] => 20539441-104.pdf
                [rotate] => 0
                [password] => 
            )

    )

[tool] => watermark
[packaged_filename] => 20539441-104_6582842_{date}_watermark_image
[output_filename] => 20539441-104_6272893_{date}_watermark_image
[ignore_errors] => 1
[ignore_password] => 1
[try_pdf_repair] => 1
[meta] => Array
    (
    )

[custom_int] => 
[custom_string] => 
[statusValues:Ilovepdf\Task:private] => Array
    (
        [0] => 
        [1] => TaskSuccess
        [2] => TaskDeleted
        [3] => TaskWaiting
        [4] => TaskProcessing
        [5] => TaskSuccessWithWarnings
        [6] => TaskError
        [7] => TaskNotFound
    )

[result] => 
[outputFile] => 
[outputFileName] => 20539441-104_6272893_{date}_watermark_image
[outputFileType] => 
[secretKey:Ilovepdf\Ilovepdf:private] => secret_key_8d27cc2a9438f34fd56b7675132b91ee_e7tUD45f6fee0d435e7254ea3e17ba54e9fb1
[publicKey:Ilovepdf\Ilovepdf:private] => project_public_e01d8d752a10309aa1d29db999ec2ba6_KIhnU309c7296019ad408ea735adcecc568e9
[workerServer:Ilovepdf\Ilovepdf:private] => https://api1.ilovepdf.com
[token] => eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE1MDkwMTM1NTcsIm5iZiI6MTUwOTAxMzU1NywiZXhwIjoxNTA5MDI3OTU3LCJqdGkiOiJwcm9qZWN0X3B1YmxpY19lMDFkOGQ3NTJhMTAzMDlhYTFkMjlkYjk5OWVjMmJhNl9LSWhuVTMwOWM3Mjk2MDE5YWQ0MDhlYTczNWFkY2VjYzU2OGU5In0.MrcymqdcrB5E9Ftcl2QNm93BMxtkVVpkd5K3ofm7KSE
[timeDelay] => 5400
[encrypted:Ilovepdf\Ilovepdf:private] => 
[encryptKey:Ilovepdf\Ilovepdf:private] => 
[timeout] => 10
[timeoutLarge] => 

)

[Solved] Call to undefined function execute()

I have following code from example
use Ilovepdf\Ilovepdf;

$ilovepdf = new Ilovepdf('xxx','xxx'); $myTaskConvertOffice = $ilovepdf->newTask('officepdf'); $file1 = $myTaskConvertOffice->addFile('uploads/'.$filename); $myTaskConvertOffice>execute(); $myTaskConvertOffice->download('uploads/');

And this error response:
Call to undefined function execute()

Any rules Iam miss?

Fatal error: Uncaught Ilovepdf\Exceptions\UploadException: Upload error in D:\xampp\htdocs\ilovepdf-php\src\Ilovepdf.php:191

Fatal error: Uncaught Ilovepdf\Exceptions\UploadException: Upload error in D:\xampp\htdocs\ilovepdf-php\src\Ilovepdf.php:191 Stack trace: #0 D:\xampp\htdocs\ilovepdf-php\src\Task.php(191): Ilovepdf\Ilovepdf->sendRequest('post', 'upload', Array) #1 D:\xampp\htdocs\ilovepdf-php\src\Task.php(156): Ilovepdf\Task->uploadFile('g27d4mrsg3ztmnz...', '../Powerpoint20...') #2 D:\xampp\htdocs\ilovepdf-php\samples\watermark_basic.php(15): Ilovepdf\Task->addFile('../Powerpoint20...') #3 {main} thrown in D:\xampp\htdocs\ilovepdf-php\src\Ilovepdf.php on line 191

Error: "Content-Disposition" Header Missing in API Response

Description
We are experiencing an issue where the "Content-Disposition" header is missing from the API response, which is critical for our file download functionality. This problem has recently surfaced and is affecting our web application's ability to process documents through your API. We use the API for splitting files, converting images to PDFs, merging documents, and compressing files.

Steps to Reproduce

  1. Send a request to the API to process a document (e.g., split, merge, compress, or ImageToPdf conversion).
  2. Attempt to download the processed file using the provided endpoint.
  3. The API response lacks the "Content-Disposition" header, causing our file download logic to fail.

Expected Behavior
The API response should include a "Content-Disposition" header with the filename, allowing our application to correctly handle the file download.

Actual Behavior
The "Content-Disposition" header is missing from the API response, leading to a failure in our download logic. The issue is identified in the following code snippet from our src/Task.php at line 323:

private function downloadFile($task)
{
    $data = array('v'=> self::VERSION);
    $body = Body::Form($data);
    $response = parent::sendRequest('get', 'download/' . $task, $body);

    if(preg_match("/filename\*\=utf-8\'\'([\W\w]+)/", $response->headers['Content-Disposition'], $matchesUtf)){
        $filename = urldecode(str_replace('"', '', $matchesUtf[1]));
    }
    else {
        preg_match('/ .*filename=\"([\W\w]+)\"/', $response->headers['Content-Disposition'], $matches);
        $filename = str_replace('"', '', $matches[1]);
    }

    $this->outputFile = $response->raw_body;
    $this->outputFileName = $filename;
    $this->outputFileType = pathinfo($this->outputFileName, PATHINFO_EXTENSION);
}

Code Snippet (For Reference)
Here is a snippet from our implementation attempting to download and process the file:

public function imageToPdf($path, $file): array
{
    $return = ['result' => false, 'msg' => null, 'outputFileName' => null];

    for ($attempt = 1; $attempt <= $this->maxRetry; $attempt++) {
        try {
            $myTask = new ImagepdfTask($this->api_key, $this->secret_key);
            $newFileName = pathinfo($file, PATHINFO_FILENAME) . '.pdf';
            $myTask->addFile($path . $file);
            $myTask->setPagesize('A4');
            $myTask->setOutputFilename($newFileName);
            $myTask->execute();
            $myTask->download($path);

            $newFileName = $myTask->outputFileName;
            if (!file_exists($path . $newFileName)) {
                $return['msg'] = 'Nouveau fichier introuvable';
            } else {
                $return['result'] = true;
                $return['outputFileName'] = $newFileName;
            }
            return $return;

        } catch (Exception$e) {
            $return['msg'] .= 'An error occurred: ' . $e->getMessage();

            if ($attempt == $this->maxRetry) {
                return $return;
            }
        }
    }
    return $return;
}

Attempts to Resolve

  • Implemented an API call queue with delays between calls.
  • Checked for any changes in API documentation regarding headers.

Additional Context
This issue seems to occur randomly and has significantly impacted our ability to serve our users effectively. Any insights or advice on how to address this problem would be greatly appreciated.

Internal Server Error on file upload step

Was not sure where else to post this as this may very well be a fault from my end.

I'm trying to upload files from Salesforce through Apex. Apex is already wobbly with file upload through HTTPRequest, but this post seemed to have gotten to the bottom of it.

However in that post, the OP only had one parameter in the body, the file itself, whereas ilovepdf needs the file as well as the task ID which is where I'm having the problem.

I tried many ways to assemble the request body. At first I was getting only badRequest with Empty or incorrect task, but after fiddling around with the \r\n construction within the requestbody, I started getting code 500 errors.

For your reference, this is my Apex code:

`String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
String header = '--'+boundary+'\r\n';
    + 'Content-Disposition: form-data; name="task"\n';
    + startResponse.task+'\r\n';
    + '--' + boundary;
    + '\r\nContent-Disposition: form-data; name="file"; filename="'+file_name+'";\nContent-Type: application/octet-stream';

String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
while (headerEncoded.endsWith('=')) {
    header += ' ';
    headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));}
String bodyEncoded = EncodingUtil.base64Encode(file_body);

Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());

String footer = '--'+boundary+'--';
if (last4Bytes.endsWith('==')) {
    last4Bytes = last4Bytes.substring(0,2) + '0K';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
} else if (last4Bytes.endsWith('=')) {
    last4Bytes = last4Bytes.substring(0,3) + 'N';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    footer = '\n' + footer;
} else {
    footer = '\r\n' + footer;
}

String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);

HttpRequest req = new HttpRequest();
if (headerMap != null) for (String key : headerMap.keySet()) req.setHeader(key, headerMap.get(key));
req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
req.setMethod('POST');
req.setEndpoint(url);
req.setBodyAsBlob(bodyBlob);
req.setTimeout(120000);

Http http = new Http();
HTTPResponse res = http.send(req);`

Fatal error: Class 'Ilovepdf' not found in...

I am new in this i did exactly as ilovepdf document but i am getting error
below is my code:

<?php
require_once("ilovepdf/init.php");

`//` Authenticate
$ilovepdf = new Ilovepdf('project_public_id', 'project_secret_key');

// Choose your processing tool and create a new task
$myTaskCompress = $ilovepdf->newTask('compress');

// Add files to task for upload
$file1 = $myTaskCompress->addFile('file1.pdf');
$file2 = $myTaskCompress->addFile('file2.pdf');

// Execute the task
$myTaskCompress->execute();

// Download the packaged files
$myTaskCompress->download();

?>

Upload exception

I'm trying to unlock a pdf file but when I do the task it gives me this issue:

Uncaught Ilovepdf\Exceptions\UploadException in C:\xampp\htdocs\unlock\ilovepdf-php\src\Ilovepdf.php:188 Stack trace: #0 C:\xampp\htdocs\unlock\ilovepdf-php\src\Task.php(154): Ilovepdf\Ilovepdf->sendRequest('post', 'upload', Array) #1 C:\xampp\htdocs\unlock\ilovepdf-php\src\Task.php(122): Ilovepdf\Task->uploadFile('02wswgymsA6t3zf...', 'upload/a.pdf') #2 C:\xampp\htdocs\unlock\unlock.php(15): Ilovepdf\Task->addFile('upload/a.pdf') #3 {main} thrown in C:\xampp\htdocs\unlock\ilovepdf-php\src\Ilovepdf.php on line 188

This is my code:

<?php
require_once('ilovepdf-php/init.php');

use Ilovepdf\UnlockTask;

$myTask = new UnlockTask('my_public_key','my_secret_key');

$file = $myTask->addFile('upload/a.pdf');

$myTask->execute();

$myTask->download()

I used a try-catch block, but the exception message was empty.

Fatal error: Uncaught InvalidArgumentException: File /uploadpdf/1495.pdf does not exists in C:\xampp\htdocs\Spot\Spot\vendor\ilovepdf-php\src\Task.php:191

Fatal error: Uncaught InvalidArgumentException: File /uploadpdf/1495.pdf does not exists in C:\xampp\htdocs\Spot\Spot\vendor\ilovepdf-php\src\Task.php:191 Stack trace: #0 C:\xampp\htdocs\Spot\Spot\vendor\ilovepdf-php\src\Task.php(162): Ilovepdf\Task->uploadFile('g27d4mrsg3ztmnz...', '/uploadpdf/1495...') #1 C:\xampp\htdocs\Spot\Spot\api_ilovepdf.php(18): Ilovepdf\Task->addFile('/uploadpdf/1495...') #2 {main} thrown in C:\xampp\htdocs\Spot\Spot\vendor\ilovepdf-php\src\Task.php on line 191

Upload Problem of file

Code is after following your step's of previous upload issue raised is :-
<?php require_once('init.php'); use Ilovepdf\UnlockTask; //with your credentils $myTask = new UnlockTask('project_public_1c8**','secret_key_f**'); try{ $file = $myTask->addFile('Bt21to27july2019.pdf'); } catch (\Exception $e) { var_dump($e); } ?>

This Returns up as below mentioned :-
`C:\xampp\htdocs\pdftest\index.php:43:
object(Ilovepdf\Exceptions\UploadException)[4]
private 'params' (Ilovepdf\Exceptions\ExtendedException) => null
private 'type' (Ilovepdf\Exceptions\ExtendedException) => null
protected 'message' => string 'Upload error' (length=12)
private 'string' (Exception) => string '' (length=0)
protected 'code' => int 0
protected 'file' => string 'C:\xampp\htdocs\pdftest\src\Ilovepdf.php' (length=40)
protected 'line' => int 191
private 'trace' (Exception) =>
array (size=3)
0 =>
array (size=6)
'file' => string 'C:\xampp\htdocs\pdftest\src\Task.php' (length=36)
'line' => int 191
'function' => string 'sendRequest' (length=11)
'class' => string 'Ilovepdf\Ilovepdf' (length=17)
'type' => string '->' (length=2)
'args' =>
array (size=3)
...
1 =>
array (size=6)
'file' => string 'C:\xampp\htdocs\pdftest\src\Task.php' (length=36)
'line' => int 156
'function' => string 'uploadFile' (length=10)
'class' => string 'Ilovepdf\Task' (length=13)
'type' => string '->' (length=2)
'args' =>
array (size=2)
...
2 =>
array (size=6)
'file' => string 'C:\xampp\htdocs\pdftest\index.php' (length=33)
'line' => int 41
'function' => string 'addFile' (length=7)
'class' => string 'Ilovepdf\Task' (length=13)
'type' => string '->' (length=2)
'args' =>
array (size=1)
...
private 'previous' (Exception) => null
public 'xdebug_message' => string '( ! ) Ilovepdf\Exceptions\UploadException: Upload error in C:\xampp\htdocs\pdftest\src\Ilovepdf.php on line 191

Call Stack #TimeMemoryFunc'... (length=1761)`

on Image to PDF add margin on working

on Image to PDF add margin is not adding margin o the top and bottom of the page.
Here is the request params. http://prntscr.com/h77qfa
Here is the code

public function convertToPdf($pdfFilePath, $task = 'officepdf', $orientation='portrait', $withMargin=true ,$rotation = [], $name, $pkjFileName){
    // you can call task class directly
    // to get your key pair, please visit https://developer.ilovepdf.com/user/projects
    $ilovepdf = new Ilovepdf( $this->publicKey, $this->secretKey );
    // print_r($mergeTask);
    $officepdf = $ilovepdf->newTask($task);
    if($task == 'imagepdf'){
        $officepdf->setPageSize('A4');
        $officepdf->setOrientation($orientation);
        if($withMargin){
            $officepdf->setMargin(40);
        }
    }
    // file var keeps info about server file id, name...
    // it can be used latter to cancel file
    $fileA = $officepdf->addFile($pdfFilePath);
    $fileA->setRotation($rotation);
    $officepdf->setOutputFilename($name);
    $officepdf->setPackagedFilename($pkjFileName);
    // and set name for output file.
    // the task will set the correct file extension for you.

    // process files
    $officepdf->execute();
    return $officepdf;
}

If you want to check, you can check here https://www.tweak.com/convert-to-pdf/

File Reference Broken

require_once dirname(FILE) . '/src/Exception.php';
require_once dirname(FILE) . '/src/Exceptions/Exception.php';

These files mentioned in init.php found to be missing as reported by my server.

Convert OfficePDF and compress logic

I need to save in temp path the converted document to upload again to another task compress and save again in server?

Dont have the situation of add 2 tasks convert and compress for run once, or option to compress in convert task?

Uncaught Error: Class 'Ilovepdf\EditpdfTask'

// installed with composer
use Ilovepdf\Ilovepdf;
use Ilovepdf\EditpdfTask;
use Ilovepdf\Editpdf\TextElement;

gives error:
Fatal error: Uncaught Error: Class 'Ilovepdf\EditpdfTask' not found in ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.