Generate PDFs in Laravel with Mpdf.

Overview

Laravel Mpdf: Using Mpdf in Laravel for generate Pdfs

Easily generate PDF documents from HTML right inside of Laravel using this mpdf wrapper.

Important Notes

Currently supported mpdf version 8.0 with FPDF version 2 and PHP version >= 7.0. MPDF documentation

mPDF will timeout on fetching external HTTP resources when using single-threaded servers such as php -S or artisan serve. Use a proper webserver for full functionality.

Installation

Require this package in your composer.json

"require": {
	carlos-meneses/laravel-mpdf: "2.1.6"
}

or install it by running:

composer require carlos-meneses/laravel-mpdf

To start using Laravel, add the Service Provider and the Facade to your config/app.php:

'providers' => [
	// ...
	Meneses\LaravelMpdf\LaravelMpdfServiceProvider::class
]
'aliases' => [
	// ...
	'PDF' => Meneses\LaravelMpdf\Facades\LaravelMpdf::class
]

Note: This package supports auto-discovery features of Laravel 5.5+, You only need to manually add the service provider and alias if working on Laravel version lower then 5.5

Basic Usage

To use Laravel Mpdf add something like this to one of your controllers. You can pass data to a view in /resources/views.

//....
use PDF;
class ReportController extends Controller {
	public function generate_pdf()
	{
		$data = [
			'foo' => 'bar'
		];
		$pdf = PDF::loadView('pdf.document', $data);
		return $pdf->stream('document.pdf');
	}
}

Config

You can use a custom file to overwrite the default configuration. Just create config/pdf.php and add this:

return [
	'mode'                     => '',
	'format'                   => 'A4',
	'default_font_size'        => '12',
	'default_font'             => 'sans-serif',
	'margin_left'              => 10,
	'margin_right'             => 10,
	'margin_top'               => 10,
	'margin_bottom'            => 10,
	'margin_header'            => 0,
	'margin_footer'            => 0,
	'orientation'              => 'P',
	'title'                    => 'Laravel mPDF',
	'author'                   => '',
	'watermark'                => '',
	'show_watermark'           => false,
	'watermark_font'           => 'sans-serif',
	'display_mode'             => 'fullpage',
	'watermark_text_alpha'     => 0.1,
	'custom_font_dir'          => '',
	'custom_font_data' 	       => [],
	'auto_language_detection'  => false,
	'temp_dir'                 => rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR),
	'pdfa' 			               => false,
  'pdfaauto' 		             => false,
	'use_active_forms'         => false,
];

To override this configuration on a per-file basis use the fourth parameter of the initializing call like this:

PDF::loadView('pdf', $data, [], [
  'title' => 'Another Title',
  'margin_top' => 0
])->save($pdfFilePath);

Headers and Footers

If you want to have headers and footers that appear on every page, add them to your <body> tag like this:

<htmlpageheader name="page-header">
	Your Header Content
</htmlpageheader>

<htmlpagefooter name="page-footer">
	Your Footer Content
</htmlpagefooter>

Now you just need to define them with the name attribute in your CSS:

@page {
	header: page-header;
	footer: page-footer;
}

Inside of headers and footers {PAGENO} can be used to display the page number.

Included Fonts

By default you can use all the fonts shipped with Mpdf.

Custom Fonts

You can use your own fonts in the generated PDFs. The TTF files have to be located in one folder, e.g. resources/fonts/. Add this to your configuration file (/config/pdf.php):

return [
	'custom_font_dir' => base_path('resources/fonts/'), // don't forget the trailing slash!
	'custom_font_data' => [
		'examplefont' => [
			'R'  => 'ExampleFont-Regular.ttf',    // regular font
			'B'  => 'ExampleFont-Bold.ttf',       // optional: bold font
			'I'  => 'ExampleFont-Italic.ttf',     // optional: italic font
			'BI' => 'ExampleFont-Bold-Italic.ttf' // optional: bold-italic font
		]
		// ...add as many as you want.
	]
];

