我正在尝试创建一个原型以将 PDF 文件转换为 XML 文件。结果有点奇怪,所有的字符都变成了符号。我认为错误是StringBuffer
从字节数组中获取数据的地方。有Java知识的人可以帮忙吗?
该原型软件正在使用iText
API。为了阅读 PDF 文件,我们使用了PDFReader
该类。数据先转换成字节数组,然后再用 ,Stringbuffer
再转换成字符串。然后我们使用StreamResult
wich 作为 XML 中转换结果的持有者。
之后,Transformer
该类处理来自各种源的 XML,并将转换输出写入各种接收器。然后TransformerHandler
侦听 SAX ContentHandler
,解析事件并将它们转换为结果。
方法startElement()
和endElement()
类TransformerHandler
在 xml 文件中创建了标签。Parser在 XML 文档中每个元素startElement()
的开头和每个元素的结尾调用方法。endElement()
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Cp2x {
static StreamResult streamResult;
static TransformerHandler handler;
static AttributesImpl atts;
public static void main(String[] args) throws IOException {
try {
Document document = new Document();
document.open();
PdfReader reader = new PdfReader("C:\\helloworld.pdf");
PdfDictionary page = reader.getPageN(1);
PRIndirectReference objectReference = (PRIndirectReference) page
.get(PdfName.CONTENTS);
PRStream stream = (PRStream) PdfReader
.getPdfObject(objectReference);
byte[] streamBytes = PdfReader.getStreamBytes(stream);
PRTokeniser tokeniser = new PRTokeniser(streamBytes);
StringBuffer string_buffer = new StringBuffer();
while (tokeniser.nextToken()) {
if (tokeniser.getTokenType() == PRTokeniser.TK_STRING) {
string_buffer.append(tokeniser.getStringValue());
}
}
String test = string_buffer.toString();
streamResult = new StreamResult("test.xml");
initXML();
process(test);
closeXML();
document.add(new Paragraph(".."));
document.close();
} catch (Exception 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, "UTF-8");
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("", "", "Document", atts);
}
public static void process(String s) throws SAXException {
String[] elements = s.split("\\|");
atts.clear();
handler.startElement("", "", "Note", atts);
handler.characters(elements[0].toCharArray(), 0, elements[0].length());
handler.endElement("", "", "Note");
}
public static void closeXML() throws SAXException {
handler.endElement("", "", "Document");
handler.endDocument();
}
}