Search code examples
phppdfpngfpdf

Generate a PDF file (include PNG image) with PHP


Problem: need to convert the base64 code PNG images obtained from the textarea, a PNG image (a binary file with the extension. Png - image.png) with PHP and store the image on the server. Then with the help of PHP and FPDF class to generate a PDF file (example1.pdf), inserting the previously saved PNG image. The resulting PDF file is also stored on the server.

Here is the file createPdfFromBase64.php, which I have turned:

<?php
    #header('Content-Type: image/png');

    $base64 = $_POST['base64']; // Получаем base64 код PNG изображения из <textarea id="base64" name="base64"></textarea>

    #echo("$base64");

    $base64 = str_replace(' ','+',$base64); // If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted.

    $data = base64_decode($base64); // Декодирует данные base64 и записывает их в переменную $data

    echo("$data");

    $filename = "image.png";

    // Пишем содержимое в файл image.png
    file_put_contents($filename, $data); // Сохраняем изображение image.png на сервере

    // Подключаем класс FPDF, для генерации PDF документа
    require('/home/u552896297/public_html/FPDF/fpdf.php');

    // Создаем FPDF объект
    $pdf= new FPDF();

    // Устанавливаем свойства документа
    $pdf->SetAuthor('Evgeniy Privalov'); // Устанавливаем автора PDF документа.
    $pdf->SetTitle('PDF generator'); // Устанавливаем title PDF документа.

    // Настройки страницы. Теперь когда главное сделано, приступим к созданию страницы.
    $pdf->AddPage('P'); // Книжная ориентация страницы
    $pdf->SetDisplayMode('real','default'); //Функция SetDisplayMode определяет как будет отображена страница. Вы можете определить параметры увеличения и разметки. В примере мы используем 100% увеличение и разметку по умолчанию, определенную в программе, используемой для просмотра.

    // Вставляем PNG картинку в верхний левый угол с разрешением в 300 точек на дюйм (300dpi)
    $pdf->Image('image.png', 10, 10, -300);

    // В конце мы выведем наш результат используя функцию Output
    $pdf->Output('example1.pdf', 'F'); // Здесь мы указали имя файла и параметр вывода, в данном случае "F". "F"-параметр сохранит результат в файл example1.pdf
?>

The index.html file is here - http://print-online.16mb.com/. Must first press the "Save business card"("Сохранить визитку") and then click the "Convert to PDF"("Конвертировать в PDF").

But when generating PDF, an error FPDF error: Not a PNG file: image.png

Please help me solve the problem!

UPD: image.png file is created on the server, but it does not appear in your browser! http://print-online.16mb.com/image.png


Solution

  • Obviously something goes wrong with uploading or your edits afterwards. Use http://www.php.net/manual/en/ref.fileinfo.php to test the uploaded image and see if the returned info is as you expected it.