-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPDFExtractor.java
More file actions
173 lines (157 loc) · 5.88 KB
/
PDFExtractor.java
File metadata and controls
173 lines (157 loc) · 5.88 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package com.mindee.extraction;
import static com.mindee.pdf.PDFUtils.mergePdfPages;
import com.mindee.MindeeException;
import com.mindee.input.InputSourceUtils;
import com.mindee.input.LocalInputSource;
import com.mindee.product.invoicesplitter.InvoiceSplitterV1InvoicePageGroup;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
/**
* PDF extraction class.
*/
public class PDFExtractor {
private final PDDocument sourcePdf;
private final String filename;
/**
* Init from a path.
*
* @param filePath Path to the file.
* @throws IOException Throws if the file can't be accessed.
*/
public PDFExtractor(String filePath) throws IOException {
this(new LocalInputSource(filePath));
}
/**
* Init from a {@link LocalInputSource}.
*
* @param source The local source.
* @throws IOException Throws if the file can't be accessed.
*/
public PDFExtractor(LocalInputSource source) throws IOException {
this.filename = source.getFilename();
if (source.isPdf()) {
this.sourcePdf = Loader.loadPDF(source.getFile());
} else {
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
BufferedImage bufferedImage = byteArrayToBufferedImage(source.getFile());
PDImageXObject pdImage = LosslessFactory.createFromImage(document, bufferedImage);
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
contentStream.drawImage(pdImage, 100, 600, (float) pdImage.getWidth() / 2,
(float) pdImage.getHeight() / 2);
}
this.sourcePdf = document;
}
}
/**
* @return The number of pages in the file.
*/
public int getPageCount() {
return sourcePdf.getNumberOfPages();
}
/**
* Converts an array to a buffered image.
*
* @param byteArray Raw byte array.
* @return a valid ImageIO buffer.
* @throws IOException Throws if the file can't be accessed.
*/
public static BufferedImage byteArrayToBufferedImage(byte[] byteArray) throws IOException {
try (ByteArrayInputStream stream = new ByteArrayInputStream(byteArray)) {
return ImageIO.read(stream);
}
}
/**
* Given a list of page indexes, extracts the corresponding documents.
*
* @param pageIndexes List of page indexes.
* @return A list of extracted files.
* @throws IOException Throws if the file can't be accessed.
*/
public List<ExtractedPDF> extractSubDocuments(List<List<Integer>> pageIndexes)
throws IOException {
List<ExtractedPDF> extractedPDFs = new ArrayList<>();
for (List<Integer> pageIndexElement : pageIndexes) {
if (pageIndexElement.isEmpty()) {
throw new MindeeException("Empty indexes not allowed for extraction.");
}
String[] splitName = InputSourceUtils.splitNameStrict(filename);
String fieldFilename =
splitName[0] + String.format("_%3s", pageIndexElement.get(0) + 1).replace(" ", "0")
+ "-"
+ String.format("%3s", pageIndexElement.get(pageIndexElement.size() - 1) + 1)
.replace(" ", "0") + "." + splitName[1];
extractedPDFs.add(
new ExtractedPDF(Loader.loadPDF(mergePdfPages(this.sourcePdf, pageIndexElement, false)),
fieldFilename));
}
return extractedPDFs;
}
/**
* Extract invoices from the given page indexes (from an invoice-splitter prediction).
*
* @param pageIndexes List of page indexes.
* @return a list of extracted files.
* @throws IOException Throws if the file can't be accessed.
*/
public List<ExtractedPDF> extractInvoices(
List<InvoiceSplitterV1InvoicePageGroup> pageIndexes
) throws IOException {
List<List<Integer>> indexes =
pageIndexes.stream().map(InvoiceSplitterV1InvoicePageGroup::getPageIndexes)
.collect(Collectors.toList());
return extractSubDocuments(indexes);
}
/**
* Extract invoices from the given page indexes (from an invoice-splitter prediction).
*
* @param pageIndexes List of page indexes.
* @param strict Whether the extraction should strictly follow the confidence scores or not.
* @return a list of extracted files.
* @throws IOException Throws if the file can't be accessed.
*/
public List<ExtractedPDF> extractInvoices(
List<InvoiceSplitterV1InvoicePageGroup> pageIndexes,
boolean strict
) throws IOException {
List<List<Integer>> correctPageIndexes = new ArrayList<>();
if (!strict) {
return extractInvoices(pageIndexes);
}
Iterator<InvoiceSplitterV1InvoicePageGroup> iterator = pageIndexes.iterator();
List<Integer> currentList = new ArrayList<>();
Double previousConfidence = null;
while (iterator.hasNext()) {
InvoiceSplitterV1InvoicePageGroup pageIndex = iterator.next();
Double confidence = pageIndex.getConfidence();
List<Integer> pageList = pageIndex.getPageIndexes();
if (confidence == 1.0 && previousConfidence == null) {
currentList = new ArrayList<>(pageList);
} else if (confidence == 1.0) {
correctPageIndexes.add(currentList);
currentList = new ArrayList<>(pageList);
} else if (confidence == 0.0 && !iterator.hasNext()) {
currentList.addAll(pageList);
correctPageIndexes.add(currentList);
} else {
correctPageIndexes.add(currentList);
correctPageIndexes.add(pageList);
}
previousConfidence = confidence;
}
return extractSubDocuments(correctPageIndexes);
}
}