HTML to PDF

    html to pdf

    Back in 2008, a similar article was already written and I tried to apply the knowledge, but, unfortunately, could not cope with the Russian language (I worked for denwer, I didn’t on the hosting). Perhaps the lack of experience affected. And recently I found a good library and decided to share. The topic, most likely, is addressed to a novice programmer and does not claim to be anything.

    To begin, we set the task:


    1. The conversion process should be simple - a minimum of code;
    2. Display Russian language “out of the box”;
    3. Understand html tags, images, CSS;
    4. Use a free and well-documented library.

    Input data


    The process itself is so simple that there is no fundamental difference in which framework to use it. We will convert data from HTML to PDF using mPDF .

    Implementation


    Download and unpack the latest version of mPDF into the root directory . In the same place, create the index.php file and add the following code:
    $html = 'Пример 1Пример 2Пример 3Пример 4
    Пример 5Пример 6Пример 7mPDF
    ';

    include("mpdf50/mpdf.php");

    $mpdf = new mPDF('utf-8', 'A4', '8', '', 10, 10, 7, 7, 10, 10); /*задаем формат, отступы и.т.д.*/
    $mpdf->charset_in = 'cp1251'; /*не забываем про русский*/

    $stylesheet = file_get_contents('style.css'); /*подключаем css*/
    $mpdf->WriteHTML($stylesheet, 1);

    $mpdf->list_indent_first_level = 0;
    $mpdf->WriteHTML($html, 2); /*формируем pdf*/
    $mpdf->Output('mpdf.pdf', 'I');
    ?>


    Css file code:
    table {text-align: center;font-size: 20pt;width: 100%;}

    The library can be checked on the official website . Or, for example, form the above example.

    That's all. Thanks.

    PS: Many thanks to habrowsers: rachiu, Zorkus, FeNUMe, Atrax, AusTiN for their support and human attitude to newcomers.

    Also popular now: