One of the ways to present your work is to create a portfolio. In this article, we will create a PDF portfolio with your branding from photos you upload to Cloudinary with a specific tag for instance “Wedding”.
Let’s get started.
The final project can be viewed on PHPSandbox and the entire source code is available on my Github repository.
Using Cloudinary in your Laravel projects is pretty straightforward. However, for you to be able to easily follow along, you need to have a good command of your terminal, Git, and entry knowledge of PHP specifically with the Laravel framework.
Being that Laravel is a PHP Framework, we will need Composer. Like any modern PHP framework, Laravel uses Composer to manage its dependencies. Before, we can start ensure you have Composer installed on your machine. Follow step 1 below to install Composer and PHP.
your development or production machine.
-
Install Laravel
-
Via Composer:
composer create-project --prefer-dist laravel/laravel cloudinary-branded-pdf
- Via Laravel Installer
composer global require laravel/installer
laravel new cloudinary-branded-pdf
- In step 2 above we have installed the Laravel Installer and used it to scaffold a new application in the
folder cloudinary-branded-pdf
. With Laravel installed, we should be able to start and test the server ensuring
everything is okay. Change the directory to the project folder and run the local development server by typing the
following commands:
cd cloudinary-branded-pdf
php artisan serve
The Laravel project is now up and running. When you open http://localhost:8000
on your computer, you should see the
image below:
We will be using Cloudinary to generate multi-paged PDFs from images we will tag and upload. We will also perform the
overlay transformation to add a watermark to each of the pages. Sounds fun, we will start by creating a
free Cloudinary account.
- Sign up for a free Cloudinary account then navigate to the Console page and take note of your Cloud name, API Key and
API Secret.
- Install Cloudinary’s Laravel SDK:
composer require cloudinary-labs/cloudinary-laravel
Note: Please ensure you follow all the steps in the #Installation section. Publish the configuration file and add
the Cloudinary credentials you noted in Step 1 to the .env
file.
CLOUDINARY_API_KEY=YOUR_CLOUDINARY_API_KEY
CLOUDINARY_API_SECRET=YOUR_CLOUDINARY_API_SECRET
CLOUDINARY_CLOUD_NAME=YOUR_CLOUDINARY_CLOUD_NAME
We will use Cloudinary’s Upload API with the multi
method which will take the images we upload, apply transformations and convert them to a PDF document.
To generate a PDF document we will need a user interface, we will use the Laravel package Livewire to build this.
- Install Livewire Package by running the following command in your Laravel project:
composer require livewire/livewire
- Include Livewire scripts and styles on every page that will be using Livewire. In our case
welcome.blade.php
:
...
@livewireStyles
</head>
<body>
...
@livewireScripts
</body>
</html>
Code language: HTML, XML (xml)
- We will then create a Livewire Component to handle our image uploads:
php artisan make:livewire MultipleFileUpload
This will create two files, first app/Http/Livewire/MultipleFileUpload.php
and the other one
in resources/views/livewire/multiple-file-upload.blade.php
Now you can use this component anywhere in your Laravel project using the following snippet:
<livewire:multiple-file-upload/>
or
@livewire('multiple-file-upload')
- Open
resources/views/welcome.blade.php
and add the following code within the<body></body>
tags as shown below:
<body class="antialiased">
<div>
@livewire('multiple-file-upload')
</div>
</body>
Code language: HTML, XML (xml)
This includes the Livewire component we created earlier in our welcome.blade.php
.
Note: Please ensure you go through the Livewire documentation,
to learn how to install and set it up.
- Open the file
resources/views/livewire/multiple-file-upload.blade.php
and populate it with the following code:
<form class="mb-5" wire:submit.prevent="uploadImages">
<div class="form-group row mt-5 mb-3">
<div class="input-group mb-5">
<input id="watermark" type="file" class="form-control @error('watermark') is-invalid @enderror"
placeholder="Choose files..." wire:model="watermark">
<label class="input-group-text" for="media">
Choose watermark...
</label>
@error('watermark')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">#</span>
<input class="form-control @error('tag') is-invalid @enderror" placeholder="Portfolio Tag"
aria-label="Portfolio Tag"
aria-describedby="basic-addon1" wire:model="tag">
@error('tag')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="input-group">
<input id="files" type="file" class="form-control @error('files'|'files.*') is-invalid @enderror"
placeholder="Choose files..." wire:model="files" multiple>
<label class="input-group-text" for="files">
Choose images for portfolio...
</label>
@error('files'|'files.*')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<small class="text-muted text-center mt-2" wire:loading wire:target="files">
{{ __('Uploading') }}…
</small>
<small class="text-muted text-center mt-2" wire:loading wire:target="watermark">
{{ __('Uploading') }}…
</small>
</div>
<div class="text-center">
<button type="submit" class="btn btn-sm btn-primary w-25">
<i class="fas fa-check mr-1"></i> {{ __('Generate PDF') }}
<i class="spinner-border spinner-border-sm ml-1 mt-1" wire:loading wire:target="uploadImages"></i>
</button>
</div>
</form>
Code language: HTML, XML (xml)
This is our Livewire Component view, this basically will display a form with inputs for our watermark, tag, images
files and a button.
You will see the implementation in code shortly.
Open the file app/Http/Livewire/MultipleFileUpload.php
. Here, we are going to add a method that will handle the
multiple files selected by the user, upload them to Cloudinary and save their public_id
’s in an array that we will use
later on.
Add the following code to this file.
- First, we use Livewires
WithFileUploads
to help us with file uploads, then create two variables$media
and $optimizedImage
which is an array that will contain the image URLs we get back from Cloudinary.
use WithFileUploads;
public $files = [];
public $watermark;
public $tag;
Code language: PHP (php)
- Secondly, we will create the
uploadImages
function which will upload the watermark and image files
to Cloudinary. Cloudinary will apply specific transformations to each one of the images that will make the pages before generating the PDF document.
public function uploadImages() {
...
}
Code language: PHP (php)
- Let’s populate our method in step 2 above:
public function uploadImages() {
$this->validate([
'files' => [
'required',
'max:10240'
],
'files.*' => 'mimes:jpeg,jpg,png',
'watermark' => [
'required',
'image',
'mimes:png',
'max:100'
],
'tag' => [
'required',
'string',
'max:20'
],
]);
$watermarkPublicId = cloudinary()->upload($this->watermark->getRealPath(), [
'folder' => 'branded-pdf',
'public_id' => 'watermark',
])->getPublicId();
foreach ($this->files as $file) {
cloudinary()->upload($file->getRealPath(), [
'folder' => 'branded-pdf',
'width' => '794',
'height' => '1123',
'gravity' => 'auto',
'crop' => 'fill',
'tags' => ["$this->tag"],
]);
}
cloudinary()->uploadApi()->multi($this->tag, [
'transformation' => [
'overlay' => $watermarkPublicId,
'gravity' => 'north_east',
'x' => 0.02,
'y' => 0.02,
'crop' => 'scale',
'flags' => 'relative',
'width' => 0.15,
'opacity' => 80
],
'format' => 'pdf',
'notification_url' => env('CLOUDINARY_NOTIFICATION_URL')
]);
}
Code language: PHP (php)
Let’s talk about the code.
We upload the watermark to Cloudinary and get the public_id
which we will use later on.
$watermarkPublicId = cloudinary()->upload($this->watermark->getRealPath(), [
'folder' => 'branded-pdf',
'public_id' => 'watermark',
])->getPublicId();
Code language: PHP (php)
We upload the images selected by the user and apply the tag that they specified and some transformations to each one of them using a for loop
.
foreach ($this->files as $file) {
cloudinary()->upload($file->getRealPath(), [
'folder' => 'branded-pdf',
'width' => '794',
'height' => '1123',
'gravity' => 'auto',
'crop' => 'fill',
'tags' => ["$this->tag"],
]);
}
Code language: PHP (php)
Through the Upload API
, the multi-method
allows us to apply transformations and generate the PDF from all the
images with the tag
that we pass to Cloudinary. We do this by specifying the format
as pdf
and applying the
transformations that overlay our watermark on the images with this tag.
cloudinary()->uploadApi()->multi($this->tag, [
'transformation' => [
'overlay' => $watermarkPublicId,
'gravity' => 'north_east',
'x' => 0.02,
'y' => 0.02,
'crop' => 'scale',
'flags' => 'relative',
'width' => 0.15,
'opacity' => 80
],
'format' => 'pdf',
'notification_url' => env('CLOUDINARY_NOTIFICATION_URL')
]);
Code language: PHP (php)
You can check out the reference for full
details on the relevant options.
On the notification_url
we have specified we will receive a response from Cloudinary once our PDF has been
successfully created. The response will be as follows:
{
"url": "http://res.cloudinary.com/dgrpkngjn/image/multi/c_scale,fl_relative,g_north_east,l_branded-pdf:watermark,o_80,w_0.15,x_0.02,y_0.02/f_pdf/v1656857502/Wedding%20Photos.pdf",
"secure_url": "https://res.cloudinary.com/dgrpkngjn/image/multi/c_scale,fl_relative,g_north_east,l_branded-pdf:watermark,o_80,w_0.15,x_0.02,y_0.02/f_pdf/v1656857502/Wedding%20Photos.pdf",
"asset_id": "770deef5d2f1285e39565a1a77ebbe3d",
"public_id": "Wedding Photos,pdf,c_scale,fl_relative,g_north_east,l_branded-pdf:watermark,o_80,w_0.15,x_0.02,y_0.02/f_pdf",
"version": 1656857502,
"notification_type": "multi"
}
Code language: JSON / JSON with Comments (json)
Tip: Please be sure to change your Cloudinary settings to allow delivery of PDFs and ZIP files, this is disabled by default to prevent dthe istribution of malware.
Webhooks are one of a few ways web applications can communicate with each other. We can receive Cloudinary’s responses
through a webhook and run processes that will do something like notify the user or ban the video.
Create a WebhookController.php
by typing the following command:
php artisan make:controller WebhookController
In the file created app/Http/Controllers/WebhookController.php
we will add the following code:
public function cloudinary(Request $request) {
//Verification
$verified = SignatureVerifier::verifyNotificationSignature(json_encode($request), $request->header('X-Cld-Timestamp'), $request->header('X-Cld-Signature'));
// If the signature is verified and moderation is rejected
if ($verified && $request->notification_type === 'multi') {
// Get Secure URL
$secureUrl = $request->secure_url;
// Notify user
...
}
return response('Unverified', 401);
}
Code language: PHP (php)
Tip: A webhook is a mechanism where an application can notify another application that something has happened.
Since the notification from Cloudinary will be an external request we will need to allow it through the VerifyCsrfToken.php
middleware to prevent CSRF errors.
...
protected $except = [
'webhooks'
];
}
Code language: PHP (php)
Next, we will create the webhook route in routes/api.php
.
...
//webhooks client
Route::post('webhooks/cloudinary', [WebhookController::class, 'cloudinary']);
Code language: PHP (php)
And finally, update our CLOUDINARY_NOTIFICATION_URL
in the environment variables file .env
as follows:
CLOUDINARY_NOTIFICATION_URL=https://<app_url>/api/webhooks/cloudinary
Code language: HTML, XML (xml)
Finally, we can see the results:
Cloudinary makes it easy to generate a PDF by automating and applying some transformations. We can use this to create portfolios which we can then present to our clients.
The possibilities are endless, check out Cloudinary for your A to Z media management – upload, storage, administration, manipulation, optimization, and delivery.
Get started with Cloudinary in your Laravel projects for FREE!