Now you can use the font in CSS:

body {
	font-family: 'examplefont', sans-serif;
}

Get instance your Mpdf

You can access all mpdf methods through the mpdf instance with getMpdf().

use PDF;

$pdf = PDF::loadView('pdf.document', $data);
$pdf->getMpdf()->AddPage(...);

Chunk HTML

For big HTML you might get Uncaught Mpdf\MpdfException: The HTML code size is larger than pcre.backtrack_limit xxx error, or you might just get empty or blank result. In these situations you can use chunk methods while you added a separator to your HTML:

//....
use PDF;
class ReportController extends Controller {
	public function generate_pdf()
	{
		$data = [
			'foo' => 'hello 1',
            'bar' => 'hello 2'
		];
		$pdf = PDF::chunkLoadView('<html-separator/>', 'pdf.document', $data);
		return $pdf->stream('document.pdf');
	}
}
<div>
    <h1>Hello World</h1>
    <table>
        <tr><td>{{ $foo }}</td></tr>
    </table>
    <html-separator/>
    <table>
        <tr><td>{{ $bar }}</td></tr>
    </table>
    <html-separator/>
</div>

License

Laravel Mpdf is open-sourced software licensed under the MIT license

Comments
  • Undefined array key

    Undefined array key "dejavusanscondensed"

    I'm having this error Illuminate\Foundation\Bootstrap\HandleExceptions::handleError C:\xampp\htdocs\fiamedical\vendor\mpdf\mpdf\src\Otl.php:154

    and here's my controller

    $pdf = MPDF::loadView('/printouts/salesagentreagents',array('data' => $data,'from' => $from,'to' => $to),[],[ 'margin_left'=> 35, 'margin_right'=> 15, 'default_font_size'=> '8', 'default_font'=> 'DejaVu Sans', 'format'=> 'Legal', 'orientation'=> 'L']);

    return $pdf->stream();

    opened by koheitaka 19
  • Laravel 9 Support

    Laravel 9 Support

    Hi there, I was just wondering if this package works with Laravel 9. I recently updated a project that uses this package to L9 and got the following error:

    Declaration of Mpdf\Mpdf::setLogger(Psr\Log\LoggerInterface $logger) must be compatible with Psr\Log\LoggerAwareInterface::setLogger(Psr\Log\LoggerInterface $logger): void

    I'm about to try downgrading the PSR Logger package version to see if it solves the problem.

    I've gone through every possible cenario but haven't come up with an answer yet. Any insight would be appreciated.

    opened by omdesignz 6
  • custom font not picked up

    custom font not picked up

    I am having the similar issue where the custom fonts are not picked up. config: image

    fonts: image

    load view: $pdf = PDF::loadView('emails.test.view',['data' => $this->data]);

    Result: defaults to dejavu font image

    Originally posted by @karunkshrestha in https://github.com/mccarlosen/laravel-mpdf/issues/11#issuecomment-1015438260

    opened by karunkshrestha 5
  • Non static method 'chunkLoadView' should not be called statically.

    Non static method 'chunkLoadView' should not be called statically.

    image

    I get "Non static method 'chunkLoadView' should not be called statically." warning in vs code. I think this is because the annotation need to indicate that the method is a static one.

    /**

    • Class LaravelMpdf
    • @package Meneses\LaravelMpdf\Facades
    • @method Pdf loadHTML(string $html, ?array $config = [])
    • @method Pdf loadFile(string $file, ?array $config = [])
    • @method Pdf loadView(string $view, ?array $data = [], ?array $mergeData = [], ?array $config = [])
    • @method Pdf chunkLoadHTML(string $separator, string $html, ?array $config = [])
    • @method Pdf chunkLoadFile(string $separator, string $file, ?array $config = [])
    • @method Pdf chunkLoadView(string $separator, string $view, ?array $data = [], ?array $mergeData = [], ?array $config = []) */
    opened by karunkshrestha 5
  • LoggerInterface Issue

    LoggerInterface Issue

    With the latest update we are getting this error again:

    Declaration of Mpdf\Mpdf::setLogger(Psr\Log\LoggerInterface $logger) must be compatible with Psr\Log\LoggerAwareInterface::setLogger(Psr\Log\LoggerInterface $logger): void
    
    opened by sgtcoder 4
  • Show extra html on the last page's footer

    Show extra html on the last page's footer

    Hi, currently I have a normal footer and everything works as intended. <htmlpagefooter name="Footer"> <div class="footer">You are reading document X</div> </htmlpagefooter>

    But I want a different output for the last page. <htmlpagefooter name="Footer"> <div class="footer">You are reading document X</div> <div class="extra">This is the last page.</div> </htmlpagefooter>

    How can I achieve this?

    opened by youasl 4
  • How we can run Javascript before making PDF

    How we can run Javascript before making PDF

    I have to convert the timestamp into a local timestamp. so I need to run some javascript to do it. but didn't find any way. mpdf I think allows you to set some options to enable javascript. how we can do it in this package

    opened by usmanibrahim74 4
  • Custom font not loading

    Custom font not loading

    Hi

    I have followed your docs and have the config file as below:

    `<?php

    return [ 'mode' => 'utf-8', 'format' => 'A4', 'default_font_size' => '12', 'default_font' => 'sans-serif', 'margin_left' => 10, 'margin_right' => 10, 'margin_top' => 10, 'margin_bottom' => 10, 'margin_header' => 0, 'margin_footer' => 0, 'orientation' => 'P', 'title' => 'Laravel mPDF', 'author' => '', 'watermark' => '', 'show_watermark' => false, 'watermark_font' => 'sans-serif', 'display_mode' => 'fullpage', 'watermark_text_alpha' => 0.1, 'custom_font_dir' => base_path('resources/fonts/'), // don't forget the trailing slash! 'custom_font_data' => [ 'Quantify' => [ 'R' => 'Quantify.ttf' // regular font ] ] ];`

    however the font does not display at all. Only the default san serif font.

    Inline style in my pdf balde:

    ` @font-face { font-family: 'Quantify'; }

    body { font-family: 'Quantify', sans-serif; letter-spacing: 2px; padding-right: 0 !important; }`

    Tried mapping to my standard fonts location in storage and tried moving that folder to resources as defined above. But no difference.

    Currently developing on local homestead setup if this makes a difference?

    Any help appreciated.

    opened by kinger251285 4
  • Custom font not working

    Custom font not working

    I'm trying to add a custom font, but it's not working. I've already tried all the solutions from previous issues but neither of them works for me. I don't see what I'm missing

    I already create the config/pdf.php file:

    pdf

    Added the fonts to the project, in this case I use the public folder, also tried to put them on resources folder, but not working:

    fonts

    And this is how I'm setting the font on the blade file:

    code

    opened by agares29 3
  • Laravel 9 error declaration of setLogger not compatible with Psr

    Laravel 9 error declaration of setLogger not compatible with Psr

    After trying upgrade to Laravel 9, an error of declaration of setLogger must be compatible with Psr\Log\LoggerAwareInterface::setLogger(Psr\Log\LoggerInterface $logger): void occurred.

    laravel 9 mpdf

    https://flareapp.io/share/47q10E07#F1

    opened by zulhilmixrahman 3
  • As of 03/05 PSR4 is broken

    As of 03/05 PSR4 is broken

    Class Meneses\LaravelMpdf\LaravelMpdfWrapper located in C:/Users/Colin/Websites/CSS/vendor/carlos-meneses/laravel-mpdf/src\LaravelMpdf\LaravelMpdfWrapper.php does not comply with psr-4 autoloading standard. Skipping.

    Downgrading to 2.1.3 still installs OK on PHP 8

    opened by colinmackinlay 3
  • Error in last version

    Error in last version

    I got this error while generating the pdf file:

    ErrorException: Undefined array key "type" in /Users/a/Documents/Sites/wsq/vendor/mpdf/mpdf/src/Otl.php:5631
    Stack trace:
    #0 /Users/a/Documents/Sites/wsq/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(266): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'Undefined array...', '/Users/a/Docume...', 5631)
    #1 /Users/a/Documents/Sites/wsq/vendor/mpdf/mpdf/src/Otl.php(5631): Illuminate\Foundation\Bootstrap\HandleExceptions->Illuminate\Foundation\Bootstrap\{closure}(2, 'Undefined array...', '/Users/a/Docume...', 5631)
    

    my code:

    $pdf = PDF::loadView(
                'api.contract-pdf',
                [
                    'contract' => $contract,
                    'pdf_form' => $pdf_form,
                ],
                [],
                [
                    'watermarkImgBehind' => true,
                    'watermark_image_path' => $this->opposed_contract ? base_path('public/images/opposed.png') : base_path('public/images/pdf.png'),
                ]
            );
    

    I've installed the last version and mpdf/mpdf as well, my laravel version is 9 and php 8,1

    opened by rabeeaali 0
  • mpdf library output result strange characters

    mpdf library output result strange characters

    Octane Version: 1.3.9 Laravel Version: 9.43.0 PHP Version: 8.1 Server & Version: Swoole

    Description: I am trying to create a pdf document with mpdf, but when using octane it becomes strange characters.

    Steps To Reproduce: composer require carlos-meneses/laravel-mpdf in controller: $pdf = PDF::loadView('pdf.document'); // document content with free characters return $pdf->stream('document.pdf')

    the result is 209747768-55236efc-c635-4d38-b4e0-d646465364fd

    opened by adeiming 3
  • Footer working only in last page

    Footer working only in last page

    $footer = '<span>Página {PAGENO} de {nbpg}</span>' $mpdf = PDF::chunkLoadView('<html-separator/>', 'pdf.bladepdf', $data); $mpdf->getMpdf()->SetHTMLFooter($footer);

    <style> @page { footer: page-footer; } </style> <htmlpagefooter name="page-footer"> <div style="padding: 10px 10px;"> <table width="100%"> <tr> <td width="33%" align="center" style="font-style: italic;">Página {PAGENO} de {nbpg}</td> </tr> </table> </div> </htmlpagefooter>

    When Pdf generate 2 or more pages, It works, but when it have just one page, SetHTMLFooter Not cover the footer in blade

    opened by GGarnize 2
