Giter Site home page Giter Site logo

api2pdf / api2pdf.php Goto Github PK

View Code? Open in Web Editor NEW
45.0 6.0 15.0 43 KB

PHP client library for the Api2Pdf.com REST API - Convert HTML to PDF, URL to PDF, Office Docs to PDF, Merge PDFs, HTML to Image, URL to Image, HTML to Docx, HTML to Xlsx, PDF to HTML, Thumbnail preview of office files

Home Page: https://www.api2pdf.com

License: MIT License

PHP 100.00%
pdf pdf-generation html-to-pdf url-to-pdf merge-pdf word-to-pdf wkhtmltopdf headless-chrome libreoffice aws-lambda

api2pdf.php's People

Contributors

apexdodge avatar arkamax2k avatar georgeboot avatar rozenlicht avatar sergiosusa 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

api2pdf.php's Issues

Add an interface for the public methods

The Api2Pdf class has no interface and is therefore it's difficult to unit tests classes that take a dependency on that class.

Additionally the filename, inline and options properties should not be class members but method variables since they usually vary per call and, more importantly, it makes the class stateful which is undesirable when using a shared instance (in a DI container for example).

SSL certificate problem

PHP Fatal error: Uncaught Api2Pdf\Exception\ProtocolException: SSL certificate problem: unable to get local issuer certificate in vendor\api2pdf\api2pdf.php\src\Api2Pdf.php:128

Do you have a support page on what I'm missing here? My server does use an SSL cert, I'm not sure what my next step is.

Merging many file types to pdf and adding bookmarks in the process

I'm using api2pdf to merge many different file types (docx, xlsx, jpg, png, pdf) to a single pdf. Now I want to also create a table of contents, but for that to work I have to first add bookmarks to the first page of each input file.

The challenge is that xlsx, docx and pdf input files can be more than one page long, so to calculate where to put the bookmarks I need to know the length of each input document. Any suggestions on how I could do this?

Delete method is getting me a error.

Hi,

We are starting to use your api but i get an error when i delete a generated pdf:

Looks like there is no pdf file on data when you try to create de ApiResponse object whitch is correct, file already delete.

'{ "mbIn": 0.0, "mbOut": 0.0, "cost": 6.4011E-05, "success": true, "error": null, "responseId": "46b3ab82-aaa2-4103-a856-5ea5b515962e" }'

i'm going to let a PR to fixed up.

Upstream request timeout

The last time I worked on my project (about a month ago), everything was working as expected. Yesterday I started working on it again, but now I keep getting "Upstream request timeout" when attempting to convert files to pdf using libreOfficeAnyToPdf.

This is a typical stack trace:

Api2Pdf exception: Api2Pdf\Api2PdfException Object
(
    [message:protected] => Error from API: upstream request timeout
    [string:Exception:private] => 
    [code:protected] => 0
    [file:protected] => /share/CE_CACHEDEV1_DATA/Web/vendor/api2pdf/api2pdf.php/src/Api2PdfResult.php
    [line:protected] => 49
    [trace:Exception:private] => Array
        (
            [0] => Array
                (
                    [file] => /share/CE_CACHEDEV1_DATA/Web/vendor/api2pdf/api2pdf.php/src/Api2Pdf.php
                    [line] => 350
                    [function] => createFromResponse
                    [class] => Api2Pdf\Api2PdfResult
                    [type] => ::
                    [args] => Array
                        (
                            [0] => {"Error":"Error from API: upstream request timeout"}
                        )

                )

            [1] => Array
                (
                    [file] => /share/CE_CACHEDEV1_DATA/Web/vendor/api2pdf/api2pdf.php/src/Api2Pdf.php
                    [line] => 144
                    [function] => makeRequest
                    [class] => Api2Pdf\Api2Pdf
                    [type] => ->
                    [args] => Array
                        (
                            [0] => /libreoffice/any-to-pdf
                            [1] => Array
                                (
                                    [inline] => 1
                                    [url] => https://hiddenurl.com/Kunder/Fortuna_test/Prosjekt_Rorledning/Bilder/fiskeoppdrett.jpg
                                )

                        )

                )

            [2] => Array
                (
                    [file] => /share/CE_CACHEDEV1_DATA/Web/api.php
                    [line] => 202
                    [function] => libreOfficeAnyToPdf
                    [class] => Api2Pdf\Api2Pdf
                    [type] => ->
                    [args] => Array
                        (
                            [0] => https://hiddenurl.com/Kunder/Fortuna_test/Prosjekt_Rorledning/Bilder/fiskeoppdrett.jpg
                        )

                )

            [3] => Array
                (
                    [file] => /share/CE_CACHEDEV1_DATA/Web/api.php
                    [line] => 34
                    [function] => merge_to_pdf
                    [args] => Array
                        (
                            [0] => Prosjekt_Rorledning
                            [1] => [{"isDir":false,"path":"./Kunder/Fortuna_test/Prosjekt_Rorledning/Bilder","name":"fiskeoppdrett.jpg"}]
                        )

                )

        )

    [previous:Exception:private] => 
)

