Giter VIP home page Giter VIP logo

mpdf.github.io's Introduction

mPDF is a PHP library which generates PDF files from UTF-8 encoded HTML.

It is based on FPDF and HTML2FPDF (see CREDITS), with a number of enhancements. mPDF was written by Ian Back and is released under the GNU GPL v2 licence.

Latest Stable Version Total Downloads License

⚠ If you are viewing this file on mPDF GitHub repository homepage or on Packagist, please note that the default repository branch is development which can differ from the last stable release.

Requirements

PHP versions and extensions

  • PHP >=5.6 <7.3.0 is supported for mPDF >= 7.0
  • PHP 7.3 is supported since mPDF v7.1.7
  • PHP 7.4 is supported since mPDF v8.0.4
  • PHP 8.0 is supported since mPDF v8.0.10
  • PHP 8.1 is supported as of mPDF v8.0.13
  • PHP 8.2 is supported as of mPDF v8.1.3
  • PHP 8.3 is supported as of mPDF v8.2.1

PHP mbstring and gd extensions have to be loaded.

Additional extensions may be required for some advanced features such as zlib for compression of output and embedded resources such as fonts, bcmath for generating barcodes or xml for character set conversion and SVG handling.

Known server caveats

mPDF has some problems with fetching external HTTP resources with single threaded servers such as php -S. A proper server such as nginx (php-fpm) or Apache is recommended.

Support us

Consider supporting development of mPDF with a donation of any value. Donation button can be found on the main page of the documentation.

Installation

Official installation method is via composer and its packagist package mpdf/mpdf.

$ composer require mpdf/mpdf

Usage

The simplest usage (since version 7.0) of the library would be as follows:

<?php

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Hello world!</h1>');
$mpdf->Output();

This will output the PDF inline to the browser as application/pdf Content-type.

Setup & Configuration

All configuration directives can be set by the $config parameter of the constructor.

It is recommended to set one's own temporary directory via tempDir configuration variable. The directory must have write permissions (mode 775 is recommended) for users using mPDF (typically cli, webserver, fpm).

Warning: mPDF will clean up old temporary files in the temporary directory. Choose a path dedicated to mPDF only.

<?php

$mpdf = new \Mpdf\Mpdf(['tempDir' => __DIR__ . '/tmp']);

By default, the temporary directory will be inside vendor directory and will have write permissions from post_install composer script.

For more information about custom temporary directory see the note on Folder for temporary files in the section on Installation & Setup in the manual.

If you have problems, please read the section on troubleshooting in the manual.

About CSS support and development state

mPDF as a whole is a quite dated software. Nowadays, better alternatives are available, albeit not written in PHP.

Use mPDF if you cannot use non-PHP approach to generate PDF files or if you want to leverage some of the benefits of mPDF over browser approach – color handling, pre-print, barcodes support, headers and footers, page numbering, TOCs, etc. But beware that a HTML/CSS template tailored for mPDF might be necessary.

If you are looking for state of the art CSS support, mirroring existing HTML pages to PDF, use headless Chrome.

mPDF will still be updated to enhance some internal capabilities and to support newer versions of PHP, but better and/or newer CSS support will most likely not be implemented.

Online manual

Online manual is available at https://mpdf.github.io/.

General troubleshooting

For general questions or troubleshooting please use Discussions.

You can also use the mpdf tag at Stack Overflow as the StackOverflow user base is more likely to answer you in a timely manner.

Contributing

Before submitting issues and pull requests please read the CONTRIBUTING.md file.

Unit Testing

Unit testing for mPDF is done using PHPUnit.

