spiritix / php-chrome-html2pdf

A PHP library for converting HTML to PDF using Google Chrome
MIT License
112 stars 29 forks source link

fixed double escape bugs #30

Closed ZsgsDesign closed 3 years ago

ZsgsDesign commented 3 years ago

In the current version, the following codes output a PDF that has its header wrongly generated.

$converter->setOptions([
    'printBackground' => false,
    'displayHeaderFooter' => true,
    'format' => 'a4',
    'margin' => [
        'top' => '12mm',
        'right' => '12mm',
        'left' => '12mm',
        'bottom' => '12mm',
    ],
    'headerTemplate' => '<div class="header" style="margin: 0; width: 100%; text-align: left; font-size: 12px;">Generated by NOJ - https://github.com/ZsgsDesign/NOJ</div>',
    // 'footerTemplate' => view('pdf.contest.footer')->render(),
]);
$outputBinary = $converter->convert();

image

After carefully checked the source code, I found the problem:

private function buildCommand(): string
{
    $options = ProcessUtil::escapeShellArgument(json_encode($this->getOptions()));
    $command = $this->getBinaryPath() . ' -o ' . $options;

    return $command;
}

In escapeShellArgument(), the process would be:

private static function escapeShellArgumentWindows(string $argument): string
{
    // Double up existing backslashes
    $argument = preg_replace('/\\\/', '\\\\\\\\', $argument);

    // Double up double quotes
    $argument = preg_replace('/"/', '""', $argument);

    // Double up percents.
    $argument = preg_replace('/%/', '%%', $argument);

    // Add surrounding quotes.
    $argument = '"' . $argument . '"';

    return $argument;
}

Note that drupal uses \\\ instead of \\\\, but it's OK with current PHP, so it's not a bug right now. The problem here is drupal doesn't consider the situation of formatted JSON with slashes so it just adding another slash to the existing slash, making node parsing it to \ after popen.

There are two ways to fix this, either using PHP or node.js. I am proposing adding option JSON_UNESCAPED_SLASHES to json_encode to avoid such bugs.

Here is the outcome: image

spiritix commented 3 years ago

Thanks a lot, here you go: https://github.com/spiritix/php-chrome-html2pdf/releases/tag/v1.6.1