anam-hossain / phantommagick

PhantomMagick provides a simple API to ease the process of converting HTML to PDF or images
163 stars 45 forks source link

$conv->addPage("<html><body>TEST</body></html>") doesn't work on Windows 7 #27

Open DominikStyp opened 7 years ago

DominikStyp commented 7 years ago

I've profided a fix for the following example, which doesn't work on Windows 7.

$options = [
            'format' => 'A4',
            'orientation' => 'landspace',
        ];
$conv = new \Anam\PhantomMagick\Converter();
$conv->setPdfOptions($options)
            ->addPage("<html><body><h1>Test Page 1</h1></body></html>")
            ->addPage("<html><body><h1>Test Page 2</h1></body></html>")
            ->serve();

Prolblem lies in saveLocal() method, which tries to run command with wrong temporary file prefix. On Windows you have to use prefix file:/// for that purpose. I've provided quick and dirty fix for that, but it should be fixed in source code:.

$conv = new class () extends \Anam\PhantomMagick\Converter {
                public function saveLocal($filename)
                {
                    // FIX FOR WINDOWS
                    $filePrefix = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? "file:///" : "";
                    if (self::$multiPage) {
                        if (count($this->pages)) {
                            $this->put(implode('', $this->pages));
                        }
                        return $this->run(self::$scripts['converter'], $filePrefix.$this->getTempFilePath(), $filename, self::$pdfOptions);
                    }

                    // Single page pdf
                    if (self::$format === 'pdf') {
                        return $this->run(self::$scripts['converter'], $this->getSource(), $filename, self::$pdfOptions);
                    }

                    // Image
                    return $this->run(self::$scripts['converter'], $this->getSource(), $filename, self::$imageOptions);
                }  
        };
BARNZ commented 6 years ago

Thanks, this fix worked for me on php 7.1 + windows 10.

The error I was previously getting after calling save() was:

"""
Unable to load the address!\n
Error opening url "c:%5CWINDOWS%5CTEMP/8111382345a52fa7498260.html": Protocol "c" is unknown\n
"""