PHPackages                             pdfkong/pdfkong-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. pdfkong/pdfkong-laravel

ActiveLibrary

pdfkong/pdfkong-laravel
=======================

A simple and clean Laravel package for the PDFKong API.

v1.0.1(1mo ago)02↓66.7%MITPHPPHP ^8.0

Since Jul 18Pushed 1mo agoCompare

[ Source](https://github.com/salaheldeen911/KongSDK)[ Packagist](https://packagist.org/packages/pdfkong/pdfkong-laravel)[ RSS](/packages/pdfkong-pdfkong-laravel/feed)WikiDiscussions main Synced 2w ago

READMEChangelogDependencies (4)Versions (3)Used By (0)

PDFKong Laravel SDK
===================

[](#pdfkong-laravel-sdk)

A simple, fluent, and powerful Laravel package for interacting with the **PDFKong API**. Convert URLs, HTML, Office documents, and Markdown into high-quality PDF files with ease.

📚 **PDFKong Documentation:**

🚀 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require pdfkong/pdfkong-laravel
```

Publish the configuration file:

```
php artisan vendor:publish --tag=pdfkong-config
```

⚙️ Configuration
----------------

[](#️-configuration)

After publishing, you'll find the configuration file at `config/pdfkong.php`. Add your PDFKong API credentials to your `.env` file:

```
PDFKONG_API_KEY="your-api-key-here"
PDFKONG_BASE_URL="https://pdfkong.online/api/v1"

# Optional Settings
PDFKONG_STORE_FILE=true # Set to true to retain generated PDFs on the server for 24 hours
PDFKONG_TIMEOUT=30 # Timeout for API requests in seconds
```

📖 Basic Usage
-------------

[](#-basic-usage)

You can use the `PDFKong` facade anywhere in your Laravel application.

### 1. Convert URL to PDF

[](#1-convert-url-to-pdf)

```
use PDFKong\Facades\PDFKong;

PDFKong::url('https://google.com')
    ->save(storage_path('app/public/google.pdf'));
```

### 2. Convert HTML to PDF

[](#2-convert-html-to-pdf)

```
use PDFKong\Facades\PDFKong;

$htmlContent = 'Hello, PDFKong!This is generated from raw HTML.';

$pdfBytes = PDFKong::html($htmlContent)
    ->margins('20px', '20px', '20px', '20px')
    ->getAsBytes(); // Returns raw PDF string, perfect for returning to the browser

return response($pdfBytes, 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'inline; filename="hello.pdf"'
]);
```

### 3. Convert Office Documents (Word, Excel, PPT) to PDF

[](#3-convert-office-documents-word-excel-ppt-to-pdf)

```
use PDFKong\Facades\PDFKong;

PDFKong::office(storage_path('app/documents/invoice.docx'))
    ->save(storage_path('app/public/invoice.pdf'));
```

### 4. Convert Markdown to PDF

[](#4-convert-markdown-to-pdf)

```
use PDFKong\Facades\PDFKong;

PDFKong::markdown('# Title \n\n This is a **markdown** text.')
    ->save(storage_path('app/public/markdown.pdf'));
```

### 5. Convert Image to PDF

[](#5-convert-image-to-pdf)

```
use PDFKong\Facades\PDFKong;

PDFKong::image(storage_path('app/images/photo.jpg'))
    ->save(storage_path('app/public/photo.pdf'));
```

---

🎨 Formatting and Customization
------------------------------

[](#-formatting-and-customization)

The SDK provides fluent methods to customize your PDF output easily.

### Margins and Page Size

[](#margins-and-page-size)

```
PDFKong::url('https://example.com')
    ->margins('10px', '10px', '10px', '10px')
    ->customSize('8.5in', '11in') // e.g. Custom width and height
    ->save('output.pdf');
```

### Authentication and Location Emulation

[](#authentication-and-location-emulation)

If you are converting a webpage that requires Basic HTTP Authentication or specific geolocation:

```
PDFKong::url('https://restricted-area.com')
    ->httpAuth('username', 'password')
    ->location(30.0444, 31.2357, 100) // Lat, Lng, Accuracy
    ->save('output.pdf');
```

### Watermarks

[](#watermarks)

You can secure your documents by adding Text or Image watermarks:

**Text Watermark:**

```
PDFKong::url('https://example.com')
    ->withTextWatermark('CONFIDENTIAL', 48, '#FF0000', 30) // Text, Font Size, Color, Opacity (0-100)
    ->save('output.pdf');
```

**Image Watermark:**

```
PDFKong::url('https://example.com')
    ->withImageWatermark('https://your-domain.com/logo.png', '200px', '200px', 20)
    ->save('output.pdf');
```

---

🚀 Advanced Delivery (Asynchronous)
----------------------------------

[](#-advanced-delivery-asynchronous)

If you are processing large files, you might want to offload the delivery using **Webhooks** or **Amazon S3**, so your server doesn't have to wait.

*Note: Calling `deliverToWebhook()` or `deliverToS3()` will automatically enable the `async` parameter in the background, making the API return immediately.*

### Deliver via Webhook

[](#deliver-via-webhook)

If you set `PDFKONG_WEBHOOK_URL` in your `.env`, the package will deduce the URL automatically:

```
PDFKong::url('https://example.com')
    ->deliverToWebhook() // Reads default from config, or pass a custom URL here
    ->send(); // Use send() instead of save() to avoid downloading bytes. It will return a JSON with a task_id immediately.
```

### Deliver via Amazon S3

[](#deliver-via-amazon-s3)

Ensure your S3 credentials are set in `.env` (like `PDFKONG_S3_BUCKET`).

```
PDFKong::url('https://example.com')
    ->deliverToS3() // Uploads directly to your configured S3 Bucket
    ->send(); // Returns JSON with task_id immediately.
```

### Deliver via Google Cloud Storage

[](#deliver-via-google-cloud-storage)

Ensure your GCP credentials are set in `.env` (like `PDFKONG_GCP_BUCKET`).

```
PDFKong::url('https://example.com')
    ->deliverToGoogleStorage() // Uploads directly to your configured GCS Bucket
    ->send();
```

### Deliver via Base64

[](#deliver-via-base64)

The API supports returning the PDF as a Base64 string directly inside the JSON response. You can use the `returnAsBase64()` method to trigger this.

```
// Get PDF as a Base64 String
$response = PDFKong::url('https://example.com')
    ->returnAsBase64()
    ->send();

echo $response['base64_data']; // Contains the raw base64 string
```

### Manual Async Mode

[](#manual-async-mode)

If you want to run the job asynchronously without using Webhooks or S3 (perhaps you want to poll the status manually using `batchStatus` or checking the file later), you must explicitly tell the API to store the file on its server:

```
PDFKong::url('https://example.com')
    ->async() // Forces the API to process this in the background
    ->storeFile() // Required when using async without Webhook/S3
    ->send();
```

---

---

🛠️ Management &amp; Utility Methods
-----------------------------------

[](#️-management--utility-methods)

The SDK also supports the management endpoints available in the API, allowing you to check usage, manage generated PDFs, and handle batch downloads.

```
use PDFKong\Facades\PDFKong;

// 1. Get Account Usage & Limits
$usage = PDFKong::usage();
print_r($usage);

// 2. List previously generated PDFs (Pagination: page, per_page)
$list = PDFKong::list(1, 15);

// 3. Remove a specific PDF from the server
$removed = PDFKong::remove('task_uuid_here');

// 4. Check the status of an asynchronous batch job
$status = PDFKong::batchStatus('batch_uuid_here');

// 5. Download a completed batch job (e.g. ZIP file)
PDFKong::batchDownload('batch_uuid_here', storage_path('app/public/batch_output.zip'));
```

---

🔧 Magic Methods for Extra Parameters
------------------------------------

[](#-magic-methods-for-extra-parameters)

If the API supports a new parameter (e.g., `prefer_css_page_size` or `print_background`), you can call it using camelCase. The SDK will automatically convert it to `snake_case` for the API. 📚 **View all supported parameters here:**

```
PDFKong::url('https://example.com')
    ->printBackground(true) // Maps to 'print_background' => true
    ->landscape()           // Maps to 'landscape' => true (if no arg provided, defaults to true)
    ->emulateMedia('screen') // Maps to 'emulate_media' => 'screen'
    ->save('output.pdf');
```

🛡️ Enterprise Features
----------------------

[](#️-enterprise-features)

We've built this SDK to be robust and ready for large-scale applications.

### 1. Testing (Fake)

[](#1-testing-fake)

When writing your tests, you shouldn't hit the real API. Use `PDFKong::fake()` to mock the SDK.

```
use PDFKong\Facades\PDFKong;

PDFKong::fake();

// Run your application code...
PDFKong::url('https://example.com')->save('test.pdf');

// Assert that a conversion was requested
PDFKong::assertConverted('url');
```

### 2. Auto-Retry Mechanism

[](#2-auto-retry-mechanism)

Network instability happens. You can tell the SDK to automatically retry failed requests:

```
PDFKong::url('https://example.com')
    ->retry(3, 100) // Retry up to 3 times, with a 100ms delay between attempts
    ->save('output.pdf');
```

### 3. Custom Guzzle/HTTP Options

[](#3-custom-guzzlehttp-options)

If your server sits behind a proxy, or you need to disable SSL verification locally, you can pass custom options to the underlying Laravel HTTP Client:

```
PDFKong::url('https://example.com')
    ->withOptions(['verify' => false, 'proxy' => 'http://localhost:8080'])
    ->save('output.pdf');
```

### 4. Custom Exceptions

[](#4-custom-exceptions)

The SDK throws specific exceptions based on the HTTP status code, allowing you to catch and handle them gracefully:

- `PDFKongAuthenticationException` (401/403)
- `PDFKongInsufficientCreditsException` (402)
- `PDFKongValidationException` (422)
- `PDFKongRateLimitException` (429)
- `PDFKongException` (General)

```
use PDFKong\Exceptions\PDFKongInsufficientCreditsException;

try {
    PDFKong::url('https://example.com')->save('output.pdf');
} catch (PDFKongInsufficientCreditsException $e) {
    // Notify user to top up balance
}
```

### 5. Type-Safe Enums

[](#5-type-safe-enums)

Instead of using raw strings for parameters, you can use the provided Enums for type safety:

```
use PDFKong\Enums\PageSize;
use PDFKong\Enums\DeliveryMode;

PDFKong::url('https://example.com')
    ->deliveryMode(DeliveryMode::S3->value)
    ->pageFormat(PageSize::A4->value)
    ->send();
```

---

📊 Available API Parameters Reference
------------------------------------

[](#-available-api-parameters-reference)

Below is a quick reference table of core parameters supported by the API.

ParameterTypeDefaultDescription`mode`string*required*Source type: `url`, `html`, `office`, `markdown`, `image` *(Set automatically by SDK)*`url`stringnullThe webpage URL to convert (If `mode=url`).`html`stringnullRaw HTML string to convert (If `mode=html`).`markdown`stringnullRaw Markdown to convert (If `mode=markdown`).`margin_top` / `bottom` / `right` / `left`string`0px`Page margins (e.g. `10px`, `0.5in`, `1cm`).`page_size`string`A4`Page format: `A4`, `Letter`, `Legal`, `Custom`, etc.`landscape`boolean`false`Set to true to print in landscape orientation.`print_background`boolean`true`Print background graphics and colors.`emulate_media`string`print`CSS media emulation: `print` or `screen`.`store_file`boolean`false`Keeps the generated file on PDFKong servers for 24 hours.`delivery_mode`string`json`Where to deliver the output: `json`, `webhook`, `s3`, `base64`, `google_storage`, `inline`, `attachment``watermark`boolean`false`Enables watermarking if set to true.`watermark_text`stringnullThe text used for watermarking.`watermark_img`stringnullURL of the image used for watermarking.*(Note: Use the magic methods or the `->with('key', 'value')` method to pass any extra parameters directly).*

📄 License
---------

[](#-license)

The MIT License (MIT).

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance90

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

46d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/68305647?v=4)[Salah Eldeen](/maintainers/salaheldeen911)[@salaheldeen911](https://github.com/salaheldeen911)

---

Top Contributors

[![salaheldeen911](https://avatars.githubusercontent.com/u/68305647?v=4)](https://github.com/salaheldeen911 "salaheldeen911 (7 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/pdfkong-pdfkong-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/pdfkong-pdfkong-laravel/health.svg)](https://phpackages.com/packages/pdfkong-pdfkong-laravel)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3365.5M359](/packages/psalm-plugin-laravel)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

80732.6M276](/packages/laravel-mcp)[illuminate/auth

The Illuminate Auth package.

10528.8M1.4k](/packages/illuminate-auth)[illuminate/routing

The Illuminate Routing package.

1419.6M3.8k](/packages/illuminate-routing)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45945.2k1](/packages/pressbooks-pressbooks)[api-platform/laravel

API Platform support for Laravel

58190.1k22](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
