Git Product home page Git Product logo

laravel-mpdf's Introduction

Laravel Mpdf: Generate PDF Files with ease.

Easily generate PDF files using Laravel's Blade templates and the MPDF library. This package has been tested since Laravel 5.4.

Installation

Run this composer command in your laravel application:

composer require carlos-meneses/laravel-mpdf

Important Notes:


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

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.

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

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 viewPdf()
    {
        $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 execute php artisan vendor:publish --tag=mpdf-config or 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,
    'show_watermark_image'       => false,
    'watermark_font'             => 'sans-serif',
    'display_mode'               => 'fullpage',
    'watermark_text_alpha'       => 0.1,
    'watermark_image_path'       => '',
    'watermark_image_alpha'      => 0.2,
    'watermark_image_size'       => 'D',
    'watermark_image_position'   => 'P',
    'custom_font_dir'            => '',
    'custom_font_data'           => [],
    'auto_language_detection'    => false,
    'temp_dir'                   => storage_path('app'),
    '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);

Get instance your Mpdf

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

use PDF;

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

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' => [ // must be lowercase and snake_case
            '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;
}

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>

Added Support for the Macroable Trait

You can configure the macro in the AppServiceProvider provider file.

//...
use Mccarlosen\LaravelMpdf\LaravelMpdf;

class AppServiceProvider extends ServiceProvider
{
  //...

    public function boot()
    {
        LaravelMpdf::macro('hello', function () {
            return "Hello, World!";
        });
    }

  //...
}

Now

PDF::loadView(/* ... */)->hello();

License

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

laravel-mpdf's People

Contributors

aanfarhan avatar abronin avatar abumosaab avatar ali-alharthi avatar danielrona avatar dsturm avatar finwe avatar mccarlosen avatar mortezapoussaneh avatar mudasserzahid avatar pindab0ter avatar rabrowne85 avatar realtebo avatar sdon2 avatar shukriyusof avatar tamer-dev avatar webmasterpacifico avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-mpdf's Issues

Print PDF Blank

Hello,

I am development a template editor and which i try print in pdf (with method stream) a document in blank, this result how output in html

imagen

publish new version

Hi there,

since the last version (2019) has been released
there have been 13 commits made some quite useful
but we have to currently use dev-master if we want to make use of all the recent changes

maybe it's time to publish a new version?

breaking css

When I load PDF it miss place my data

Real design

download (7)

What I get in pdf

download (8)

Code

controller

$data = [
  'foo' => $templateContent
];
$pdf = PDF::loadView('backend.template.pdf', $data);
return $pdf->stream('document.pdf');

view

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    </head>
    <body>
        {!! $foo !!}
    </body>
</html>

Any idea?

Header Footer Not Showing

I need header and footer in my pdf.
Tried using instructions provided in laravel-mpdf but it is not showing in pdf
Header is written in following way

<td >

  <!-- content -->

  <div class="container">

  <table>
    <tr>
      <td>
       <img src="http://localhost/laravel-auth/public/assets/images/archer-interiors-logo.png">
      </td>
    </tr>
	<tr>
      <td align="center"><strong>ORDER FORM</strong></td>
    </tr>
  </table>
  </div>
  <!-- /content -->
  
</td>
<td></td>

Custom font not supported (Undefined offset: 1)

I have a problem when i want to add my custom font to my project.

it's my config/pdf.php

'custom_font_dir' => base_path('public/font/fonts/'), 'custom_font_data' => [ 'IranSans' => [ 'R' => 'IRANSansFaNum.ttf', 'B' => 'IRANSansFaNumBold.ttf', 'I' => 'IRANSansFaNumLight.ttf', 'BI' => 'IRANSansFaNumMedium.ttf' ] ],

after running project i get Undefined offset: 1 ErrorException

the problem is in vendor\mpdf\mpdf\src\Mpdf.php file and line 4105

$ws = $fas[1] . $style;

is this font not supported or what?

Thanks.

costume fonts not working

I use in config/Mpdf.php this code

