Skip to content

Commit 809ac29

Browse files
committed
RenderPDF.io PHP Library
0 parents  commit 809ac29

File tree

13 files changed

+504
-0
lines changed

13 files changed

+504
-0
lines changed

.editorconfig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
; This file is for unifying the coding style for different editors and IDEs.
2+
; More information at http://editorconfig.org
3+
4+
root = true
5+
6+
[*]
7+
charset = utf-8
8+
indent_size = 4
9+
indent_style = space
10+
end_of_line = lf
11+
insert_final_newline = true
12+
trim_trailing_whitespace = true
13+
14+
[*.md]
15+
trim_trailing_whitespace = false
16+
17+
[composer.json]
18+
indent_size = 4
19+
indent_style = space

.github/renderpdf-io-cover.png

86.3 KB
Loading

.github/workflows/build.yml

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
name: Unit Test
2+
3+
on:
4+
pull_request:
5+
branches:
6+
- 'main'
7+
types: [ opened, synchronize, reopened, ready_for_review ]
8+
push:
9+
branches:
10+
- 'main'
11+
12+
jobs:
13+
unit:
14+
strategy:
15+
fail-fast: false
16+
matrix:
17+
version: ['8.1', '8.2', '8.3', '8.4']
18+
runs-on: ubuntu-latest
19+
steps:
20+
- uses: actions/checkout@v3
21+
if: success()
22+
23+
- name: Setup PHP with coverage driver
24+
uses: shivammathur/setup-php@v2
25+
with:
26+
php-version: ${{ matrix.version }}
27+
coverage: pcov
28+
29+
- name: Setup
30+
if: success()
31+
run: |
32+
composer install --no-interaction
33+
34+
- name: PHPUnit tests with coverage
35+
if: success()
36+
run: |
37+
composer test-coverage
38+
39+
- name: upload coverage to codecov.io
40+
if: success() && matrix.version == '8.3'
41+
uses: codecov/codecov-action@v3
42+
with:
43+
token: ${{ secrets.CODECOV_TOKEN }}
44+
file: ./coverage.xml

