xref: /plugin/totext/vendor/prinsfrank/pdfparser/src/PdfParser.php (revision 0fbee1892eb8b7339ce48e27e48e3fc821a8695f) !
1<?php
2declare(strict_types=1);
3
4namespace PrinsFrank\PdfParser;
5
6use PrinsFrank\PdfParser\Document\CrossReference\CrossReferenceSourceParser;
7use PrinsFrank\PdfParser\Document\Document;
8use PrinsFrank\PdfParser\Document\Security\StandardSecurity;
9use PrinsFrank\PdfParser\Document\Version\VersionParser;
10use PrinsFrank\PdfParser\Exception\InvalidArgumentException;
11use PrinsFrank\PdfParser\Exception\PdfParserException;
12use PrinsFrank\PdfParser\Stream\FileStream;
13use PrinsFrank\PdfParser\Stream\InMemoryStream;
14use PrinsFrank\PdfParser\Stream\Stream;
15
16/** @api */
17class PdfParser {
18    /** @throws PdfParserException */
19    public function parse(Stream $stream, ?StandardSecurity $security = null): Document {
20        return new Document(
21            $stream,
22            VersionParser::parse($stream),
23            CrossReferenceSourceParser::parse($stream),
24            $security,
25        );
26    }
27
28    /**
29     * @param bool $useInMemoryStream if set to false, a handle to the file itself will be used. This uses less memory, but will be significantly slower
30     * @throws PdfParserException
31     */
32    public function parseFile(string $filePath, bool $useInMemoryStream = true, ?StandardSecurity $security = null): Document {
33        if ($useInMemoryStream) {
34            $fileContent = @file_get_contents($filePath);
35            if ($fileContent === false) {
36                throw new InvalidArgumentException(sprintf('Failed to open file at path "%s"', $filePath));
37            }
38
39            $stream = new InMemoryStream($fileContent);
40        } else {
41            $stream = FileStream::openFile($filePath);
42        }
43
44        return $this->parse($stream, $security);
45    }
46
47    /**
48     * @param bool $useFileCache if set to true, the file will be cached to a temporary file. This will use less memory, but will be significantly slower
49     * @throws PdfParserException
50     */
51    public function parseString(string $content, bool $useFileCache = false, ?StandardSecurity $security = null): Document {
52        if ($useFileCache) {
53            $stream = FileStream::fromString($content);
54        } else {
55            $stream = new InMemoryStream($content);
56        }
57
58        return $this->parse($stream, $security);
59    }
60}
61