使用 PHP LibreOffice 和 ncjoes/office-converter 库转换文件

Converting files using PHP LibreOffice and the ncjoes/office-converter library

我将 ampps 用作 windows 10 apache 服务器,我的 php 版本是 7.3。我从 LibreOffice 下载页面下载并安装在我的电脑上。然后我通过 composer https://github.com/ncjoes/office-converter 安装了这个库。我按照给出的示例进行尝试,但它不会转换并给出错误。如果您能在我错的地方帮助我,我将不胜感激。这是我的代码示例和我遇到的错误:

<?php
if (!file_exists(__DIR__.'/vendor/autoload.php')) echo 'autoload.php mevcut değil!';
else require __DIR__.'/vendor/autoload.php';

use NcJoes\OfficeConverter\OfficeConverter;
use PHPUnit\Framework\TestCase;

class OfficeConverterTest extends TestCase
{
    /**
     * @var OfficeConverter $converter
     */
    private $converter;
    private $outDir;

    public function setUp()
    {
        parent::setUp();

        $DS = DIRECTORY_SEPARATOR;
        $file = __DIR__."{$DS}sources{$DS}test.docx";
        $this->outDir = __DIR__."{$DS}results";

        $this->converter = new OfficeConverter($file, $this->outDir);
    }

    public function testDocxToPdfConversion()
    {
        $output = $this->converter->convertTo('result.pdf');

        $this->assertFileExists($output);
    }

    public function testDocxToHtmlConversion()
    {
        $output = $this->converter->convertTo('result.html');

        $this->assertFileExists($output);
    }
}

$donustur = new OfficeConverterTest();
$donustur->testDocxToPdfConversion();
?>

Fatal error: Uncaught Error: Call to a member function convertTo() on null in C:\Program Files\Ampps\www\converter\converter.php:29 Stack trace: #0 C:\Program Files\Ampps\www\converter\converter.php(43): OfficeConverterTest->testDocxToPdfConversion() #1 {main} thrown in C:\Program Files\Ampps\www\converter\converter.php on line 29

当 运行 测试时,我们应该将 运行 留给 phpunit,但您试图手动调用(在代码的最后两行)。

但是如果你坚持要手动调用,就改成:

$donustur = new OfficeConverterTest();
$donustur->testDocxToPdfConversion();

进入:

$donustur = new OfficeConverterTest();
$donustur->setUp();
$donustur->testDocxToPdfConversion();

So that you call setUp() which phpunit would normally call for you automatically.

另请参阅: How do I run all my PHPUnit tests?
How to run single test method with phpunit?

页面示例

如果您想在网页上使用此逻辑,它应该类似于:

<?php
if (!file_exists(__DIR__.'/vendor/autoload.php')) echo 'autoload.php mevcut değil!';
else require __DIR__.'/vendor/autoload.php';

use NcJoes\OfficeConverter\OfficeConverter;

echo 'Converting...<br>';

$input = __DIR__ . '/test.docx';
$converter = new OfficeConverter($input, __DIR__.'/results');
$output = $converter->convertTo('result.pdf');

echo 'Saved at:' . $output . '<br>';