如何使用iText替换PDF中的文本而没有编码问题? (安卓) [英] How can I replace text in PDF with iText without encoding issue? (Android)
问题描述
我需要一些帮助.我想用PDF文件中的另一个替换文本(我正在使用iText库),但是当我尝试使用带重音符号的字母时,它存在编码问题.
I need some help. I want to replace a text with an another in a PDF file (I'm using iText library), but when I'm trying to do it with accent letters, it has encoding problems.
public static void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfDictionary dict = reader.getPageN(1);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String eredeti = "öüóá";
final String s = new String(eredeti.getBytes(), BaseFont.CP1250);
stream.setData(new String(data).replace("Hello World", s).getBytes());
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
但是当我打开PDF文件时,会看到以下内容: 错误的PDF
But when I open the PDF file, I see this: Wrong PDF
我已经尝试了所有编码类型,以获取正确的字母(öüóá),但是它对我没有用.
I've already tried all encoding types, to get the right letters (öüóá), but it never worked for me.
有人知道我该怎么办吗?
Has anybody any idea what should I do ?
推荐答案
我已经找到了解决方案;)
I already found the solution ;)
问题在于,在将字符串放入PDF文件之前,我已经对其进行了编码.完全将其放入PDF时,应该对字符串进行编码,如下所示:
The problem was that, I have encoded the string before I put it into the PDF file. You should encode your string when exactly you put it into the PDF, just like here:
stream.setData(new String(data).replace("Hello World", s).getBytes("ISO-8859-2"));
您可以在此处查看我的代码的最终形式:
You can see the final form of my code here:
public static void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfDictionary dict = reader.getPageN(1);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
byte[] data = PdfReader.getStreamBytes(stream);
String eredeti = "öűóá";
final String s = new String(eredeti.getBytes());
stream.setData(new String(data).replace("Hello World", s).getBytes("ISO-8859-2"));
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
Paragraph preface = new Paragraph();
preface.setAlignment(Element.ALIGN_CENTER);
reader.close();
}
这篇关于如何使用iText替换PDF中的文本而没有编码问题? (安卓)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!