I’m trying to draw QR barcodes in a PDF file using iTextSharp. If I’m using English text the barcodes are fine, they are decoded properly, but if I’m using Chinese text, the barcode is decoded as question marks. For example this character ‘测’ (\u6D4B) is decoded as ‘?’. I tried all supported character sets, but none of them helped.
What combination of parameters should I use for the QR barcode in iTextSharp in order to encode correctly Chinese text?
I’m trying to draw QR barcodes in a PDF file using iTextSharp. If I’m
Share
iText and iTextSharp apparently don’t natively support this but you can write some code to handle this on your own. The trick is to get the QR code parser to work with just an arbitrary byte array instead of a string. What’s really nice is that the iTextSharp code is almost ready for this but doesn’t expose the functionality. Unfortunately many of the required classes are
sealedso you can’t just subclass them, you’ll have to recreate them. You can either download the entire source and add these changes or just create separate classes with the same names. (Please check over the license to make sure you are allowed to do this.) My changes below don’t have any error correction so make sure you do that, too.The first class that you’ll need to recreate is
iTextSharp.text.pdf.qrcode.BlockPairand the only change you’ll need to make is to make the constructorpublicinstead ofinternal. (You only need to do this if you are creating your own code and not modifying the existing code.)The second class is
iTextSharp.text.pdf.qrcode.Encoder. This is where we’ll make the most changes. Add an overload toAppend8BitBytesthat looks like this:The string version of this method converts text to a byte array and then uses the above so we’re just cutting out the middle man. Next, add a new overload to the constructor that takes in a byte array instead of a string. We’ll then just cut out the string detection part and force the system to byte-mode, otherwise the code below is pretty much the same.
The third class is
iTextSharp.text.pdf.qrcode.QRCodeWriterand once again we just need to add an overloadedEncodemethod supports a byte array and that calls are new constructor created above:The last class is
iTextSharp.text.pdf.BarcodeQRCodewhich we once again add our new constructor overload:The last trick is to make sure when calling this that you include the byte order mark (BOM) so that decoders know to decode this properly, in this case UTF-8.