Convert image to PDF Java using Aspose.PDF - OutOfMemoryException

Hi

We’re using JDK 1.8, and com.aspose.aspose-pdf 20.1

Our source java code is the following :

public static int convertImagesToPdf(String vFileName, String zipWorkDir, String vFilePath) throws Exception {
	int nbPages = 0;
	Document doc = null;
	FileInputStream fs = null;
	Page page = null;

	try {
		doc = new Document();
		fs = new FileInputStream(vFilePath);

		page = doc.getPages().add();

		// Set margins so image will fit, etc.
		page.getPageInfo().getMargin().setBottom(0);
		page.getPageInfo().getMargin().setTop(0);
		page.getPageInfo().getMargin().setLeft(0);
		page.getPageInfo().getMargin().setRight(0);

		page.setCropBox(new Rectangle(0, 0, 400, 400));
		// Create an image object
		Image img = new Image();
		// Add the image into paragraphs collection of the section
		page.getParagraphs().add(img);
		// Set the image file stream
		img.setImageStream(fs);

		// Save resultant PDF file
		nbPages = doc.getPages().size();

		doc.save(zipWorkDir + vFileName + ".pdf");

	} catch (Exception e) {
		LOG.error(e.getMessage());
	} finally {
		if (fs != null)
			fs.close();

		if (page != null)
			page.dispose();

		if (doc != null)
			doc.dispose();
	}
	return nbPages;
}

But we have two ou three times by day out of memory.

We have increased JVM size (intially 3Go, the current size is 4 Go).

Is there any mistake in our java code ?
Do you have some advices ?

Regards
JF

@jfreguer

The code snippet seems fine and should produce results without any issue. Are you facing OOM with particular type of images with certain file sizes or it is random? Please try to share some images with us with which we can try to replicate the issue in our environment and address it accordingly. Also, please make sure to test with 21.1v of the API before sharing your response.

Thanks for your answer.

It is difficult for us to give you some examples of images, because it dicuments of customer…

I saw that you advice to use the function com.aspose.pdf.MemoryCleaner.clear(); in that page :

Do we have to do it after each API call ?

Thanks

@jfreguer

The usage of this method depends upon the nature of the code routine. The API actually loads resources into memory and keeps them loaded during processing. In a complex code routine, it is necessary to free memory due to which this method was introduced in the API. In your case, as you also mentioned - the API giving OOM exception which indicates that the memory is not being released properly after converting images to PDFs.

You can surely try using this method after saving a Document. In case issue still persists, you can please share sample images in a private message where they will be accessible by only Aspose Staff. We use the files for investigation purposes and erase them from our system once analysis is done.