使用iText 5.5.3合并文档时面对空指针异常

时间:2015-06-22 14:01:49

标签: java pdf-generation itext

我以流的形式传递2个文档并尝试将它们合并为单个pdf。在循环的第一次迭代中,一切正常,但在第二次迭代期间奇迹般地抛出空指针异常。传递的两个流实际上是相同的,被用作两个独立的流。

代码:

public synchronized void doMerge(InputStream[] streams,OutputStream out) throws Exception {


    System.out.println("Starting To Merge Files...");
    System.out.println("Total Number Of Files To Be Merged..." +
                      streams.length + "\n");
    try {

        int fileIndex = 0;
        Document document = null;
        PdfCopy writer = null;
        PdfReader reader = null;

        for (fileIndex = 0; fileIndex < streams.length; fileIndex++) {


            System.out.println("Loop No : "+ (fileIndex+1));

            reader = new PdfReader(streams[fileIndex]);
            System.out.println("Reader "+ (fileIndex+1) +" created successfully");

            if (fileIndex == 0) {

            document = new Document();
            System.out.println("Document created successfully");

            writer = new PdfSmartCopy(document, out);
            System.out.println("Reader created successfully");

            document.open();

            }

            writer.addDocument(reader);
            System.out.println("Document "+ (fileIndex+1)+" merged" );
            reader.close();
            System.out.println("Reader "+ (fileIndex+1)+" closed" );
        }



        document.close();
        System.out.println("Document successfully closed");

        System.out.println("File has been merged and written to-" + out);
    }

    catch (Exception e) {
        System.out.println(in exception block");
        System.out.println(e.toString());
    }

}

这是我在输入中发送2个流时得到的输出:

Loop No : 1
Reader 1 created successfully
Document created successfully
Reader created successfully
Document 1 merged
Reader 1 closed
Loop No : 2
in exception block
java.lang.NullPointerException

0 个答案:

没有答案