Using Paged.js with Laravel

Setting Up a Laravel Project

First, make sure you have PHP and Composer installed. Then create a new Laravel project:

composer create-project laravel/laravel my-amazing-project
cd my-amazing-project

Here is the official documentation.

Create a new View

In Laravel, views are stored in resources/views and use the Blade templating engine. We can then use controllers to pass data to these views, which generate dynamic HTML for the user's browser.

Let's create a new file named magazine.blade.php in the resources/views directory with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Magazine</title>
</head>
<body>
    <div class="content">
        <h1 class="main-title">Doppio Magazine</h1>
        <section class="page" id="first-page">
            <h2 class="title">Chapter 1</h2>
            <p class="text">This is the content of the first page.</p>
        </section>
        <!-- More sections... -->
    </div>
</body>
</html>

Install PagedJS via a CDN

Paged.js can be integrated into a Laravel project in three main ways: using a CDN, installing via NPM (or Yarn), or downloading the library manually. Including it via a CDN is the simplest method. We just have to include the following script in our view:

<script src="https://unpkg.com/pagedjs/dist/paged.polyfill.js"></script>

Styling the Page

To style a page using Paged.js, we can apply CSS rules to define layout and appearance. Let's design our magazine style! In the /public/css folder, we have to create a magazine.css file:

.content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 2rem 4rem;
}
.page { break-after: page; }
h1 { text-align: center; color: #5935dd; }
h2 { text-align: center; color: #3c3c3c; }
p { text-align: center; color: #a1a1a1; }

Configure the Route

Next, we need to set up a route to handle the display of our magazine view. Open routes/web.php and add:

Route::get('/magazine', function () {
    return view('magazine');
});

Display custom content through "named strings"

What if we want to display the name of the chapter at the bottom of the PDF? Let's use the specific Paged.js CSS features:

@page {
  @bottom-center { content: string(title); }
}
.chapter > h2 {
  string-set: title content(text);
}

The first block tells PagedJS to add content in the margin of the PDF, at the bottom center position. The second block makes available the title of the chapter to PagedJS using named strings.

Generate PDFs

Now that you have created a webpage that displays as a PDF using Paged.js, you can easily generate PDF files out of this page using Doppio.

What's next?

Be sure to check out the Paged.js documentation to see all the features available and how you can use them to render beautiful PDFs!

Using Paged.js with Laravel