Kar*_*120 2 java pdf itext character-encoding
当我创建一个PDF文件时,我使用此代码附加一些信息,以使其对我的程序可读:
PdfDictionary dictionary = new PdfDictionary();
PdfObject object;
PdfName index;
ArrayList<String> content = getCompactData(document);
for (int i = 0; i < content.size(); i++)
{
object = new PdfString(content.get(i));
index = new PdfName(Integer.toString(i+1));
dictionary.put(index, object);
}
writer.getExtraCatalog().putAll(dictionary);
Run Code Online (Sandbox Code Playgroud)
当我打开程序时,我使用此代码来提取数据:
PdfDictionary dictionary = reader.getCatalog();
PdfName index;
PdfObject line;
ArrayList<String> data = new ArrayList<String>();
for (int i = 1; i < dictionary.size()-2; i++)
{
index = new PdfName(Integer.toString(i));
line = dictionary.getAsString(index);
data.add(line.toString());
}
Run Code Online (Sandbox Code Playgroud)
除了一个小细节外,一切都很好.诸如čšđćž之类的人物由于某种原因没有正确地传递给过程.一旦我尝试提取数据,我的程序就会变得混乱,无法识别这些字母.
几点说明:
所以我不知道哪里出错了.你呢?
你错误地使用了这个PdfString类.代替
object = new PdfString(content.get(i));
Run Code Online (Sandbox Code Playgroud)
使用
object = new PdfString(content.get(i), PdfObject.TEXT_UNICODE);
Run Code Online (Sandbox Code Playgroud)
而不是
data.add(line.toString());
Run Code Online (Sandbox Code Playgroud)
使用
data.add(line.toUnicodeString());
Run Code Online (Sandbox Code Playgroud)
一些背景资料:
您使用的构造函数尝试使用PDFDocEncoding:
/**
* Constructs a <CODE>PdfString</CODE>-object containing a string in the
* standard encoding <CODE>TEXT_PDFDOCENCODING</CODE>.
*
* @param value the content of the string
*/
public PdfString(String value)
Run Code Online (Sandbox Code Playgroud)
您的字符?š??ž不在该编码中.
另一个构造函数允许您选择UTF-16BE编码:
/**
* Constructs a <CODE>PdfString</CODE>-object containing a string in the
* specified encoding.
*
* @param value the content of the string
* @param encoding an encoding
*/
public PdfString(String value, String encoding)
Run Code Online (Sandbox Code Playgroud)
对于字符提取,toString只返回内部表示,同时toUnicodeString关心编码:
/**
* Returns the Unicode <CODE>String</CODE> value of this
* <CODE>PdfString</CODE>-object.
*
* @return A <CODE>String</CODE>
*/
public String toUnicodeString()
Run Code Online (Sandbox Code Playgroud)