java.lang.ClassCastException:com.itextpdf.text.pdf.PdfArray无法强制转换为com.itextpdf.text.pdf.PRIndirectReference
我在编写的将PDF文件转换为XML文件的程序中收到此错误。它是如何产生的,我该如何解决?
`package pkgfinal.year;
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.xml.sax.helpers.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.stream.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.lowagie.text.pdf.PRTokeniser;
public class FinalYear {
static StreamResult streamResult;
static TransformerHandler handler;
static AttributesImpl atts;
public static void main(String[] args) throws IOException {
try {
Document document = new Document();
document.open();
FileInputStream fis = new FileInputStream("TestFiles/test.pdf");
PdfReader reader = new PdfReader(fis);
PdfDictionary page = reader.getPageN(1);
PRIndirectReference objectReference = (PRIndirectReference) page.get(PdfName.CONTENTS);
PRStream stream = (PRStream) PdfReader
.getPdfObject(objectReference);
byte[] streamBytes = PdfReader.getStreamBytes(stream);
PRTokeniser tokenizer = new PRTokeniser(streamBytes);
StringBuilder strbufe = new StringBuilder();
while (tokenizer.nextToken()) {
if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) {
strbufe.append(tokenizer.getStringValue());
}
}
String test = strbufe.toString();
streamResult = new StreamResult("TestFiles/output1.xml");
initXML();
process(test);
closeXML();
document.add(new Paragraph(".."));
document.close();
} catch (Exception e) {
System.out.print(e);
}
}
public static void initXML() throws ParserConfigurationException,
TransformerConfigurationException, SAXException {
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
handler = tf.newTransformerHandler();
Transformer serializer = handler.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
serializer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
handler.setResult(streamResult);
handler.startDocument();
atts = new AttributesImpl();
handler.startElement("", "", "Title", atts);
}
public static void process(String s) throws SAXException {
String[] elements = s.split("\\|");
atts.clear();
handler.startElement("", "", "Message", atts);
handler.characters(elements[0].toCharArray(), 0, elements[0].length());
handler.endElement("", "", "Message");
}
public static void closeXML() throws SAXException {
handler.endElement("", "", "Title");
handler.endDocument();
}
}
以上是抛出错误的代码。显示错误的行是双星标题或粗体。请帮忙!
答案 0 :(得分:0)
您正在尝试将一类PdfArray转换为一类PRIndirectReference。
如果您提供了正在执行此操作的代码,那么将会出现更多帮助,但查看错误消息,您将尝试将一个类转换为另一个无法从中实例化的类。
答案 1 :(得分:0)
我从代码中看到的是,您尝试将page.get(PdfName.CONTENTS);
的返回值分配给PRIndirectReference
,这会引发ClassCastException。这推断page.get(..)
不会使PRIndirectReference
类型的对象或其任何子类类型退回。
你可能需要在这里添加一个合适的包装器,它返回适当类型的类或子类,可以转换为PRIndirectReference
。浏览'itextpdf'文档,我认为您将使用PDFIndirectReference
类并最终使用错误的文档。