mangstadt / ez-vcard

A vCard parser library for Java
Other
405 stars 93 forks source link

Adding charset encoding to elements in VCard #106

Closed DJViking closed 4 years ago

DJViking commented 4 years ago

In order to support special characters on iPhone we had to (with VCard v2.1) add Charset=UTF-8 to each elements. WIthout it tthe special characters did not display properly on iPhone. It works fine on Android with and without the Charset.

N;CHARSET=UTF-8:Solskjær;Åge ADR;WORK;CHARSET=UTF-8:Address with ÆØÅ Special Characters;1234;Norway

I could not find any way to add this with ez-vcard.

DJViking commented 4 years ago

I found out how. Setting parameter address.setProperty("Chartset", "UTF-8");

mangstadt commented 4 years ago

To just add a CHARSET parameter to a property:

vcard.getStructuredName().getParameters().setCharset("UTF-8");

If you are still having trouble, you can try encoding the property value in quoted-printable encoding. My understanding is that this is the most widely supported technique amongst vCard readers.

Quoted-printable encoding allows for non-ASCII characters to be included in a property value, no matter what character set the vCard as a whole uses. By default, ez-vcard uses UTF-8 when encoding a value in quoted-printable encoding (the CHARSET parameter is automatically added when quoted-printable encoding is used).

StructuredName n = new StructuredName();
n.setFamily("Solskjær");
n.setGiven("Åge");
n.getParameters().setEncoding(Encoding.QUOTED_PRINTABLE);

VCard vcard = new VCard(VCardVersion.V2_1);
vcard.setStructuredName(n);
vcard.write(System.out);

//outputs: N;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Solskj=C3=A6r;=C3=85ge
DJViking commented 4 years ago

Thanks. A much better approach than what I just found.

DJViking commented 4 years ago

On VCard V3.0 and V4.0 this produces an warning on validation n.getParameters().setEncoding(Encoding.QUOTED_PRINTABLE);

W04 ENCODING parameter value ("QUOTED_PRINTABLE") is not supported by this vCard version.

It didn't like my Charset parameter either.

W06 Charset parameter is not supported by this vCard version.

Though I could just stick with V2.1

mangstadt commented 4 years ago

That is correct. According to the specifications, only 2.1 supports quoted-printable encoding and the CHARSET parameter.