Convert multi-page TIFF to PDF never ends

Good morning,
i’m tring to convert some multi page tiff to a multi page pdf, but when I call the method save on the image frame object it never answers.

Here a class with a main that I used to reproduce the case:

package ...;

import ....UnsupportedTiffColorSpaceException;
import com.aspose.imaging.Image;
import com.aspose.imaging.ImageOptionsBase;
import com.aspose.imaging.PixelFormat;
import com.aspose.imaging.fileformats.tiff.TiffFrame;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.fileformats.tiff.enums.TiffExpectedFormat;
import com.aspose.pdf.Page;
import com.aspose.pdf.PageSize;
import com.aspose.pdf.Rectangle;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TestAspose {

    public static void main(String[] args) {
        try {
//            DirectoryStream<Path> pathList = Files.newDirectoryStream(Paths.get("path/to/file/to/convert"));
            DirectoryStream<Path> pathList = Files.newDirectoryStream(Paths.get("D:\\temp\\converter"));
            for (Path path : pathList) {
                File file = path.toFile();
                if (file.isDirectory()) {
                    continue;
                }

                ByteArrayInputStream docPath = null;
                try {
                    docPath = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
                } catch (IOException e) {
                    System.out.println("error reading file: " + file.getAbsolutePath());
                }
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                try (Image image = Image.load(docPath)) {
                    if (image.getFileFormat() != com.aspose.imaging.FileFormat.Tiff &&
                            image.getFileFormat() != com.aspose.imaging.FileFormat.BigTiff) {
                        return;
                    }

                    Image[] images = null;
                    boolean hasAlpha = false;
                    if (image instanceof TiffImage tiffImage) {
                        images = tiffImage.getPages();
                        hasAlpha = tiffImage.hasAlpha();
                    } else {
                        images = new Image[]{image};
                    }

                    try (com.aspose.pdf.Document document = new com.aspose.pdf.Document()) {
                        for (Image imageTmp : images) {
                            InputStream stream = null;
                            ByteArrayOutputStream workingStream = null;
                            try (Page page = document.getPages().add()) {
                                float scale = PageSize.getA4().getHeight() /
                                        Integer.max(imageTmp.getWidth(), imageTmp.getHeight());
                                float scaledWidth = imageTmp.getWidth() * scale;
                                float scaledHeight = imageTmp.getHeight() * scale;
                                page.setPageSize(scaledWidth, scaledHeight);
                                Rectangle rectangle = new Rectangle(0, 0, scaledWidth, scaledHeight);
                                page.setMediaBox(rectangle);
                                workingStream = new ByteArrayOutputStream();
                                int compressionType;
                                if (imageTmp instanceof TiffFrame frame) {
                                    int pixelFormat = frame.getRawDataSettings().getPixelDataFormat().getPixelFormat();
                                    if (pixelFormat == PixelFormat.Cmyk) {
                                        compressionType = hasAlpha || frame.hasAlpha() ? TiffExpectedFormat.TiffNoCompressionCmyk : TiffExpectedFormat.TiffNoCompressionCmyka;
                                    } else if (pixelFormat == PixelFormat.Rgb) {
                                        compressionType = hasAlpha || frame.hasAlpha() ? TiffExpectedFormat.TiffNoCompressionRgb : TiffExpectedFormat.TiffNoCompressionRgba;
                                    } else if (pixelFormat == PixelFormat.Grayscale) {
                                        compressionType = TiffExpectedFormat.TiffNoCompressionBw;
                                    } else {
                                        throw new UnsupportedTiffColorSpaceException("file name");
                                    }
                                } else {
                                    throw new UnsupportedTiffColorSpaceException("file name");
                                }

                                try (ImageOptionsBase options = new com.aspose.imaging.imageoptions.TiffOptions(compressionType)) {
                                    imageTmp.save(workingStream, options);
                                }
                                stream = new ByteArrayInputStream(workingStream.toByteArray());

                                page.addImage(stream, rectangle);
                            } finally {
                                IOUtils.closeQuietly(workingStream);
                                IOUtils.closeQuietly(stream);
                                IOUtils.closeQuietly(imageTmp);
                            }
                        }
                        com.aspose.pdf.optimization.OptimizationOptions optimizationOptions =
                                new com.aspose.pdf.optimization.OptimizationOptions();
                        optimizationOptions.setRemoveUnusedObjects(true);
                        optimizationOptions.setRemoveUnusedStreams(true);
                        optimizationOptions.setUnembedFonts(true);
                        document.optimizeResources(optimizationOptions);
                        document.optimize();
                        document.save(outputStream);
                        //to do you can save the output to a file...
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}

P.S.: I also tried to use Aspose’s online image editor product here, but still stuck also there.

I’m using aspose total 24.1, I will provide some examples shortly, thanks in advacne to everyone for support.

@nicolo.rossi

It seems that you are experiencing an issue where the conversion of multi-page TIFF images to a multi-page PDF is hanging indefinitely when you call the save method on the image frame object. This can happen for several reasons, including memory issues or improper handling of the TIFF frames.

Here are some suggestions to troubleshoot and potentially resolve the issue:

  1. Memory Management: Ensure that you are managing memory effectively, especially when dealing with large TIFF files. Consider using a memory strategy optimization approach, which allows you to limit the memory buffer size during operations. This can help prevent memory overflow issues.

  2. Batch Processing: If you are processing multiple pages, consider using batch mode for exporting TIFF images. This method allows you to process each page without keeping all resources in memory at once, which can significantly reduce memory consumption.

  3. DPI Settings: When converting images to PDF, you can specify the DPI (dots per inch) for the exported PDF. This can affect the quality and size of the output file, so ensure that you are setting appropriate DPI values.

  4. Error Handling: Implement robust error handling to catch any exceptions that may occur during the image loading or saving process. This can help you identify specific issues that may be causing the hang.

  5. Testing with Different Files: Try converting different TIFF files to see if the issue is specific to certain files. This can help determine if the problem lies with the file format or the conversion process itself.

  6. Update Aspose Libraries: Ensure that you are using the latest version of Aspose.Imaging and Aspose.PDF libraries, as updates may contain bug fixes and performance improvements.

Here is a simplified example of how you might structure your code to include some of these suggestions:

try (TiffImage tiffImage = (TiffImage) Image.load("path/to/multi-page.tiff")) {
    try (Document pdfDocument = new Document()) {
        for (TiffFrame frame : tiffImage.getFrames()) {
            // Process each frame
            ByteArrayOutputStream workingStream = new ByteArrayOutputStream();
            frame.save(workingStream, new TiffOptions(TiffExpectedFormat.TiffNoCompressionRgb));
            InputStream stream = new ByteArrayInputStream(workingStream.toByteArray());
            Page pdfPage = pdfDocument.getPages().add();
            pdfPage.addImage(stream);
        }
        pdfDocument.save("output.pdf");
    }
} catch (Exception e) {
    e.printStackTrace();
}

By following these suggestions, you should be able to troubleshoot the issue more effectively. If the problem persists, consider reaching out to Aspose support for further assistance.

Sources:
[1]: Convert Images to PDF with Aspose.Imaging for Java
[2]: Manipulating TIFF Images - Aspose Documentation

@Professionalize.Discourse

Thank you for your answer… but I’ve already checked that things and nothing strange appearse.
When it start to save to output stream it start, but never ends… This happens only with some file, but i can’t share with you 'cause of sensitive data.
I’m looking for some examples without sensitive data, when I find it I’ll share it, thanks.

@nicolo.rossi

Please take your time to gather a sample file that you could share to replicate the issue in our environment along with minimal sample code snippet. We will further proceed accordingly.