Reputation: 59
Am trying to images as new page to the pdf files, the jpeg images are too large in size, though it gets added fine, am facing issue while converting the pdf to Tiff, its throwing outofmemory exception, is there a way to compress these jpeg files
Below code to convert images to pdf
PDImageXObject image = PDImageXObject.createFromFile(imagePath, doc);
PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
doc.addPage(page);
try (PDPageContentStream contents = new PDPageContentStream(doc, page)) {
contents.drawImage(image, 0,0);
contents.close();
}
Below to convert to pdf to tiff
document = PDDocument.load(new File(pdfFilename));
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage[] images = new BufferedImage[document.getNumberOfPages()];
for (int i = 0; i < images.length; i++) {
PDPage page = (PDPage) document.getPage(i);
BufferedImage image;
try {
image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB); // its throwing outofmemory error at this line
images[i] = image;
} catch (IOException e) {
LOGGER.error("Exception while reading merged pdf file:" + e.getMessage());
throw e;
}
}
File tempFile = new File(tiffFileName+".tiff");
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
ImageOutputStream output = ImageIO.createImageOutputStream(tempFile);
writer.setOutput(output);
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writer.prepareWriteSequence(null);
for (int i = 0; i < images.length; i++) {
params.setCompressionType("JPEG");
writer.writeToSequence(new IIOImage(images[i], null, null), params);
}
writer.endWriteSequence();
Upvotes: 1
Views: 1146
Reputation: 7789
To avoid the out of memory exception, try starting your application by passing it Xms and Xmx parameters, using suitable values. See this post What are the Xms and Xmx parameters when starting JVMs? and https://docs.oracle.com/cd/E21764_01/web.1111/e13814/jvm_tuning.htm#PERFM150:
Setting initial and minimum heap size
-Xms Oracle recommends setting the minimum heap size (-Xms) equal to the maximum heap size (-Xmx) to minimize garbage collections.
Setting maximum heap size
-Xmx Setting a low maximum heap value compared to the amount of live data decrease performance by forcing frequent garbage collections.
Upvotes: 1