How to Generate PDF in Drupal 10 (2025) – Easy Step-by-Step Guide

🔥 How to Generate PDF in Drupal 10 (2024) – Easy Step-by-Step Guide

🔥 How to Generate PDF in Drupal 10 (2024) – Easy Step-by-Step Guide

Want to create **PDFs in Drupal 10**? This step-by-step guide will help you implement **PDF generation** using **dompdf** quickly. 🚀

✅ Step 1: Install DomPDF Library

Run this command inside your Drupal project root:

composer require dompdf/dompdf

✅ Step 2: Install Required Dependencies

Install font support:

composer require phenx/php-font-lib

✅ Step 3: Create a Custom Drupal Module

Create a folder:

mkdir -p modules/custom/pdf_generator

✅ Step 4: Create Module Info File

Create pdf_generator.info.yml inside the module folder:

name: 'PDF Generator'
type: module
description: 'A custom module to generate PDFs in Drupal.'
core_version_requirement: ^10 || ^9
package: Custom
dependencies:
  - dompdf/dompdf

✅ Step 5: Create a PDF Controller

Create modules/custom/pdf_generator/src/Controller/PDFGeneratorController.php:

<?php

namespace Drupal\pdf_generator\Controller;

use Dompdf\Dompdf;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

class PDFGeneratorController {
    public function generatePDF() {
        $dompdf = new Dompdf();
        $html = '
            <h1 style="color:blue; text-align:center;">Drupal PDF Generation</h1>
            <p>This is a sample PDF generated in Drupal using DomPDF.</p>
        ';
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        
        $response = new Response($dompdf->output());
        $response->headers->set('Content-Type', 'application/pdf');
        $response->headers->set('Content-Disposition', ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'sample.pdf');

        return $response;
    }
}

✅ Step 6: Define Routing

Create pdf_generator.routing.yml:

pdf_generator.download:
  path: '/generate-pdf'
  defaults:
    _controller: 'Drupal\pdf_generator\Controller\PDFGeneratorController::generatePDF'
    _title: 'Download PDF'
  requirements:
    _permission: 'access content'

✅ Step 7: Enable the Module

Enable your module:

drush en pdf_generator -y

✅ Step 8: Test Your PDF Generation

Run the local Drupal server:

drush serve

Visit:

http://your-drupal-site.com/generate-pdf

A **sample.pdf** file will be downloaded! 🎉

🚀 Conclusion

By following this guide, you have successfully implemented **PDF generation** in **Drupal 10** using **dompdf**.

🔗 Visit Developer Sahayak

0 Comments