Free Support Forum -

Convert image to PDF Java using Aspose.PDF - OutOfMemoryException


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.setCropBox(new Rectangle(0, 0, 400, 400));
		// Create an image object
		Image img = new Image();
		// Add the image into paragraphs collection of the section
		// Set the image file stream

		// Save resultant PDF file
		nbPages = doc.getPages().size(); + vFileName + ".pdf");

	} catch (Exception e) {
	} finally {
		if (fs != null)

		if (page != null)

		if (doc != null)
	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 ?



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 ?



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.