Releases(2.1.11)
Owner
Carlos Meneses
Full Stack PHP Developer, #Laravel, #Livewire, #Vue, #React.
Carlos Meneses
Simple wrapper package around MPDF's setProtection method that allows you to set password on PDF files

Laravel PDF Protect (fork) Simple wrapper package around MPDF's setProtection method that allows you to set password on PDF files. Installation You ca

Raphael Planer 2 Jan 23, 2022
Generate PDF invoices for your customers in laravel

What is Invoices? Invoices is a Laravel library that generates a PDF invoice for your customers. The PDF can be either downloaded or streamed in the b

Erik C. Forés 399 Jan 2, 2023
Rapidly Generate Simple Pdf, CSV, & Excel Report Package on Laravel

Laravel Report Generators (PDF, CSV & Excel) Rapidly Generate Simple Pdf Report on Laravel (Using barryvdh/laravel-dompdf or barryvdh/laravel-snappy)

Jimmy Setiawan 513 Dec 31, 2022
Official clone of PHP library to generate PDF documents and barcodes

TCPDF PHP PDF Library Please consider supporting this project by making a donation via PayPal category Library author Nicola Asuni [email protected] co

Tecnick.com LTD 3.6k Jan 6, 2023
Generate simple PDF invoices with PHP

InvoiScript Generate simple PDF invoices with PHP. Installation Run: composer require mzur/invoiscript Usage Example use Mzur\InvoiScript\Invoice; re