To get started, run composer install from the command line while in the mPDF root directory (you'll need composer installed first).

To execute tests, run composer test from the command line while in the mPDF root directory.

Any assistance writing unit tests for mPDF is greatly appreciated. If you'd like to help, please note that any PHP file located in the /tests/ directory will be autoloaded when unit testing.

mpdf.github.io's People

Contributors

a-bakos avatar alexander-schranz avatar alrnz avatar binarykitten avatar bmg-ruudv avatar carli2 avatar e-e avatar finwe avatar githubeing avatar jakejackson1 avatar jevinsonlim avatar klap-in avatar marclaporte avatar mitelg avatar noplanman avatar sagearslan avatar tomtomau avatar uestla avatar willyarisky 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mpdf.github.io's Issues

header footer lost when use @page

I have faced issue when use @page. Page render very nice but in second page of pdf header and footer lost
orders_18-Jan-21_17-01-19.pdf

@page {
/not use header: header_name;
footer: footer_name;
/
margin: 1.2in 0.5in 1.2in 0.5in;
}

Using mpdf 6.1 work with magento 2 enviroment. PHP7.0.25
How to bring header footer back. Thank all you guys
see sample pdf in my attachment

SetFooter page text

There are a couple of spots on the page for SetFooter that references 'header' instead of 'footer'. Specifically at the top next to

SetFooter – Sets a page header

and in the following example for the $footer parameter example's TEXT STRING.

not listed variables at configuration overview

Add page reference/mpdf-variables/overview.html variables are listed.

Following variables are not in that list

  • defaultPagebreakType (but autoPageBreak is listed, but not in defaults of src/Config/ConfigVariables.php of mPDF library)

  • PDFAXwarnings

  • spotColors

  • spotColorIDs

  • annotSize

  • indexUseSubentries

  • splitTableBorderWidth

  • interpolateImages

  • useDictionaryLBR

  • useTibetanLBR

  • ColGap

  • SHYlanguages

  • SHYleftmin

  • SHYrightmin

  • SHYcharmin

  • SHYcharmax

  • useActiveForms

  • watermarkText

  • watermarkImage

  • defaultCSS (in overview mentioned: useDefaultCSS2)

  • defaultCssFile
    suggestion: link to /css-stylesheets/default-stylesheet.html. Is useDefaultCSS2 old version of this variable?

Note in src/Config/ConfigVariables.php: "values only likely to be changed by developers."

From these values are already documented, but not listed in overview.

  • pdf_version ( in example configuration/configuration-v7-x.md )
  • fontDir ( fonts-languages/font-names.md )
  • tempDir (in doc installation-setup/installation-v7-x.md )

not documented and not listed, and not useful to add:

fontTempDir (not found)
hyphenationDictionaryFile (not found)
default_lineheight_correction (not found)
fontsizes (not found)
pregRTLchars (not found)
pregCJKchars (not found)
CJKleading (not found)
CJKfollowing (not found)
CJKoverflow (not found)
pregCURSchars (not found)
allowedCSStags (not found)
outerblocktags (not found)

How can I passing content from a view to a controller and print in pdf?

Hello, I am using mpdf with codeigniter, but I am faced with the problem that don't work with ajax and don't allow downloading directly by clicking on a button or receiving a pdf file.

What I'm trying to do is to have a button in the view, which sends the controller a certain content in html, let's say an example div tag or a form, for the driver to receive it and print that content, I've tried it by ajax so much json as per html type, but none of them work and I can't send from the view html content to the controller without going through ajax, could indicate me some solution to be able to send from any view (html) to controller and print that content.

page-break-inside:avoid; PDF layout brakes completly

Hello

I've been using this lib for a while and never had big problems with it.
Recently we started to change the way our PDF's get build. We stopped using tables because our document builder now tries to be 'wysiwyg'. Each item (previously table row) should be kept in one piece so we added the css page-break-inside:avoid; to each item html block element (now div).

The above makes the content go wild:
after page-break-inside

If we remove the inline css again all is back to normal:
before page-break-inside

Currently we do
$this->mpdf = new mPDF(); $this->mpdf->use_kwt = false; $this->mpdf->AddPage(); $this->mpdf->WriteHTML($allHtmlContentToBePrinted); // in here we have some items with the css property $this->mpdf->SetHTMLFooter($footer);
So, no fancy options are used etc, no HTML tables are printed. As CSS we load Bootstrap responsive stylesheet.
Any ideas please?

Review a different branch of "mpdf.github.io"

Is there a way to see what the rendered online version of a different branches looks like? For instance, "mpdf.github.io" shows the contents of the master branch, but I'd like to see what it looks like when pulling data using the development branch.

escape | to prevent tables

one | (pipe-character) or at least more | are interpreted as a table by the markdown parser.

Solution: escaping by \|

note boxes with markdown

replace <div class="alert alert-info" role="alert"> by
<div class="alert alert-info" role="alert" markdown="1">

  • fix indention
  • closing tag at new lines to prevent including in block.

background-position & background-size problems

the css attributes 'background-position: center' & 'background-size: cover' on an element with a background-image only work, as long as the background image gets cropped vertically, but if it would get cropped horizontally, the image will instead be stretched and repeated wrongly.

this is how it looks like & should look like in Html, and how its rendered in the pdf

Does anyone know a workaround for this? the elements with the background-image also have width & height = 100% and im assuming it could have something to do with those percent sizes.

manual_block is not rendered

See the end of http://mpdf.github.io/what-else-can-i-do/index.html where this paragraph was previously:

<p>This is the appearance with $this-&gt;indexUseSubentries = false;</p> 
<p class="manual_block">Mammals 73<br /> 
Mammals, elephants 142<br /> 
Mammals, <b>elephants</b>: breeding 15<br /> 
Mammals, humans 173<br /> 
Marsupials, kangaroos 75<br /> 
Marsupials, wombats 86</p> 

Now the source is missing the linebreaks of p and br tags:

This is the appearance with $this-&gt;indexUseSubentries = false;

Mammals 73

Mammals, elephants 142

Mammals, <b>elephants</b>: breeding 15

Mammals, humans 173

Marsupials, kangaroos 75

Marsupials, wombats 86

Images with Relative Pathnames Fail to Render

Hello, I am using this tool to render a pdf of owned products you mark as such on the site and then click a "render to pdf" button. Then the pdf of the images of the products you own is generated.

My issue is if I use a relative path that points back to the root folder of our site (ie: /includes/images/products/product_1.jpg) the image does not display (get a red x in a box). Funny thing is if I render the page as html the images will show or if I remove the first forward slash (ie: includes/images/products/product_1.jpg) it behaves as if the forward slash is there, goes to the root and finds the correct path to the image.

Looking to understand why this is - it seems backwards from how paths are usually handled.

Thanks!

Using phpdoc

Browsing through mpdf source code, I noticed several inline comments mentioning versions where a particular change occurred. Some examples:

if (!empty($attr['POSITION'])) {  // mPDF 5.7.2

I also noticed that the documentation is maintained by hand, and that some of the latest changes in mPDF are not yet reflected (which is completely understandable).

I was wondering if phpdoc could be used more efficiently in the source code, in order to generate the documentation. I know this will require a lot of work, and I'm willing to participate here as well :)

Let me know what are your thoughts on this subject.

howto setup jekyll

page-break-inside: avoid when using columns

I have blocks (divs) in columns, but when using page-break-inside: avoid on these blocks, the blocks are cut.

I would like a block (the whole block) to move to the next column when it doesn't fit. Is this possible somehow? The blocks have a variable size.

Is there any way to fix it, or can somebody point me in the right direction to add working functionality like this? I did browse through the code and found that page-break-inside: avoid is ignored when columns are being used, but I didn't understand the inner workings well enough to get it to work.

Example of problem in attached image.

pdf_column_problem

Add documentation for usage of LogInterface

The 7.0 version of https://mpdf.github.io/reference/mpdf-variables/debug.html
mentions the note: This variable was succeeded by usage of \Psr\Log\LogInterface in 7.0

  • Add some explanation (or references) for usage of the LogInterface.
  • Add mpdf-function description for setLogger()
  • Update/rewrite documentation with debug mpdf variable (e.g. /reference/mpdf-variables/debug.html, /troubleshooting/error-messages.html)

Some details:

Request - Documentation update for mPDF 7.x

Hi everyone,

Would it be possible to have a documentation update that reflects version 7.x of mPDF?

i think there where quite a few changes that peoples might not be all that aware of...

Unknown error when embedding adobeCJK custom fonts into pdf

Aiming to embed a custom font into the final pdf, working well in 6.0 but something wrong when referencing the 7.0 document to migrate the implementation.

Using: php 7.2.0, CodeIgniter 3.1.6, mpdf 7.0, HTML page main language: zh-CN, zh-HK, zh-TW
Here is what happens:
I was about to render an HTML page which was no lang tag, css font-family is "SF Pro SC" which is widely known as Apple's system default font. In CJK world, the "SF Pro SC" must fall back to "PingFang SC" to support zh language so I have to set default fonts and do some work to support:

public function create_pdf($pdf)
{

    $defaultConfig = (new Mpdf\Config\ConfigVariables())->getDefaults();
    $fontDirs = $defaultConfig['fontDir'];

    $defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
    $fontData = $defaultFontConfig['fontdata'];


    file_put_contents('php://stderr', print_r(array_merge($fontDirs, [
        base_url() . 'resource/fonts/SF-Pro-SC/v1/',
    ]), TRUE));
    
    $mpdf = new \Mpdf\Mpdf([
        'mode' => '+aCJK',
        'format' => 'A4',
        'mgl' => 15,
        'mgr' => 15,
        'mgt' => 15,
        'mgb' => 16,
        'mgh' => 9,
        'mgf' => 9,
        'orientation' => 'P',
        'watermark_font' => 'sfprosc',
        'fontDir' => array_merge($fontDirs, [
            base_url() . 'resource/fonts/SF-Pro-SC/v1/',
        ]),
        'fontdata' => $fontData + [
                'sfprosc' => [
                    'R' => "PingFangSC-Thin.ttf",
                    'B' => "PingFangSC-Regular.ttf",
                    'I' => "PingFangSC-Light.ttf",
                    'BI' => "PingFangSC-SemiBold.ttf"
                ]
            ],
        'default_font' => 'sfprosc',
        'autoLangToFont' => true,
        'autoScriptToLang' => true,
        'languageToFont' => new CustomLanguageToFontImplementation(),
        'debugfonts' => true
    ]);
    $mpdf->WriteHTML($pdf['html']);
    if (isset($pdf['attach'])) {
        $mpdf->Output('./resource/tmp/' . $pdf['filename'], 'F');
        return base_url() . 'resource/tmp/' . $pdf['filename'];
    } else {
        $mpdf->Output($pdf['filename'], 'D');
        exit;
    }
}

I choose the customise word "sfprosc" to link the font file and set it to be the default font, then I set 'mode' => '+aCJK', 'watermark_font' => 'sfprosc', and both autoLangToFont and autoScriptToLang are TRUE,

Something weird is after I added 'fontdata' config variable, the page is freezing and nothing to display after running this function. Also something I have to change a little bit is the implementation of CustomLanguageToFontImplementation(), I cannot extends the interface like the documents suggested:
class CustomLanguageToFontImplementation implements \Mpdf\Language\LanguageToFontInterface
{

public function getLanguageOptions($llcc, $adobeCJK)
{

    $tags = explode('-', $llcc);
    $lang = strtolower($tags[0]);
    $country = '';
    $script = '';
    if (!empty($tags[1])) {
        if (strlen($tags[1]) === 4) {
            $script = strtolower($tags[1]);
        } else {
            $country = strtolower($tags[1]);
        }
    }
    if (!empty($tags[2])) {
        $country = strtolower($tags[2]);
    }

    $unifont = '';
    $coreSuitable = false;

    if ($lang && ($lang == 'zh' || $lang == 'zho')) {
        $unifont = 'sfprosc';
        if ($adobeCJK) {
            $unifont = 'sfprosc';
            if ($country === 'HK' || $country === 'TW') {
                $unifont = 'sfprosc';
            }
        }
        return [false, $unifont];
    } else {
        /* Undetermined language - script used */
        $unifont = 'sfprosc';
        return [false, $unifont];
    }

    return parent::getLanguageOptions($llcc, $adobeCJK);
}

}

In mpdf6.0, I only force the $unifont = 'sfprosc' in the config_lang2fonts.php before return array($coreSuitable, $unifont); and that's working fine.

Error : Word is too long to fit in table

Hi here!

I wrote an mpdf html with tables and it keeps sending me this error saying "Word is too long to fit in table - " no matter what's the length of strings I have in tds. This is an example of my html:

$mpdf = new Mpdf([
'default_font' => 'roboto',
'table_error_report' => true
]);

$mpdf->SetHTMLFooter('






Joe Dree
5 years experience
Web developer, Web designer, UX Designer
New York, USA

');

How do I fix this?Thank you

Please provide support for HelveticaNeue and helveticaneue-boldcond

We need to use these fonts in our pdf. I tried to update $pdf->fontdata to accomodate these fonts. Event update constant "_MPDF_SYSTEM_TTFONTS" that's holding path to fonts library but nothing.

Lemme know if there is a way to add support for custom fonts. Otherwise please support these fonts.

Thanks

how explain difference of usage of mpdf-variables

How explain difference between:

  • variables that are could be used as attributes ($mpdf->variablename)
  • and these that could be only use as configuration parameter in the $config array of the mPDF constructor?

I spot that sometimes is written:
Set as a <a href="{{ "/configuration/configuration-v7-x.html" | prepend: site.baseurl }}">configuration variable</a>

And /reference/mpdf-variables/overview.html lists a lot of variables that only should be used on initiation of DOCUMENT.

But from the variable pages this difference in usage is not clear.
Who has suggestions for a simple manner to make these difference in usage clear on the variable pages?

name convention for mpdf-variables

mpdf variables are handled since the mpdf 7.0 version as values with are defined in the $config array.

See
/configuration/configuration-v7-x.html
/reference/mpdf-variables/overview.html
/reference/mpdf-functions/construct.html

The naming of the mpdf-variables is not consistent. What would be a preferred manner?

Now in use are:

  • the variable string <a href="{{ "/reference/mpdf-variables/aliasnbpggp.html" | prepend: site.baseurl }}">aliasNbPgGp</a>
    -> [aliasNbPgGp]
  • the variable <span class="parameter">$aliasNbPgGp</span>
    -> [$aliasNbPgGp]
  • The <a href="{{ "/configuration/configuration-v7-x.html" | prepend: site.baseurl }}">configuration variable</a> ``useActiveForms`` should be set ...
    -> [configuration variable] useActiveForms

Some thoughts:

  • I now prefer the first option. But from that layout it is not direct visible that it is a link to /reference/mpdf-variable/...
  • adding $ before all variables looks not logic, because some variable may only be used as configuration parameter in the $config array of the constructor.
  • $variablename is also bit different than the actual syntax, $mpdf->variablename.

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.