Openpdf: java.util.regex.PatternSyntaxException on android

Created on 14 Jul 2020  路  6Comments  路  Source: LibrePDF/OpenPDF

librepdf 1.3.20 is almost working on android. There is only one issue with custom fonts:

  • Registering font (create local file of ttf from resources and register it with alias works)
  • FontFactory.getFont(...) calls
public class FontFactoryImp implements FontProvider {
    ...
    public Font getFont(@Nullable String fontname, String encoding, boolean embedded, float size, int style, @Nullable Color color, boolean cached) {

        ...Line 195
        try {
                // the font is a type 1 font or CJK font
                basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null, true);
            } catch (DocumentException ignored) {
            }
        ...
    }
...
}

Used in Play! Framework DocumentException is thrown.
On Android java.util.regex.PatternSyntaxException is thrown, therefore using custom fonts is not working. The error is caused by the following regexes that can't be resolved for some reason.

public final class MessageLocalization {
    ... Line 172
    public static String getComposedMessage(String key, Object p1, Object p2, Object p3, Object p4) {
        String msg = getMessage(key);
        if (p1 != null) {
            msg = msg.replaceAll("\\{1}", p1.toString());
        }
        if (p2 != null) {
            msg = msg.replaceAll("\\{2}", p2.toString());
        }
        if (p3 != null) {
            msg = msg.replaceAll("\\{3}", p3.toString());
        }
        if (p4 != null) {
            msg = msg.replaceAll("\\{4}", p4.toString());
        }
        return msg;
    }
    ...
}

On android build.gradle


dependencies {
    implementation 'com.github.librepdf:openpdf:1.3.20'
    implementation 'com.github.andob:android-awt:1.0.0' // Used by OpenPDF
}

/* necessary for OpenPDF */
repositories {
    maven { url "https://jitpack.io" }
}
bug

All 6 comments

For anyone having this issue. Workaround is to 1. register font and 2. getFont with:

FontFactory.getFont(FontFactory.getFontImp().getFontPath("font-alias").toString(), font-size);

The proper syntax would be: msg = msg.replaceAll("\\{1\\}", p1.toString());
The second bracket should be escaped like the first because it is a special char in the regex language
This happens only on android because they have substituted the java pattern matcher by a native library: ICU which is less tolerant

The call is in openpdf/src/main/java/com/lowagie/text/error_messages/MessageLocalization.java

This code seems to have been changed by some IDE-Optimisations. It was originally:

if (p1 != null) {
    msg = msg.replaceAll("\\{1\\}", p1.toString());
}

I'll do some refactoring on this, this weekend. Stay tuned.

Hi @joseluu , @michaelhugi ,

Could you try with the SNAPSHOT-Version, to see if the issue is fixed?

Thanks

Yes, I confirm that the issue is fixed

Was this page helpful?
0 / 5 - 0 ratings