Martin Zurowietz 16 Aug 24, 2022
Generate pdf file with printable labels

printable_labels_pdf Generate pdf file with printable labels with PHP code. CREATE A PDF FILE WITH LABELS EASELY: You can get a pdf file with labels f

Rafael Martin Soto 5 Sep 22, 2022
Gravity PDF is a GPLv2-licensed WordPress plugin that allows you to automatically generate, email and download PDF documents using Gravity Forms.

Gravity PDF Gravity PDF is a GPLv2-licensed WordPress plugin that allows you to automatically generate, email and download PDF documents using the pop

Gravity PDF 90 Nov 14, 2022
Official clone of PHP library to generate PDF documents and barcodes

TCPDF PHP PDF Library Please consider supporting this project by making a donation via PayPal category Library author Nicola Asuni [email protected] co

Tecnick.com LTD 3.6k Dec 26, 2022
Laravel Snappy PDF

Snappy PDF/Image Wrapper for Laravel 5 and Lumen 5.1 This package is a ServiceProvider for Snappy: https://github.com/KnpLabs/snappy. Wkhtmltopdf Inst

Barry vd. Heuvel 2.3k Jan 2, 2023
A DOMPDF Wrapper for Laravel

DOMPDF Wrapper for Laravel Laravel wrapper for Dompdf HTML to PDF Converter Require this package in your composer.json and update composer. This will