<?php return [ 'mode' => '', 'format' => 'A4-L', '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' => 'L', 'title' => 'Laravel mPDF', 'author' => 'مسوده', 'watermark' => '', 'show_watermark' => true, 'watermark_font' => 'sans-serif', 'display_mode' => 'fullpage', 'watermark_text_alpha' => 0.2, 'custom_font_dir' => base_path('dist/fonts/tajawal/'), 'custom_font_data' => [ 'tajawal' => [ 'R' => 'Tajawal-Regular.ttf', // regular font //'useOTL' => 0xFF, //'useKashida' => 75, ] ], 'auto_language_detection' => false, 'temp_dir' => '', 'pdfa' => false, 'pdfaauto' => false, ];

but I get this error

Mpdf\MpdfException
Cannot find TTF TrueType font file "Tajawal-Regular.ttf" in configured font directories.

also I get this error

Mpdf\MpdfException
Font "tajawal" is not supported

Problem : data transfer from the controller into the view

Hi,

I have just installed your packages, however I encounter a problem when retrieving my data variables.

I use :
- carlos-meneses/laravel-mpdf": "2.1.3".
- "php": "^7.3"
- "laravel/framework": "^8.0"

here is my code :

  1. Route :
Route::get('/pdf/{id}/RC_{nof}-{lof}', [RcMtvController::class, 'generate_pdf'])
        ->where('id', '[0-9]+')->where('nof', '[0-9]{6}')->where('lof', '[0-9]{3}')
        ->name('mtv.pdf');
  1. Controller :
    public function generate_pdf(int $id, int $nof, int $lof) 
	{
		$data = [
                    'titlePDF'` => 'Test PDF',
                    'id'       => $id,
                    'nof'      => $nof,
                    'lof'      => $lof
               ];

		$pdf = \PDF::loadView('PDF/pdf', $data);
                 return $pdf->stream($data['titlePDF'] . '.pdf');
	}
  1. View :
<?php

dd($data);

?>
  1. Result :
    Undefined variable: data (View: C:\laragon\www\siteName\resources\views\PDF\pdf.blade.php)

thank you in advance for your help.

Landscape Orientation is Not working.

I am trying to get PDF in landscape orientation but it's not working. I have tried with this method.
$config = [
'orientation' => 'L'
]
$pdf = PDF::loadView($view, $data, [ ], $config);
return $pdf->stream('Report.pdf');

I have tried both 'P' and 'L' but it is giving PDF only in Portrait mode.

shrink_tables_to_fit or autosize="1" is not working

Hello,

I generate pdf using an HTML table.

I have used many solutions to stop shrik.
e.g

  1. $pdf->getMpdf()->shrink_tables_to_fit = 0; and ​$pdf->getMpdf()->shrink_tables_to_fit = 1;
  2. autosize="1" and autosize="0

but nothing is working, can you tell me what I'm doing wrong?

I'm using "carlos-meneses/laravel-mpdf": "^2.1",

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.

Image not able to load !

Using Laravel 8, everything is working fine except image not loading in mpdf. While removing logo-image everything woks fine. Am I missing something for image in mpdf ?

Create table of content

Hi ,

I need to Create a table of content for the generated PDF document .
the documentations not clear regarding the table content creation .

could you please assist in this ?

thanks

Save pdf file to S3 CloudFront CDN

I want to save pdf on s3 CloudFront I am using the save method but the file is not saving.

$pdf = PDF::chunkLoadView('<html-separator/>', 'pdf.user', $data);
$pdf->save('path');

PHP 7 Comatibility

Hi!

The latest release changed required PHP version to 8, but I have not seen any changes that made the code incompatibile with PHP 7. Why both PHP versions weren't allowed for the newest version?

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?

Different Page Header/Footer

Using the niklasravnsborg / laravel-pdf package, is there a way to create a header and/or footer based on whether or not a page is an odd or an even page?

I haven't been able to find anything that suggests it's possible, but I also haven't found anyone specifically inquiring about this issue.

If I did something like this styling in the html document:

         @page {
            odd-header-name: odd-header;
            even-header-name: even-header;
            odd-footer-name: odd-footer;
            even-footer-name: even-footer;
}

And this in the body:

<htmlpageheader name="odd-header">
    <div style="text-align: center">MUNICIPAL CODE</div>
</htmlpageheader>

<htmlpageheader name="even-header">
    <div style="text-align: center">MUNICIPAL CODE</div>
</htmlpageheader>

<htmlpagefooter name="even-footer">

    <div style="float:left; width: 50%;">
        EvenTitle {{$title->number}} - {{$title->title}}
    </div>

    <div style="float:right; width: 40%; text-align: right;">Page {PAGENO} of {nb}</div>
</htmlpagefooter>

<htmlpagefooter name="odd-footer">

    <div style="float:right; width: 50%;">
        OddTitle {{$title->number}} - {{$title->title}}
    </div>

    <div style="float:left; width: 40%; text-align: right;">Page {PAGENO} of {nb}</div>
</htmlpagefooter>

Only the odd versions appear. Does anyone have any workarounds or suggestions?

How to add new page

How can we create a new page?

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

The above code didn't work.

How to insert a page break?

Hi ! Thanks for your package.

Could you document how to add a pagebreak? I can't get it work.

I tried using <pagebreak /> in my view (see mPDF Doc but it seems simply ignored

Also <formfeed /> ( see ) is ignored.

footer is working only on last page

$pdf = PDF::loadView('transaksi.pdf_'.$query, $data, [], [
	'orientation' => 'L',
	'margin_footer' => '5',
]);
$pdf->getMpdf()->SetTitle($title);
$pdf->getMpdf()->SetAuthor(config('settings.app_name'));
$pdf->getMpdf()->SetCreator(config('settings.app_name'));
$pdf->getMpdf()->SetSubject($title);
$pdf->getMpdf()->setFooter('Dicetak dari Aplikasi '.config('settings.app_name').'||Halaman {PAGENO} dari {nbpg}');

security issue

Dear

I scan the code using tools and that show for me there is a problem on that line

can you example what is the problem?

$this->pages[$n] = preg_replace('/(___HEADER___MARKER' . $this->uniqstr . ')/', "\n" . $os . "\n" . '\1', $this->pages[$n]);

			$this->pages[$n] = preg_replace('/(___HEADER___MARKER' . $this->uniqstr . ')/', "\n" . $os . "\n" . '\\1', $this->pages[$n]);

thank you

Lists: list_symbol_size not working

I've tried a number of ways now to make li list bullet items bigger with the mpdf setting: list_symbol_size.
I've attempted implementing it in my pdf config file, and I've also tried including it in the loadView config array, but none of it seems to work, then again I don't get any errors either, so I don't really have a lot to go on :-)

Update package to require Mpdf ^8.0

Mpdf has released v8 in march with some bugfixes and features, and most importantly dependency of the FPDI library to version 2.

Your package blocks upgrading to a higher version than Mpdf v7.1.9 and fpdi v1.6.2 which I would really enjoy to fix some Mpdf issues.

Could you upgrade the dependancies please? I could do it with a PR but there's no tests defined here so I'm a bit hesitant in relation to breaking changes. Thanks!

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

"Unsupported operand types" error

I just installed Laravel Mpdf via composer, but when I tried writing a simple PDF, a fatal error was thrown in file

vendor\carlos-meneses\laravel-mpdf\src\LaravelMpdf\LaravelMpdf.php

"Unsupported operand types"

The code highlighted is at line 44:

'fontdata' => $fontData + $this->getConfig('custom_font_data'),

I'm using Laravel 5.6 and php 7.0. Any ideas what I can do to get past this?

Header remains on imported pages

Is there a way to clear the header for imported pages? I want the header on the generated portion, but I want to clear it when I start importing pages.

Tabelas shrink_tables_to_fit

A tabela sempre estão mantendo as linhas em uma página só. Isso é padrão ? Queria para a tablela continuar o texto sem quebrar página. Tentei shrink_tables_to_fit=1, porem não faz efeito.
Obrigado
Captura de Tela 2019-04-04 às 22 19 36

temp_dir default rely on the dir vendor/mpdf/mpdf/tmp to be writabe

Problem:
It is possible to get the error "Temporary files directory "/var/www/app/vendor/mpdf/mpdf/src/Config/../../tmp" is not writable" because of temp_dir is set to the empty string '' here: https://github.com/mccarlosen/laravel-mpdf/blob/master/src/config/pdf.php#L25 by default.

It's not a problem in the local environment but you can get into trouble when you run the application in Docker (which we do), as an example.

Solution:
It would be better to use a system temporary directory in this case. It may look like this:
'temp_dir' => rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR),
This code is from widely used spatie/temporary-directory and it is heavily tested on all the platforms.

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

Multiple custom_font_data

How to use multiple custom_font_data
like

    'custom_font_dir' => public_path('template-sertifikat/fonts/'), // don't forget the trailing slash!
    'custom_font_data' => [
        'Verdana' => [
            'R'  => 'verdana.ttf',    // regular font
            'B'  => 'verdanab.ttf',       // optional: bold font
            'I'  => 'verdanai.ttf',     // optional: italic font
            'BI' => 'verdanaz.ttf' // optional: bold-italic font
        ],
        'edwardian' => [
            'R'  => 'EdwardianScriptITC.ttf',    // regular font
            'B'  => 'EdwardianScriptITC.ttf',       // optional: bold font
            'I'  => 'EdwardianScriptITC.ttf',     // optional: italic font
            'BI' => 'EdwardianScriptITC.ttf' // optional: bold-italic font
        ]
    ],
    'default_font'         => 'Verdana',

if i use this code, i'm getting error in vendor\mpdf\mpdf\src\Mpdf.php line 4125

$ws = $fas[1] . $style;

thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.