.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/vendor/
2+
node_modules/
3+
.phpunit.result.cache
4+
.idea/
5+
.php-cs-fixer.cache
6+
.phpunit.cache
7+
composer.lock

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 RenderPDF.io, a product of ShipSaaS Integration System LLC
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Render HTML to PDF for PHP - RenderPDF.io PHP Library
2+
3+
4+
![RenderPDF.io Cover](./.github/renderpdf-io-cover.png)
5+
6+
[RenderPDF.io](https://renderpdf.io) provides awesome & developer-friendly APIs to convert HTML to PDF.
7+
8+
This is a PHP library for RenderPDF.io that provides an easy way to integrate for PHP users.
9+
10+
If you're a Laravel users, check out this: [RenderPDF.io for Laravel](https://github.com/renderpdf-io/renderpdf-laravel)
11+
12+
## Requirement
13+
- PHP 8.1 and above
14+
15+
## Installation
16+
17+
```bash
18+
composer install renderpdf-io/renderpdf-php
19+
```
20+
21+
## Usage
22+
23+
```php
24+
use RenderPdfIoPhp\RenderPdfIoService;
25+
use RenderPdfIoPhp\RenderPdfOptions;
26+
27+
$renderPdfIoService = RenderPdfIoService::make("YOUR_API_KEY_HERE");
28+
29+
$fileUrl = $renderPdfIoService->render(new RenderPdfOptions(
30+
htmlContent: 'Hello world',
31+
headerHtmlContent: 'Welcome to RenderPdf.io - PHP Library',
32+
footerHtmlContent: 'We love you'
33+
));
34+
35+
$isQueued = $renderPdfIoService->renderAsync(new RenderPdfOptions(
36+
htmlContent: 'Render this in async flow please',
37+
));
38+
39+
// if there are any errors, a RenderPdfIoException will be thrown
40+
```
41+
42+
See all the available options here: [RenderPdfOptions.php](./src/RenderPdfOptions.php)
43+
44+
## Contributing
45+
46+
Thank you for your consideration to contribute to PHP library of RenderPDF.io, please feel free to:
47+
48+
- Open an issue for bug reports.
49+
- Submit a PR for improvements/enhancements.
50+
51+
## License
52+
This library is free to use, under [MIT License](./LICENSE).

composer.json

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
{
2+
"name": "renderpdf-io/renderpdf-php",
3+
"type": "library",
4+
"version": "1.0.0",
5+
"description": "Render and covert HTML to PDF using RenderPDF.io service, library for PHP",
6+
"keywords": [
7+
"php library",
8+
"php convert html to pdf",
9+
"php render html to pdf",
10+
"html to pdf",
11+
"renderpdf",
12+
"renderpdf.io",
13+
"php"
14+
],
15+
"license": "MIT",
16+
"require": {
17+
"php": "^8.1",
18+
"guzzlehttp/guzzle": "^7.8"
19+
},
20+
"require-dev": {
21+
"mockery/mockery": "^1.6",
22+
"phpunit/phpunit": "^10",
23+
"phpunit/php-code-coverage": "^10"
24+
},
25+
"autoload": {
26+
"psr-4": {
27+
"RenderPdfIoPhp\\": "src/"
28+
},
29+
"files": []
30+
},
31+
"autoload-dev": {
32+
"psr-4": {
33+
"RenderPdfIoPhp\\Tests\\": "tests/"
34+
}
35+
},
36+
"scripts": {
37+
"test-coverage": [
38+
"@php vendor/bin/phpunit --coverage-clover coverage.xml"
39+
],
40+
"test": [
41+
"@php vendor/bin/phpunit"
42+
]
43+
},
44+
"minimum-stability": "dev",
45+
"prefer-stable": true
46+
}

phpunit.xml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" bootstrap="vendor/autoload.php" colors="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
3+
<testsuites>
4+
<testsuite name="RenderPDFio PHP Test Suite">
5+
<directory suffix=".php">./tests/</directory>
6+
<exclude>./tests/TestCase.php</exclude>
7+
</testsuite>
8+
</testsuites>
9+
<php>
10+
<ini name="memory_limit" value="-1"/>
11+
</php>
12+
<source>
13+
<include>
14+
<directory suffix=".php">./src</directory>
15+
</include>
16+
</source>
17+
</phpunit>

src/RenderPdfIoException.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
namespace RenderPdfIoPhp;
4+
5+
use GuzzleHttp\Exception\ClientException;
6+
use RuntimeException;
7+
use Throwable;
8+
9+
class RenderPdfIoException extends RuntimeException
10+
{
11+
public static function fromException(Throwable $exception): self
12+
{
13+
if ($exception instanceof ClientException) {
14+
return match ($exception->getCode()) {
15+
422 => self::forValidationErrors(
16+
json_decode((string) $exception->getResponse()->getBody(), true)
17+
),
18+
429 => self::forRateLimited(),
19+
default => self::forGeneric($exception),
20+
};
21+
}
22+
23+
return self::forGeneric($exception);
24+
}
25+
26+
public static function forGeneric(?Throwable $previous = null): self
27+
{
28+
return new self('Failed to render your PDF file', previous: $previous);
29+
}
30+
31+
public static function forValidationErrors(array $errorsBag): self
32+
{
33+
$firstErrors = array_shift($errorsBag['errors']);
34+
35+
return new self($firstErrors[0]);
36+
}
37+
38+
public static function forRateLimited(): self
39+
{
40+
return new self('You have exceeded the API usage for the current minute.');
41+
}
42+
43+
public static function forMissingIdentifierForAsyncFlow(): self
44+
{
45+
return new self('You must set an unique identifier when using the async mode.');
46+
}
47+
}

src/RenderPdfIoService.php

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
<?php
2+
3+
namespace RenderPdfIoPhp;
4+
5+
use GuzzleHttp\Client;
6+
use Throwable;
7+
8+
class RenderPdfIoService
9+
{
10+
public function __construct(
11+
/**
12+
* Your RenderPDF.io API Key
13+
*
14+
* Get one here
15+
* @see https://renderpdf.io/app/api-keys
16+
*/
17+
protected readonly string $apiKey,
18+
19+
/**
20+
* Don't set this param on your own, we do this to help us to write Unit Tests
21+
*
22+
* @internal
23+
*/
24+
protected ?Client $customClient = null
25+
) {
26+
}
27+
28+
public static function make(string $apiKey): self
29+
{
30+
return new self($apiKey);
31+
}
32+
33+
/**
34+
* Convert HTML to PDF file using sync mode
35+
*
36+
* @param RenderPdfOptions $options
37+
*
38+
* @return string
39+
*
40+
* @throws RenderPdfIoException on errors (validation, generic)
41+
*/
42+
public function render(RenderPdfOptions $options): string
43+
{
44+
try {
45+
$res = $this->createHttpClient()
46+
->post('render-sync', [
47+
'json' => $options->toRequestData(),
48+
]);
49+
50+
$body = json_decode((string) $res->getBody(), true);
51+
52+
return $body['fileUrl'];
53+
} catch (Throwable $exception) {
54+
throw RenderPdfIoException::fromException($exception);
55+
}
56+
}
57+
58+
/**
59+
* Convert HTML to PDF file using sync mode
60+
* @note you need to create a webhook URL before using this mode https://renderpdf.io/app/webhooks
61+
*
62+
* @param RenderPdfOptions $options
63+
*
64+
* @return bool true on success
65+
*
66+
* @throws RenderPdfIoException on errors (validation, generic)
67+
*/
68+
public function renderAsync(RenderPdfOptions $options): bool
69+
{
70+
if (!$options->identifier) {
71+
throw RenderPdfIoException::forMissingIdentifierForAsyncFlow();
72+
}
73+
74+
try {
75+
$res = $this->createHttpClient()
76+
->post('render-sync', [
77+
'json' => $options->toRequestData(),
78+
]);
79+
80+
$body = json_decode((string) $res->getBody(), true);
81+
82+
return $body['outcome'] === 'SUCCESS';
83+
} catch (Throwable $exception) {
84+
throw RenderPdfIoException::fromException($exception);
85+
}
86+
}
87+
88+
protected function createHttpClient(): Client
89+
{
90+
return $this->customClient ?? new Client([
91+
'base_uri' => 'https://renderpdf.io/api/pdfs',
92+
'headers' => [
93+
'Authorization' => 'Bearer ' . $this->apiKey,
94+
'User-Agent' => 'RenderPdfIoHTTP/1.0',
95+
'Content-Type' => 'application/json',
96+
],
97+
]);
98+
}
99+
}

0 commit comments

Comments
 (0)