Total Pageviews

2016/10/07

[PDFBox] Generate TIF with 0-kb

Problem
I am using Apache PDFBox to convert PDF to TIF file.

The scenario is to generate TIF file to a specific path, then another application will read this TIF file and move to another directory.



But it will generate TIF file with 0-kb at times and fail to open this TIF file, and does not have any abnormal message in application log.


How-To

Here is the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    private List<String> writeImage(PDDocument document, String outputPrefix, ImageType imageType,
            float dpi, String fileName) throws IOException {
        ImageIO.scanForPlugins();

        List<String> tifNames = new ArrayList<String>();

        PDFRenderer renderer = new PDFRenderer(document);

        for (int i = 0; i < document.getNumberOfPages(); i++) {

            BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType);

            String outputPostfix = "_" + String.format("%02d", i + 1); // 01開始
            String outputFileName = outputPrefix + outputPostfix;// 檔名: 保單號碼_0X

            tifNames.add(fileName + outputPostfix); // 回傳產了那些檔名

            ImageIOUtil.writeImage(image, outputFileName + "." + "tif", Math.round(dpi));
            image.flush();
        }
        return tifNames;
    }



We can see implementation details in ImageIOUtil.writeImage
https://github.com/apache/pdfbox/blob/04292e421e9531616aa2856b908fbdb05b381af7/tools/src/main/java/org/apache/pdfbox/tools/imageio/ImageIOUtil.java#L65-L79

We can see it will create a File instance at first, then write image to TIF file.


As it create a File instance, this file will be created. It another application had read this file, then this file may be locked and failed to write.

Therefore, we should create TIF file to a temporary directory first, then move the finished TIF file to the destination. 




No comments: