Strona główna > Java, programming > RtfTemplate and character encoding

RtfTemplate and character encoding


RtfTemplate is quite interesting tool, that enables processing MsOffice serial correspondence (mail merge) templates in java code. The source and the output is in RTF format. It is very good to quickly and easily prepare prints in application. What is more, the prints can be prepared by non-technical users, teached only in using MsOffice (which is common skill by office workers).

Hovewer, there is one serious problem with the tool. It lacks the ability to property encode characters. The data put into template is not displayed properly, not counting those cases, where data is 7-bit ASCII only. However, this was propably the test case for authors, so the result is the tool, that is very useful, but only for the small part of the world.

The solution is not elegant, but quite simple. It requires using another tool, which is free: iText. iText has build-in functionality to print into RTF documents, and its class RtfDocument has methods for encoding characters according to RTF standard. The only thing you have to do, is to use it to encode the data you are going to print. The minus is, that you have to do it for all the data you send to template printer, no matter how deep in the structure sent they are. The function to call is quite simple. This is the sample how to use it:

22     public static String escape(String sentence) {
23         ByteArrayOutputStream baos = new ByteArrayOutputStream();
24         try {
25             new RtfDocument().filterSpecialChar(baos, sentence, true, true);
26         catch (IOException e) {
27             // will never happen for ByteArrayOutputStream
28         }
29         return new String(baos.toByteArray());
30     }

%d blogerów lubi to: