Removing invalid characters from a string using PDFBox

When I try to write illegal characters in PDF, I obviously get an exception. For instance.

contentStream.showText("some illegal characters");    
...
java.lang.IllegalArgumentException: U+000A ('controlLF') is not available in this font Helvetica (generic: ArialMT) encoding: WinAnsiEncoding...

How to find out which characters are not supported and cut them out of a string?

+4
source share
1 answer

Here is my solution ... at least it works for what I need. I used the WinAnsiEncoding PDFBox class and called the contains method to check if this character is supported.

import org.apache.pdfbox.pdmodel.font.encoding.WinAnsiEncoding;

public class Test extends WinAnsiEncoding {

    public static String remove(String test) {
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < test.length(); i++) {
            if (WinAnsiEncoding.INSTANCE.contains(test.charAt(i))) {
                b.append(test.charAt(i));
            }
        }
        return b.toString();
    }

    public static void main(String[] args) {
        System.out.println(remove("abc\rcde"));
        // prints abccde
    }

}
+5
source

Source: https://habr.com/ru/post/1669709/


All Articles