Ákos Jakub Ákos Jakub - 5 months ago 345
Android Question

How can I replace text in PDF with iText without encoding issue? (Android)

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();
}


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 ?

Answer

I already found the solution ;)

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();
}