Itext PdfSmartCopy获取Null指针异常

时间:2015-02-11 10:45:22

标签: java pdf itext

我现在正在使用Itext PdfSmartCopy。我正在使用XMLworker向文档对象添加一些业务内容。然后我宣布了一个读者(用于将pdf文件连接到此文档对象)。然后我用相同的文档对象和输出文件流作为参数调用PdfSmartCopy。然后我使用传统步骤将页面复制到文档中,

addHTML(document, htmlStringToBeAdded);
document.newPage();
com.itextpdf.text.pdf.PdfCopy copy = new com.itextpdf.text.pdf.PdfSmartCopy(document, new FileOutputStream("c:\\pdf_issue\\bad_itext3.pdf"));
com.itextpdf.text.pdf.PdfReader reader=new com.itextpdf.text.pdf.PdfReader("c:\\pdf_issue\\bad1.pdf");
 // loop over the pages in that document
 n = reader.getNumberOfPages();
  for (int page = 0; page < n; ) {
                copy.addPage(copy.getImportedPage(reader, ++page));
            }
copy.freeReader(reader);
    reader.close();

但是我在getPageReference上得到Null指针异常?有什么问题?

Exception in thread "main" java.lang.NullPointerException
    at com.itextpdf.text.pdf.PdfWriter.getPageReference(PdfWriter.java:1025)
    at com.itextpdf.text.pdf.PdfWriter.getCurrentPage(PdfWriter.java:1043)
    at com.itextpdf.text.pdf.PdfCopy.addPage(PdfCopy.java:356)
    at com.jci.util.PdfTest.main(PdfTest.java:627)

但如果我使用新的文档对象,即不添加业务内容,这部分就可以正常工作。

1 个答案:

答案 0 :(得分:4)

我们在已关闭的问题跟踪器中遇到了类似的问题。在该票证中,似乎需要在创建Document实例后立即打开PdfCopy

在您的情况下,我们发现了类似的问题:您使用Document对象从头开始创建PDF,然后使用相同的 Document来创建现有PDF的副本。这永远不会起作用:您需要先从头开始创建您创建的文档,然后为复制过程创建一个新的Document

// first create the document
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
addHTML(document, htmlStringToBeAdded);
document.close();
// Now you can use the document you've just created
PdfReader reader = new PdfReader(baos.toArray());
PdfReader existing = new PdfReader("c:\\pdf_issue\\bad1.pdf");
document = new Document();
PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream("c:\\pdf_issue\\bad_itext3.pdf"));
document.open();
copy.addDocument(reader);
copy.addDocument(existing);
document.close();
reader.close();
existing.close();