Code Monkey home page Code Monkey logo

api2pdf / api2pdf.php Goto Github PK

View Code? Open in Web Editor NEW
44.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 Introduction

api2pdf.php

PHP code for Api2Pdf REST API

Api2Pdf.com is a powerful REST API for instantly generating PDF and Office documents from HTML, URLs, Microsoft Office Documents (Word, Excel, PPT), Email files, and images. You can generate image preview or thumbnail of a PDF, office document, or email file. The API also supports merge / concatenation of two or more PDFs, setting passwords on PDFs, and adding bookmarks to PDFs. Api2Pdf is a wrapper for popular libraries such as wkhtmltopdf, Headless Chrome, PdfSharp, and LibreOffice.

Installation

Run the following from command line:

$ composer require api2pdf/api2pdf.php

Usage without Composer

Copy the file in the src directory to a sub-directory in your project, then add the following in the beginning of your PHP file:

require_once 'your-own-directory/Api2Pdf.php';

Resources

Resources this API supports:

Authorization

Acquire API Key

Create an account at portal.api2pdf.com to get your API key.

Usage

Initialize the Client

All usage starts by calling the import command and initializing the client by passing your API key as a parameter to the constructor.

use Api2Pdf\Api2Pdf;

$apiClient = new Api2Pdf('YOUR-API-KEY');

Once you initialize the client, you can make calls like so:

$result = $apiClient->chromeHtmlToPdf('<p>Hello, World</p>');
echo $result->getFile();

Result Format

An ApiResult object is returned from every API call. If a call is unsuccessful then an exception will be thrown with a message containing the result of failure.

Additional attributes include the total data usage out, and the cost for the API call, typically very small fractions of a penny.

$file = $result->getFile();
$cost = $result->getCost();
$mbOut = $result->getMbOut();
$seconds = $result->getSeconds();
$responseId = $result->getResponseId();

wkhtmltopdf

Convert HTML to PDF

$result = $apiClient->wkHtmlToPdf('<p>Hello, World</p>');

Convert HTML to PDF (load PDF in browser window and specify a file name)

$result = $apiClient->wkHtmlToPdf('<p>Hello, World</p>', $inline = false, $fileName = "test.pdf");

Convert HTML to PDF (use arguments for advanced wkhtmltopdf settings) View full list of wkhtmltopdf options available.

$options = [
    "orientation" => "landscape",
    "pageSize" => "A4"
];
$result = $apiClient->wkHtmlToPdf('<p>Hello, World</p>', $inline = false, $filename = "test.pdf", $options = $options);

Convert URL to PDF

$result = $apiClient->wkUrlToPdf('http://www.api2pdf.com');

Convert URL to PDF (load PDF in browser window and specify a file name)

$result = $apiClient->wkUrlToPdf('http://www.api2pdf.com', $inline = false, $fileName = "test.pdf");

Convert URL to PDF (use arguments for advanced wkhtmltopdf settings) View full list of wkhtmltopdf options available.

$options = [
    "orientation" => "landscape",
    "pageSize" => "A4"
];
$result = $apiClient->wkUrlToPdf('http://www.api2pdf.com', $inline = false, $filename = "test.pdf", $options = $options);

Headless Chrome

Convert HTML to PDF

$result = $apiClient->chromeHtmlToPdf('<p>Hello, World</p>');

Convert HTML to PDF (load PDF in browser window and specify a file name)

$result = $apiClient->chromeHtmlToPdf('<p>Hello, World</p>', $inline = false, $filename = "test.pdf");

Convert HTML to PDF (use arguments for advanced Headless Chrome settings) View full list of Headless Chrome options available.

$options = [
    "landscape" => true
];
$result = $apiClient->chromeHtmlToPdf('<p>Hello, World</p>', $inline = false, $filename = "test.pdf", $options = $options);

Convert URL to PDF

$result = $apiClient->chromeUrlToPdf('http://www.api2pdf.com');

Convert URL to PDF (load PDF in browser window and specify a file name)

$result = $apiClient->chromeUrlToPdf('http://www.api2pdf.com', $inline = false, $filename = "test.pdf");

Convert URL to PDF (use arguments for advanced Headless Chrome settings) View full list of Headless Chrome options available.

$options = [
    "landscape" => true
];
$result = $apiClient->chromeUrlToPdf('http://www.api2pdf.com', $inline = false, $filename = "test.pdf", $options = $options);