Is there some problem with your servers?

enable psr-4 / composer

would it be possible to provide a composer installation method compliant with psr-4?
https://getcomposer.org/doc/04-schema.md

of course copying the file (with some little customization) works... but it would be far preferable to have the possibility of installing this library through the composer

wrong notation in documentation

in PHP, methods are not noted with a dot, but with an arrow:

$api_response = $a2p_client.wkhtmltopdf_from_html('<p>Hello, World</p>');
is wrong

$api_response = $a2p_client->wkhtmltopdf_from_html('<p>Hello, World</p>');
is correct

Documentation says Headless Chrome paperWidth and paperHeight default to 8.5in by 11in., but it's defaulting to A4 size

In the API2PDF docs (https://www.api2pdf.com/documentation/advanced-options-headless-chrome/) it says paperWidth and paperHeight default to 8.5in by 11in respectively. In my CSS I have:

@page {
	size: letter;
	margin: 0;
}

I wasn't passing any options to the API. After struggling for hours to figure out where this extra "margin" was coming from. I screenshotted the PDF and measured it and figured out it was A4 size. So I set paperWidth to 8.5 and paperHeight to 11 and the page size was correct.

Are the docs wrong? Why was my page size defaulting to A4?

PHP Fatal error: Class 'Api2Pdf\Exception\ConversionException' not found

Hi. Im new to Api2Pdf. Im using this for merging bunch of files to create a pdf document. Currently im facing an issue:

PHP Fatal error: Class 'Api2Pdf\Exception\ConversionException' not found in /api2pdf/src/ApiResult.php on line 52

From the beginning, I never do any changes in Api2Pdf source codes. I just call merge functions. Is it possible that this happens because of the merging process is too heavy because i compile too many pdfs?

Pdf From Url Failing

If I use headlessChromeFromUrl, all my requests are failing with the error **invalid authorization header** this is despite the URL page not needing authentication to be viewed.

The specific line that fails is line #50 $result = $this->api2PdfClient->headlessChromeFromUrl($url);

My Code

<?php


namespace App\ApiActions;


use Api2Pdf\Api2Pdf;
use App\Models\Invoice;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

class PdfApiGenerator
{
    /**
     * @var Api2Pdf Client
     */
    private $api2PdfClient;
    /**
     * @var \Ramsey\Uuid\UuidInterface
     */
    private $uuid;

    public function __construct()
    {
        $this->api2PdfClient = new Api2Pdf(config('api2pdf.client_key'));
        $this->uuid = Str::uuid();
    }

    public function generatePdfFromHtml(string $html): string
    {
        $result = $this->api2PdfClient->headlessChromeFromHtml($html);
        $fileContent = file_get_contents($result->getPdf());

        $this->uploadFileToStorage($fileContent);

        return \Storage::disk('invoices')->path($this->uuid);
    }

    private function uploadFileToStorage($fileContent): bool
    {
        return \Storage::disk('invoices')->write($this->uuid . '.pdf', $fileContent);
    }

    public function generatePdfFromUrl(Invoice $invoice): string
    {
        $url = URL::temporarySignedRoute('invoice_pdf_view', now()->addMinutes(1), [
            'invoice' => $invoice->id
        ]);

        $result = $this->api2PdfClient->headlessChromeFromUrl($url);

        $fileContent = file_get_contents($result->getPdf());

        $this->uploadFileToStorage($fileContent);

        return \Storage::disk('invoices')->path($this->uuid);
    }

}

Stacktrace

Api2Pdf\Exception\ConversionException:  Invalid authorization header in  /home/forge/staging.app.swiftpesa.com/vendor/api2pdf/api2pdf.php/src/ApiResult.php:52
--
Stack trace:
#0   /home/forge/myapp/vendor/api2pdf/api2pdf.php/src/Api2Pdf.php(131):  Api2Pdf\ApiResult::createFromResponse()
#1 /home/forge/myapp/vendor/api2pdf/api2pdf.php/src/Api2Pdf.php(171): Api2Pdf\Api2Pdf->makeRequest()
#2 /home/forge/myapp/app/ApiActions/PdfApiGenerator.php(50): Api2Pdf\Api2Pdf->headlessChromeFromUrl()

please rewrite it using constants

I tried to use the library but it did not seem to work.
I rewrote it then using constants instead of global variables.
I would also suggest to throw exceptions in the case the curl call did not end with a 200

<?php

define("API2PDF_BASE_ENDPOINT", 'https://v2018.api2pdf.com');
define("API2PDF_MERGE", API2PDF_BASE_ENDPOINT.'/merge');
define("API2PDF_WKHTMLTOPDF_HTML", API2PDF_BASE_ENDPOINT.'/wkhtmltopdf/html');
define("API2PDF_WKHTMLTOPDF_URL", API2PDF_BASE_ENDPOINT.'/wkhtmltopdf/url');
define("API2PDF_CHROME_HTML", API2PDF_BASE_ENDPOINT.'/chrome/html');
define("API2PDF_CHROME_URL", API2PDF_BASE_ENDPOINT.'/chrome/url');
define("API2PDF_LIBREOFFICE_CONVERT", API2PDF_BASE_ENDPOINT.'/libreoffice/convert');

class Api2PdfLibrary {
    var $apikey;
    function __construct($apikey) {
        $this->apikey = $apikey;    
    }
    public function headless_chrome_from_url($url, $inline = false, $filename = null, $options = null) {
        $payload = array("url"=>$url, "inlinePdf"=>$inline);
        if ($filename != null) {
            $payload["fileName"] = $filename;
        }
        if ($options != null) {
            $payload["options"] = $options;
        }
        return $this->_make_request(API2PDF_CHROME_URL, $payload);
    }
    public function headless_chrome_from_html($html, $inline = false, $filename = null, $options = null) {
        $payload = array("html"=>$html, "inlinePdf"=>$inline);
        if ($filename != null) {
            $payload["fileName"] = $filename;
        }
        if ($options != null) {
            $payload["options"] = $options;
        }
        return $this->_make_request(API2PDF_CHROME_HTML, $payload);
    }
    public function wkhtmltopdf_from_url($url, $inline = false, $filename = null, $options = null) {
        $payload = array("url"=>$url, "inlinePdf"=>$inline);
        if ($filename != null) {
            $payload["fileName"] = $filename;
        }
        if ($options != null) {
            $payload["options"] = $options;
        }
        return $this->_make_request(API2PDF_WKHTMLTOPDF_URL, $payload);
    }
    public function wkhtmltopdf_from_html($html, $inline = false, $filename = null, $options = null) {
        $payload = array("html"=>$html, "inlinePdf"=>$inline);
        if ($filename != null) {
            $payload["fileName"] = $filename;
        }
        if ($options != null) {
            $payload["options"] = $options;
        }
        return $this->_make_request(API2PDF_WKHTMLTOPDF_HTML, $payload);
    }
    public function merge($urls, $inline = false, $filename = null) {
        $payload = array("urls"=>$urls, "inlinePdf"=>$inline);
        if ($filename != null) {
            $payload["fileName"] = $filename;
        }
        return $this->_make_request(API2PDF_MERGE, $payload);
    }
    public function libreoffice_convert($url, $inline = false, $filename = null) {
        $payload = array("url"=>$url, "inlinePdf"=>$inline);
        if ($filename != null) {
            $payload["fileName"] = $filename;
        }
        return $this->_make_request(API2PDF_LIBREOFFICE_CONVERT, $payload);
    }

    private function _make_request($endpoint, $payload) {
        //Initiate cURL.
        $ch = curl_init($endpoint);
        //Encode the array into JSON.
        $jsonDataEncoded =  json_encode($payload);
        //Tell cURL that we want to send a POST request.
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //Attach our encoded JSON string to the POST fields.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
        //Set the content type to application/json
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: '.$this->apikey));
        //Execute the request
        $json_result = curl_exec($ch);

        if($json_result === false) {
            throw new \Exception(curl_error($ch), 1);
        }
        $result = json_decode($json_result);
        return $result;
    }
}

finally, I would remove the ending ?> tag which is not needed

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.