2015-02-11 114 views
0

我现在使用Itext PdfSmartCopy。我使用XMLworker将一些业务内容添加到文档对象中。然后我宣布了一个阅读器(将pdf文件连接到这个文档对象)。然后,我使用相同的文档对象和输出文件流作为参数调用PdfSmartCopy。然后,我使用传统的步骤将页面复制到文档,Itext 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获得空指针异常?有什么问题?

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) 

但是这片效果很好,如果我用一个新的文档对象即不增加业务内容。

+0

这将有助于看PDF或失败的任何文件? – 2015-02-11 11:04:51

+0

嗨@PauloSoares,如果您想要重现问题的示例,请查看https://jira.itextsupport.com/browse/DEV-1256。 – 2015-02-11 11:24:37

+0

嗨@布鲁诺,我无法访问上述链接。你能帮我解决这个问题吗? – dev123 2015-02-11 12:05:27

回答

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 c 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(); 
+0

感谢布鲁诺。这是有道理的,并为我提供了我正在寻找的解决方案。让我试试看。 – dev123 2015-02-12 09:45:45