Convert HTML to Image

$result = $apiClient->chromeHtmlToImage('<p>Hello, World</p>');

Convert HTML to Image (load image in browser window and specify a file name)

$result = $apiClient->chromeHtmlToImage('<p>Hello, World</p>', $inline = false, $filename = "test.jpg");

Convert HTML to Image (use arguments for advanced Headless Chrome settings) View full list of Headless Chrome options available.

$options = [
    "fullPage" => true
];
$result = $apiClient->chromeHtmlToImage('<p>Hello, World</p>', $inline = false, $filename = "test.jpg", $options = $options);

Convert URL to Image

$result = $apiClient->chromeUrlToImage('http://www.api2pdf.com');

Convert URL to Image (load image in browser window and specify a file name)

$result = $apiClient->chromeUrlToImage('http://www.api2pdf.com', $inline = false, $filename = "test.jpg");

Convert URL to Image (use arguments for advanced Headless Chrome settings) View full list of Headless Chrome options available.

$options = [
    "fullPage" => true
];
$result = $apiClient->chromeUrlToImage('http://www.api2pdf.com', $inline = false, $filename = "test.jpg", $options = $options);

LibreOffice

Convert any office file to PDF, image file to PDF, email file to PDF, HTML to Word, HTML to Excel, and PDF to HTML. Any file that can be reasonably opened by LibreOffice should be convertible. Additionally, we have an endpoint for generating a thumbnail of the first page of your PDF or Office Document. This is great for generating an image preview of your files to users.

You must provide a url to the file. Our engine will consume the file at that URL and convert it to the PDF.

Convert Microsoft Office Document or Image to PDF

$result = $apiClient->libreOfficeAnyToPdf('https://www.api2pdf.com/wp-content/themes/api2pdf/assets/samples/sample-word-doc.docx');

Thumbnail or Image Preview of a PDF or Office Document or Email file

$result = $apiClient->libreOfficeThumbnail('https://www.api2pdf.com/wp-content/themes/api2pdf/assets/samples/sample-word-doc.docx');

Convert HTML to Microsoft Word or Docx

$result = $apiClient->libreOfficeHtmlToDocx('http://www.api2pdf.com/wp-content/uploads/2021/01/sampleHtml.html');

Convert HTML to Microsoft Excel or Xlsx

$result = $apiClient->libreOfficeHtmlToXlsx('http://www.api2pdf.com/wp-content/uploads/2021/01/sampleTables.html');

Convert PDF to HTML

$result = $apiClient->libreOfficePdfToHtml('http://www.api2pdf.com/wp-content/uploads/2021/01/1a082b03-2bd6-4703-989d-0443a88e3b0f-4.pdf');

PdfSharp - Merge / Concatenate Two or More PDFs, Add bookmarks to pdfs, add passwords to pdfs

To use the merge endpoint, supply a list of urls to existing PDFs. The engine will consume all of the PDFs and merge them into a single PDF, in the order in which they were provided in the list.

Merge PDFs from list of URLs to existing PDFs

$linksToPdfs = ['https://LINK-TO-PDF', 'https://LINK-TO-PDF'];
$mergeResult = $apiClient->pdfsharpMerge($linksToPdfs);

Add bookmarks to existing PDF

$linkToPdf = 'https://LINK-TO-PDF';
$bookmarks = [
    [ "Page" => 0, "Title" => "Introduction" ],
    [ "Page" => 1, "Title" => "Second page" ] 
];
$bookmarkResult = $apiClient->pdfsharpAddBookmarks($linkToPdf, $bookmarks);

Add password to existing PDF

$linkToPdf = 'https://LINK-TO-PDF';
$userpassword = 'hello';
$bookmarkResult = $apiClient->pdfsharpAddPassword($linkToPdf, $userpassword);

Helper Methods

delete($responseId)

By default, Api2Pdf will delete your generated file 24 hours after it has been generated. For those with high security needs, you may want to delete your file on command. You can do so by making an DELETE api call with the responseId attribute that was returned on the original JSON payload.

$result = $apiClient->chromeHtmlToPdf("<p>Hello World</p>");
$responseId = $result->getResponseId();
//delete pdf
$apiClient->utilityDelete($responseId);

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

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?

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

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?

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?

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

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).

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()

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.

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

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.

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.