Barry vd. Heuvel 5.6k Jan 7, 2023
Adobe XDでデザインしてSVGでエクスポートしたテンプレートをもとに、A4サイズの帳票をHTMLで出力する機能のPHP(Laravel)による実装例です

svg-paper-example Adobe XDでデザインしてSVGでエクスポートしたテンプレートをもとに、A4サイズの帳票をHTMLで出力する機能のPHP(Laravel)による実装例です。 こちらで実際に動くデモが見られます ?? 実装内容についての詳細は こちらのブログ記事 で解説していま

Takashi Kanemoto 21 Dec 11, 2022
A Laravel package for creating PDF files using LaTeX

LaraTeX A laravel package to generate PDFs using LaTeX · Report Bug · Request Feature For better visualization you can find a small Demo and the HTML

Ismael Wismann 67 Dec 28, 2022
DOMPDF module for Laravel 5

pdf-laravel5 DOMPDF module for Laravel 5. Export your views as PDFs - with css support. Instalation Add: "vsmoraes/laravel-pdf": "^2.0" To your compo

Vinicius Moraes 88 Jul 25, 2022
Laravel package to convert HTML to PDF, supporting multiple drivers.

eve/pdf-converter A Laravel package to help convert HTML to PDF. Supports multiple drivers. Requirements and Installation eve/pdf-converter requires L

eve.io 11 Feb 15, 2022
⚡️ MIRROR — A feature-rich Laravel wrapper for the WeasyPrint Document Factory.

WeasyPrint for Laravel A feature-rich Laravel wrapper for the WeasyPrint Document Factory. This package requires Laravel 8.47+ running on PHP 8+ in or

Mike Rockétt 7 Dec 30, 2022
Browsershot wrapper for Laravel 5

Browsershot wrapper for Laravel 5 This package takes advantage of Google Chrome's Headless mode to take screenshots and generate PDFs from websites, v

VECO 108 Jul 25, 2022
Dompdf - Simple Dompdf package for Laravel

Dompdf - Simple Dompdf package for Laravel

Jonathan Thuau 228 May 3, 2022
Ce projet vous montre comment utiliser des fonts localement dans vos applications Laravel, avec ViteJS et Tailwind CSS

Laravel - use local fonts with Tailwind CSS and Vite Ce projet est né d'un constat: vous êtes souvent nombreuses et nombreux à galérer pour utiliser d

Fred Christian 2 Sep 20, 2022
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
This package will generate PDFs and PNGs from websites.

This package will generate PDFs and PNGs from websites.

Appoly 0 Dec 3, 2021