PHPOffice/PHPWord · error · PhpOffice\PhpWord\Exception\Exception

Could not open file $filename for writing.

Error message

Could not open file $filename for writing.

What it means

prepareForSave opens the target $filename with fopen(..., 'wb') before rendering the PDF; a false return means the path is unwritable (bad directory, missing permission, disk error), so saving cannot proceed.

Solutions

  1. Check that the target directory exists and the PHP process has write permission on it.
  2. Verify the filename/path is valid and the disk is not full or read-only.
  3. Save to a temporary writable location and move the file afterward.
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at src/PhpWord/Writer/PDF/AbstractRenderer.php:195 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of PHPOffice/PHPWord@aef95c0415 (2026-09-14). Data as JSON: /api/errors/3fb0d3849944ad7c. Report an issue: GitHub.

Appendix: source

Thrown at src/PhpWord/Writer/PDF/AbstractRenderer.php:195

        $this->orientation = $value;

        return $this;
    }

    /**
     * Save PhpWord to PDF file, pre-save.
     *
     * @param string $filename Name of the file to save as
     *
     * @return resource
     */
    protected function prepareForSave($filename = null)
    {
        $fileHandle = fopen($filename, 'wb');
        // @codeCoverageIgnoreStart
        // Can't find any test case. Uncomment when found.
        if ($fileHandle === false) {
            throw new Exception("Could not open file $filename for writing.");
        }
        // @codeCoverageIgnoreEnd

        return $fileHandle;
    }

    /**
     * Save PhpWord to PDF file, post-save.
     *
     * @param resource $fileHandle
     */
    protected function restoreStateAfterSave($fileHandle): void
    {
        fclose($fileHandle);
    }
}

View on GitHub (pinned to aef95c0415)