Thursday, August 1, 2013

Visualforce Page with ContentType in MultiByte Language

I'm working on a project where there are several multibyte languages, like Chinese and Arabic, that are supported.  One issue that we discovered in a new feature is related to exporting some content as a Word file.  The issue was in specifying the filename.  As you probably know, the syntax for something like this is:


<apex:page Controller="yourController" contenttype="application/msword#yourfilename" .. />

This works great but if you are substituting yourfilename with something from the controller, one symptom you could see is the file generated with the name of your VF page.  So, let's say you were doing something like this:

<apex:page Controller="yourController" contenttype="application/msword#{!someVar}" .. />

If {!someVar} is a value that is in Chinese or Arabic, your file name will probably look like "YourVFPage.doc" instead of "{!someVar}.doc".

There wasn't much in the Salesforce support community so I've come up with a workaround:

1. I added a charset identifier to the contenttype attribute like so:

<apex:page Controller="yourController" contenttype="application/msword#{!someVar};charset=utf-8" .. />

When you try to view your file, you get a little closer - your filename will likely look like: "------.doc".

2. The following thread, gave me the idea for the fix for ---- characters.  In the controller, we just encode the someVar value like so:

  String someVar = EncodingUtil.urlEncode(myString, 'UTF-8'); 
  return someVar;

When you try to view your file, you'll see the multibyte value in the filename.  You may have to do some substitution to remove any other characters, but this should get you closer to a user acceptable solution.

2 comments:

  1. I ran into a tangential issue in Chrome where the contenttype was not being recognized when the file was downloaded. So, I'd have to go through the trouble of telling windows how to deal w/ the file. The resolution, fortunately, is simple. Just add this the .doc file extension like this:

    ReplyDelete
  2. from this: contenttype="application/msword#{!someVar};charset=utf-8"
    to this: contenttype="application/msword#{!someVar}.doc;charset=utf-8"

    ReplyDelete