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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
| public byte[] convertToPdf(List<byte[]> files) throws IOException { Tika tika = new Tika();
List<String> mimeTypes = files.stream().map(fileData -> { try (TikaInputStream tikaStream = TikaInputStream.get(fileData)) { return tika.detect(tikaStream); } catch (IOException e) { throw new RuntimeException(e); } }).collect(Collectors.toList());
if (mimeTypes.stream().noneMatch(mimeType -> mimeType != null && mimeType.toLowerCase().contains("pdf"))) { ByteArrayOutputStream finalOutputStream = new ByteArrayOutputStream(); PdfWriter finalWriter = new PdfWriter(finalOutputStream); PdfDocument finalPdf = new PdfDocument(finalWriter); Document finalDocument = new Document(finalPdf);
for (int i = 0; i < files.size(); i++) { byte[] fileData = files.get(i); String mimeType = mimeTypes.get(i);
try (InputStream inputStream = new ByteArrayInputStream(fileData)) { if (mimeType != null && (mimeType.toLowerCase().contains("png") || mimeType.toLowerCase().contains("jpg") || mimeType.toLowerCase().contains("jpeg"))) { com.itextpdf.io.image.ImageData imageData = ImageDataFactory.create(changeDPI(fileData)); Image image = new Image(imageData); PageSize pageSize = new PageSize(image.getImageWidth(), image.getImageHeight()); finalDocument.getPdfDocument().addNewPage(pageSize); finalDocument.setMargins(0, 0, 0, 0); finalDocument.add(image); if (i == files.size() - 1) { finalDocument.add(new AreaBreak(AreaBreakType.NEXT_PAGE)); finalDocument.close(); return finalOutputStream.toByteArray(); } } else if (mimeType != null && (mimeType.toLowerCase().contains("tiff") || mimeType.toLowerCase().contains("tif"))) { try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream)) { Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(imageInputStream); int pageCount = reader.getNumImages(true); for (int k = 0; k < pageCount; k++) { BufferedImage page = reader.read(k); try (ByteArrayOutputStream pageOutputStream = new ByteArrayOutputStream()) { ImageIO.write(page, "png", pageOutputStream); ImageData imageData = ImageDataFactory.create(pageOutputStream.toByteArray()); Image image = new Image(imageData); finalDocument.add(image); finalDocument.add(new AreaBreak(AreaBreakType.NEXT_PAGE)); } } } } } } catch (IOException e) { throw new RuntimeException(e); } }
finalDocument.close(); finalPdf.close();
return finalOutputStream.toByteArray(); } else {
int batchSize = 50; int totalFiles = files.size(); int batches = (int) Math.ceil((double) totalFiles / batchSize);
ExecutorService executorService = Executors.newFixedThreadPool(Math.min(batches, Runtime.getRuntime().availableProcessors()));
List<CompletableFuture<PDDocument>> futures = new ArrayList<>();
for (int i = 0; i < batches; i++) { int fromIndex = i * batchSize; int toIndex = Math.min((i + 1) * batchSize, totalFiles); List<byte[]> batchFiles = files.subList(fromIndex, toIndex);
CompletableFuture<PDDocument> future = CompletableFuture.supplyAsync(() -> { PDDocument batchPdf = new PDDocument(); PDFMergerUtility merger = new PDFMergerUtility(); for (byte[] fileData : batchFiles) { String mimeType = null; try { mimeType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(fileData)); } catch (IOException e) { throw new RuntimeException(e); } if (isPDF(fileData)) { try (InputStream inputStream = new ByteArrayInputStream(fileData)) { PDDocument sourcePdf = PDDocument.load(inputStream); merger.appendDocument(batchPdf, sourcePdf); sourcePdf.close(); } catch (IOException e) { e.printStackTrace(); } } else if (mimeType != null && (mimeType.toLowerCase().contains("png") || mimeType.toLowerCase().contains("jpg") || mimeType.toLowerCase().contains("jpeg"))) { PDPage page = createPDPageFromImage(batchPdf, fileData); if (page != null) { batchPdf.addPage(page); } } else if (mimeType != null && (mimeType.toLowerCase().contains("tiff") || mimeType.toLowerCase().contains("tif"))) { List<byte[]> tiffImages = null; try { tiffImages = tiffToImage(fileData); } catch (IOException e) { throw new RuntimeException(e); } for (byte[] imageFileData : tiffImages) { PDPage page = createPDPageFromImage(batchPdf, imageFileData); if (page != null) { batchPdf.addPage(page); } } } } return batchPdf; }, executorService);
futures.add(future); }
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); allFutures.join();
PDDocument finalPdf = new PDDocument(); PDFMergerUtility merger = new PDFMergerUtility();
for (CompletableFuture<PDDocument> future : futures) { PDDocument batchPdf = future.join(); merger.appendDocument(finalPdf, batchPdf); batchPdf.close(); } PDPage blankPage = new PDPage(); finalPdf.addPage(blankPage); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); finalPdf.save(outputStream); finalPdf.close();
executorService.shutdown();
return outputStream.toByteArray(); }
}
public byte[] changeDPI(byte[] imageData) { try { BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); writer.setOutput(ios);
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), null); IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree("javax_imageio_1.0"); IIOMetadataNode dimension = getChildNode(root, "Dimension");
if (dimension == null) { dimension = new IIOMetadataNode("Dimension"); root.appendChild(dimension); }
IIOMetadataNode horiz = getChildNode(dimension, "HorizontalPixelSize"); if (horiz == null) { horiz = new IIOMetadataNode("HorizontalPixelSize"); dimension.appendChild(horiz); }
IIOMetadataNode vert = getChildNode(dimension, "VerticalPixelSize"); if (vert == null) { vert = new IIOMetadataNode("VerticalPixelSize"); dimension.appendChild(vert); }
horiz.setAttribute("value", Double.toString(25.4 / 300)); vert.setAttribute("value", Double.toString(25.4 / 300)); metadata.setFromTree("javax_imageio_1.0", root);
writer.write(null, new IIOImage(image, null, metadata), null);
ios.close(); writer.dispose();
return baos.toByteArray();
} catch (Exception e) { e.printStackTrace(); return null; } }
private PDPage createPDPageFromImage(PDDocument pdf, byte[] imageData) { try (InputStream is = new ByteArrayInputStream(imageData)) { BufferedImage image = ImageIO.read(is); if (image == null) { return null; } PDImageXObject imageObject = LosslessFactory.createFromImage(pdf, image); PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight())); try (PDPageContentStream contentStream = new PDPageContentStream(pdf, page)) { contentStream.drawImage(imageObject, 0, 0, image.getWidth(), image.getHeight()); } return page; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Error processing image data", e); } }
public List<byte[]> tiffToImage(byte[] tiffData) throws IOException { List<byte[]> imageFiles = new ArrayList<>(); try (ImageInputStream is = ImageIO.createImageInputStream(new ByteArrayInputStream(tiffData))) { Iterator<ImageReader> it = ImageIO.getImageReaders(is); if (it.hasNext()) { ImageReader reader = it.next(); reader.setInput(is); for (int i = 0; i < reader.getNumImages(true); i++) { BufferedImage image = reader.read(i); try (ByteArrayOutputStream imageStream = new ByteArrayOutputStream()) { ImageIO.write(image, "png", imageStream); imageFiles.add(imageStream.toByteArray()); } } } } return imageFiles; }
public static List<byte[]> pdfToImagePlus(InputStream inputStream) { List<byte[]> result = new ArrayList<>(); try { PDDocument document = PDDocument.load(inputStream); PDFRenderer renderer = new PDFRenderer(document); for (int i = 0; i < document.getNumberOfPages(); i++) { BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DEFAULT_DPI); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageOutputStream imageOut = ImageIO.createImageOutputStream(out); ImageIO.write(bufferedImage, DEFAULT_FORMAT, imageOut); result.add(out.toByteArray()); out.close(); imageOut.close(); inputStream.close(); } document.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
|