-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExtractedPdf.php
More file actions
105 lines (93 loc) · 2.72 KB
/
Copy pathExtractedPdf.php
File metadata and controls
105 lines (93 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
declare(strict_types=1);
namespace Mindee\Extraction;
use Mindee\Dependency\DependencyChecker;
use Mindee\Error\ErrorCode;
use Mindee\Error\MindeePdfException;
use Mindee\Error\MindeeUnhandledException;
use Mindee\Input\BytesInput;
use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfParser\PdfParserException;
use const DIRECTORY_SEPARATOR;
/**
* An extracted sub-Pdf.
*/
class ExtractedPdf
{
/**
* Initializes a new instance of the ExtractedPdf class.
*
* @param string $pdfBytes A binary string representation of the PDF.
* @param string $filename Name of the original file.
*
* @throws MindeeUnhandledException Throws if PDF operations aren't supported.
*/
public function __construct(protected string $pdfBytes, public string $filename)
{
DependencyChecker::isImageMagickAvailable();
DependencyChecker::isGhostscriptAvailable();
}
/**
* Wrapper for pdf GetPageCount().
*
* @return integer the number of pages in the file
*
* @throws MindeePdfException Throws if FPDI is unable to process the file.
*/
public function getPageCount(): int
{
try {
$pdfHandle = new Fpdi();
$tempFilename = tempnam(sys_get_temp_dir(), 'extracted_pdf_');
file_put_contents($tempFilename, $this->pdfBytes);
return $pdfHandle->setSourceFile($tempFilename);
} catch (PdfParserException $e) {
throw new MindeePdfException(
"Couldn't open PDF file.",
ErrorCode::PDF_CANT_CREATE,
$e
);
}
}
/**
* Write the PDF to a file.
*
* @param string $outputPath The output directory (must exist).
*/
public function writeToFile(string $outputPath): void
{
$pdfPath = $outputPath . DIRECTORY_SEPARATOR . $this->filename;
if ('' !== basename($outputPath)) {
if (!($pdfPath = realpath($outputPath))) {
$pdfPath = $outputPath;
}
}
if (!str_ends_with(strtolower($pdfPath), 'pdf')) {
$pdfPath .= '.pdf';
}
file_put_contents($pdfPath, $this->pdfBytes);
}
/**
* Return the file in a format suitable for sending to MindeeClient for parsing.
*
* @return BytesInput bytes input for the image
*/
public function asInputSource(): BytesInput
{
return new BytesInput($this->pdfBytes, $this->filename);
}
/**
* @return string the pdf bytes
*/
public function getPdfBytes(): string
{
return $this->pdfBytes;
}
/**
* @return string the name of the file
*/
public function getFilename(): string
{
return $this->filename;
}
}