PdfBox encode symbol currency euro

I created a PDF document with the Apache PDFBox library. My problem is to encode the euro currency symbol when drawing a string on the page, because the base font Helvetica does not provide this character. How I can convert the output "þÿ ¬" to the symbol "€"?.


Unfortunately PDFBox's String encoding is far from perfect yet (version 1.8.x). Unfortunately it uses the same routines when encoding strings in generic PDF objects as when encoding strings in content streams which is fundamentally wrong. Thus, instead of using PDPageContentStream.drawString (which uses that wrong encodings), you have to translate to the correct encoding yourself.

E.g. instead of using

    contentStream.beginText();
    contentStream.setTextMatrix(100, 0, 0, 100, 50, 100);
    contentStream.setFont(PDType1Font.HELVETICA, 2);
    contentStream.drawString("€");
    contentStream.endText();
    contentStream.close();

which results in

€ wrong encoding

you could use some like

    contentStream.beginText();
    contentStream.setTextMatrix(100, 0, 0, 100, 50, 100);
    contentStream.setFont(PDType1Font.HELVETICA, 8);
    byte[] commands = "(x) Tj ".getBytes();
    commands[1] = (byte) 128;
    contentStream.appendRawCommands(commands);
    contentStream.endText();
    contentStream.close();

resulting in

€ correct encoding

If you wonder how I got to use 128 as byte code for the €, have a look at the PDF specification ISO 32000-1, annex D.2, Latin Character Set and Encodings which indicates an octal value 200 (decimal 128) for the € symbol in WinAnsiEncoding.


PS: An alternative approach has meanwhile been presented by other answers which in case of the € symbol amounts to something like:

    contentStream.beginText();
    contentStream.setTextMatrix(100, 0, 0, 100, 50, 100);
    contentStream.setFont(PDType1Font.HELVETICA, 8);
    contentStream.drawString(String.valueOf(Character.toChars(EncodingManager.INSTANCE.getEncoding(COSName.WIN_ANSI_ENCODING).getCode("Euro"))));
    contentStream.endText();
    contentStream.close();

This indeed also draws the '€' symbol. But even though this approach looks cleaner (it does not use byte arrays, it does not construct an actual PDF stream operation manually), it is dirty in its own way:

To use a broken method, it actually breaks its string argument in just the right way to counteract the bug in the method.

Thus, if the PDFBox people decided to fix the broken PDFBox method, this seemingly clean work-around code here would start to fail as it would then feed the fixed method broken input data.

Admittedly, I doubt they will fix this bug before 2.0.0 (and in 2.0.0 the fixed method has a different name), but one never knows...


This worked for me:

char symbol = '€';

Encoding e = EncodingManager.INSTANCE.getEncoding(COSName.WIN_ANSI_ENCODING);

String toPDF = String.valueOf(Character.toChars(e.getCode(e.getNameFromCharacter(symbol))));`