简体   繁体   中英

Groupdocs conversion using streams

I need to be able to convert .pdf documents into preview/thumbnail images for later retrieval. It's working now in my solution, which currently involves dumping new files into a watched folder, writing the converted files to disk, and then pushing them into a MongoDB collection. But I want to do it without writing any files to disk. (The image files themselves will be going into a MongoDB collection, and the content from which the image files will be generated comes from a different MongoDB collection.) I'm using groupdocs conversion to do this.

I have one class which retrieves the content and passes it as an InputStream into another class, whose method of interest goes like this:

public void generateRenderedImages(InputStream inputStream, String fileName, ConversionHandler conversionHandler) {

    File previewImage = null;
    File thumbnailImage = null;
    File parent = null;

    try {
        ImageSaveOptions imageSaveOptions = new ImageSaveOptions();
        imageSaveOptions.setSaveFileType(ImageSaveOptions.JPEG);
        imageSaveOptions.setPage(1);
        imageSaveOptions.setHeight(THUMBNAIL_HEIGHT);
        imageSaveOptions.setWidth(THUMBNAIL_WIDTH);
        imageSaveOptions.setSavePath(null);

        // generate preview image
        imageSaveOptions.setSaveName("blah.jpg");

        OutputStream outputStream = conversionHandler.convertToImage(inputStream, fileName, imageSaveOptions);

        saveToDatabase(outputStream, CONTENT_TYPE_PREVIEW, fileName);

        imageSaveOptions.setHeight(THUMBNAIL_HEIGHT);
        imageSaveOptions.setWidth(THUMBNAIL_WIDTH);

        outputStream.close();

        outputStream = conversionHandler.convertToImage(inputStream, fileName, imageSaveOptions);
        saveToDatabase(outputStream, CONTENT_TYPE_THUMBNAIL, fileName);
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Image rendering failed); error = " + e.getMessage());
        resLogger.writeLog("Image rendering failed); error = " + e.getMessage());

    } finally {
        // maybe need something here, not sure yet
    }
}

The problem is that I'm throwing a NullPointerException at the conversionHandler.convertToImage(...) line -- relevant parts of the stack trace will follow -- even though neither the conversionHandler nor any of its parameters are null.

java.lang.NullPointerException at com.groupdocs.conversion.converter.a.(ConversionHelper.java:31) at com.groupdocs.conversion.handler.ConversionHandler.convertToImage(ConversionHandler.java:127)

I have done some research into this, but the relative lack of documentation that I can find has created some limits. For example, this page:

https://github.com/groupdocs/groupdocs-conversion-java-maven-sample/blob/master/src/main/java/com/groupdocs/conversion/maven/converters/ToImageSampleConversion.java

...positively shows in this snippet that this is possible, and at least in theory how:

/** * Convert 1 document page to images
* On this type of conversion convertToImage returns OutputStream with converted file
* Note: converted file is not saved in local directory
* To use this type of conversion 'page' and 'saveToStream' parameters must be set in ImageSaveOptions
* convertToImage method also can receive InputStream as parameter
* See JavaDoc for more info.
* @param conversionHandler ConversionHandler instance * @param page page number */ public void convertToStream(ConversionHandler conversionHandler, int page){ ImageSaveOptions imageSaveOptions = new ImageSaveOptions(); imageSaveOptions.setSaveFileType(ImageSaveOptions.PNG); imageSaveOptions.setPage(page);

    OutputStream outputStream = conversionHandler.convertToImage(PDF_FILE, imageSaveOptions);
    //do something with the stream

Unfortunately there is no setSaveToStream() method, but I found from this page:

http://groupdocs.com/Community/files/9/java-libraries/groupdocs_conversion_for_java/entry5343.aspx

that in the previous version this was removed:

Public Api changes ... com.groupdocs.conversion.option.SaveOptions The method setSaveToStream was removed to simplify options parameters. Now for saving result document to stream output just do not set SaveOptions.setSavePath or set it to null.

So I don't have to explicitly set the saveToStream property, I just have to make sure savePath is null. Which I have done, and yet the problem persists. I've tried every other combination of setting/not setting properties, all with the same result.

I'm using version 1.2.0 of groupdocs conversion. Anyone see this before, and know why I might be getting a NPE when nothing is null?

I was away from this for a while, but got back to it today.

Here is my solution:

public class RenderImages {
private static final Log log = LogFactory.getLog(RenderImages.class);

public static void generateRenderedImages(Datastore datastore,
    InputStream inputStream,
    String fileName,
    ConversionHandler conversionHandler,
    SystemProperties systemProperties,
    Logger logger) {

    int thumbnailHeight = systemProperties.getAsInteger("RENDER_THUMBNAIL_HEIGHT");
    int thumbnailWidth = systemProperties.getAsInteger("RENDER_THUMBNAIL_WIDTH");
    String contentTypePreview = systemProperties.get("RENDER_CONTENT_TYPE_PREVIEW");
    String contentTypeThumbnail = systemProperties.get("RENDER_CONTENT_TYPE_THUMBNAIL");

    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        inputStream.close();

        ImageSaveOptions imageSaveOptions = new ImageSaveOptions();
        imageSaveOptions.setSaveFileType(ImageSaveOptions.JPEG);
        imageSaveOptions.setPage(1);

        ByteArrayOutputStream previewStream = conversionHandler.convertToImage(new ByteArrayInputStream(imageBytes),
            fileName + ".pdf",
            imageSaveOptions);

        saveToDatabase(datastore, previewStream, contentTypePreview, fileName);
        previewStream.close();

        imageSaveOptions.setHeight(thumbnailHeight);
        imageSaveOptions.setWidth(thumbnailWidth);

        ByteArrayOutputStream thumbnailStream = conversionHandler.convertToImage(
            new ByteArrayInputStream(imageBytes),
            fileName + ".pdf",
            imageSaveOptions);

        saveToDatabase(datastore, thumbnailStream, contentTypeThumbnail, fileName);
        thumbnailStream.close();
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Image rendering failed); error = " + e.getMessage());
        logger.writeLog("Image rendering failed); error = " + e.getMessage());

    } finally {
        // maybe need something here, not sure yet
    }
}

private static void saveToDatabase(Datastore datastore,
    ByteArrayOutputStream image, String contentType, String fileName) throws IOException {

    RenderedImage renderedImage = datastore.find(RenderedImage.class)
        .filter("attachmentId", fileName)
        .filter("contentType", contentType)
        .get();

    if (renderedImage == null) {
        renderedImage = new RenderedImage();
        renderedImage.setAttachmentId(fileName);
        renderedImage.setContentType(contentType);
        renderedImage.setContent(image.toByteArray());
        datastore.save(renderedImage);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM