Manual php html pdf

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP library generating PDF files from UTF-8 encoded HTML

License

mpdf/mpdf

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  Bitrix отложить загрузку css

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

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.

⚠ 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.

PHP versions and extensions

  • PHP >=5.6 = 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 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.

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.

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

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

$ composer require mpdf/mpdf 

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

 require_once __DIR__ . '/vendor/autoload.php'; $mpdf = new \Mpdf\Mpdf(); $mpdf->WriteHTML('

Hello world!

'
); $mpdf->Output();

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

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.

 $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 is available at https://mpdf.github.io/.

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.

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

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.

About

PHP library generating PDF files from UTF-8 encoded HTML

Источник

Download documentation

The PHP manual is available in a selection of languages and formats. Pick a language and format from the table below to start downloading.

Notes to read before you download

  • The English version should be considered the most accurate, since translations are based on that version. Most of the translations are not complete, and contain English parts.
  • If you are looking for PHP 5 documentation, please read this explanation.
  • If you are looking for PHP 4 documentation, please read this explanation.

If you are using Windows XP SP2 or later and you are going to download the documentation in CHM format, you need to «unblock» the file after downloading it by right-clicking on it in Windows Explorer and selecting the «Properties» menu item, then clicking on the «Unblock» button (on Windows Vista this is within the «Security» options). Failure to unblock the documentation file may result in error messages including «Navigation to the webpage was canceled» due to Windows security restrictions.

Single HTML file Many HTML files HTML Help file HTML Help file (with user notes)
English html.gz tar.gz chm chm
Brazilian Portuguese html.gz tar.gz chm chm
Chinese (Simplified) html.gz tar.gz chm chm
French html.gz tar.gz chm chm
German html.gz tar.gz chm chm
Japanese html.gz tar.gz chm chm
Russian html.gz
Size: 6273Kb
Date: 24 Jul 2023
tar.gz
Size: 11866Kb
Date: 24 Jul 2023
chm
Size: 14720Kb
Date: 21 Jul 2023
chm
Size: 28457Kb
Date: 21 Jul 2023
Spanish html.gz tar.gz chm chm
Turkish html.gz tar.gz chm chm

You can read the documentation online in various languages. The Documentation HOWTO, and archive manuals are also available from our documentation page.

The manual is also available via *nix style man pages. To install and use:

  • Install: pear install doc.php.net/pman
  • Upgrade: pear upgrade doc.php.net/pman
  • Example usage: pman strlen

Источник

doctor Brain

Итак, нам нужно получить файл в формате PDF из HTML-документа, стилизованного с помощью CSS. К сожалению, PHP не имеет встроенных функций, позволяющих выполнить такую задачу. Поэтому мы воспользуемся помощью библиотеки, созданной сторонними разработчиками.

Я полагаю, что конвертер html2pdf является отличным выбором, так как данная библиотека бесплатна и не имеет ограничений, связанных с ее распространением и модификацией даже в случае коммерческого использования. Несомненно, приятным моментом является то, что html2pdf не только преобразует HTML-синтаксис в PDF-формат, но и учитывает используемые для элементов конвертируемой страницы свойства CSS.

Также, следует отметить, что html2pdf работает с широким диапазоном версий PHP: от 5.6 до 7.4. Этот факт указывает на целесообразность использования данного конвертера для достаточно старых проектов.

Установка HTML2PDF

Конвертор html2pdf можно забрать из репозитария на github или установить с помощью Composer’а. В нашем примере мы используем последний вариант:

composer require spipu/html2pdf 

Интеграция HTML2PDF в проект

Следующим шагом необходимо подключить конвертер к существующему проекту:

use Spipu\Html2Pdf\Html2Pdf; 

Преобразование HTML в PDF

Для того, чтобы получить PDF-документ и вывести его в окно браузера можно использовать следующий код:

$html2pdf = new Html2Pdf(); $html2pdf->writeHTML('

Title

Convert this HTML to PDF please!

'); $html2pdf->output('myPdf.pdf'); // Создаем PDF-документ и выводим его в браузер

Для того, чтобы создать PDF-документ и сразу перейти к его загрузке для функции output нужно установить второй аргумент D :

$html2pdf = new Html2Pdf(); $html2pdf->writeHTML('

Title

Convert this HTML to PDF please!

'); $html2pdf->output('myPdf.pdf', 'D'); // Создаем PDF-документ и сразу его загружаем

Вывод PDF-документа в браузер

Можно заметить, что по умолчанию функция output создает PDF-документ и выводит его в окно браузера. В результате, можно не только просмотреть в окне браузера, но и скачать преобразованный в PDF-формат файл.

Заключение

html2pdf далеко не единственная библиотека, позволяющая конвертировать HTML-документ в формат PDF. Тем не менее, она проста в использовании, имеет хорошее описание и не требует дополнительных затрат.

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

Оцените статью