Разбитые изображения в phpwkhtmltopdf - PullRequest
0 голосов
/ 27 апреля 2018

Что следует отметить, я проверил это на двух разных серверах, Debian 9 и Ubuntu 14.04, и та же ошибка сохраняется. Сейчас я использую Ubuntu 14.04 с PHP 5, я установил composer, я правильно установил и wkhtmltopdf, и phpwkhtmltopdf. Откуда я это знаю? Что ж, wkhtmltopdf / image работает через CLI, phpwkhtmltopdf также работает через PHP, однако, когда я пытаюсь отправить изображение клиенту в виде встроенного дисплея или загрузить изображение, оно искажается. Например;

  1. Посетите желаемый URL, для нас его test.php
  2. Phpwkhtmltopdf будет отправлять команды, которые связаны с версией CLI wkhtmltopdf
  3. Как только страница загрузится, она перейдет на google.com, сохраните снимок экрана на диске /var/www/html/tmp/page.jpg, и это изображение откроется / отобразится нормально, однако, когда я пытаюсь использовать $image->send('page.jpg'); отправленное изображение повреждено / не открывается.

Я сделал два изменения в системе, я отключил mod_deflate в apache2 и также увеличил параметры max_filesize в файле конфигурации apache2 php.ini.

* Зависимости 1016 *

Живой пример

http://155.254.35.63/test.php // Generate the image
http://155.254.35.63/tmp/page.png // The image file generated

test.php

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

?>

<?php

$loader = require __DIR__ . '/vendor/autoload.php';

?>

<?php

use mikehaertl\wkhtmlto\Image;

$image = new \mikehaertl\wkhtmlto\Image('https://www.google.co.uk/search?q=what+is+the+time&oq=what+is+the+time&aqs=chrome.0.69i59j69i60l3j0l2.2977j0j4&sourceid=chrome&ie=UTF-8');
$image->setOptions(array(
'binary' => '/usr/local/bin/wkhtmltoimage',
'type' => 'png'
));

$image->saveAs('/var/www/html/tmp/page.png');

header('Content-Type: image/png');
echo file_get_contents('/var/www/html/tmp/page.jpg');

?>

File.php (строки с 72 по 83)

<?php
namespace mikehaertl\tmp;

/**
 * File
 *
 * A convenience class for temporary files.
 *
 * @author Michael Härtl <haertl.mike@gmail.com>
 * @version 1.1.0
 * @license http://www.opensource.org/licenses/MIT
 */
class File
{
    /**
     * @var bool whether to delete the tmp file when it's no longer referenced or when the request ends.
     * Default is `true`.
     */
    public $delete = true;

    /**
     * @var string the name of this file
     */
    protected $_fileName;

    /**
     * Constructor
     *
     * @param string $content the tmp file content
     * @param string|null $suffix the optional suffix for the tmp file
     * @param string|null $prefix the optional prefix for the tmp file. If null 'php_tmpfile_' is used.
     * @param string|null $directory directory where the file should be created. Autodetected if not provided.
     */
    public function __construct($content, $suffix = null, $prefix = null, $directory = null)
    {
        if ($directory===null) {
            $directory = self::getTempDir();
        }

        if ($prefix===null) {
            $prefix = 'php_tmpfile_';
        }

        $this->_fileName = tempnam($directory,$prefix);
        if ($suffix!==null) {
            $newName = $this->_fileName.$suffix;
            rename($this->_fileName, $newName);
            $this->_fileName = $newName;
        }
        file_put_contents($this->_fileName, $content);
    }

    /**
     * Delete tmp file on shutdown if `$delete` is `true`
     */
    public function __destruct()
    {
        if ($this->delete) {
            unlink($this->_fileName);
        }
    }

    /**
     * Send tmp file to client, either inline or as download
     *
     * @param string|null $filename the filename to send. If empty, the file is streamed inline.
     * @param string $contentType the Content-Type header
     * @param bool $inline whether to force inline display of the file, even if filename is present.
     */
    public function send($filename = null, $contentType, $inline = false)
    {
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Type: image/png');
        header('Content-Transfer-Encoding: binary');

        if ($filename!==null || $inline) {
            $disposition = $inline ? 'inline' : 'attachment';
            header("Content-Disposition: $disposition; filename=\"$filename\"");
        }

        readfile($this->_fileName);
    }

    /**
     * @param string $name the name to save the file as
     * @return bool whether the file could be saved
     */
    public function saveAs($name)
    {
        return copy($this->_fileName, $name);
    }

    /**
     * @return string the full file name
     */
    public function getFileName()
    {
        return $this->_fileName;
    }

    /**
     * @return string the path to the temp directory
     */
    public static function getTempDir()
    {
        if (function_exists('sys_get_temp_dir')) {
            return sys_get_temp_dir();
        } elseif ( ($tmp = getenv('TMP')) || ($tmp = getenv('TEMP')) || ($tmp = getenv('TMPDIR')) ) {
            return realpath($tmp);
        } else {
            return '/tmp';
        }
    }

    /**
     * @return string the full file name
     */
    public function __toString()
    {
        return $this->_fileName;
    }
}

php.ini

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir = /var/www/html/tmp

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 50M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

В лог-файле apache есть none (0) ошибок, что на самом деле отвлекает меня от проблемы. Я попытался найти разрешение с помощью разработчика, но не посмотрел;

https://github.com/mikehaertl/phpwkhtmltopdf/issues/278

Буду признателен за помощь в этом.

1 Ответ

0 голосов
/ 27 апреля 2018

Я изучил файл page.jpg, созданный на вашем тестовом сайте. Сам файл не поврежден. Это значит, что с вашей сантехникой все в порядке.

Заголовок файла показывает, что вместо стандартного файла JPEG у вас есть вариант JFIF. Посмотрите, можете ли вы настроить библиотеку для создания файла PNG, чтобы обойти эту проблему.

Редактировать: теперь, когда я вижу, что сгенерированный файл правильный, посмотрите, можете ли вы просто передавать содержимое вместо использования $ image-> send. Отправь сам:

header('Content-Type: image/png');
echo file_get_contents('/var/www/html/tmp/page.jpg');
...