Buffer gIdBuffer = new Buffer();
gIdBuffer.append((byte)0);
gIdBuffer.append((byte)0);
int code = 0;
codes = new BiMap<ByteArray,Integer>(glyphIndexes.size());
PdfArray widthsObject = new PdfArray(glyphWidths.size());
for(Map.Entry<Integer,Integer> glyphIndexEntry : glyphIndexes.entrySet())
{
// Character code (codepoint to unicode) entry.
code++;
byte[] charCode = (glyphIndexEntry.getKey() == 32
? new byte[]{32}
: new byte[]
{
(byte)((code >> 8) & 0xFF),
(byte)(code & 0xFF)
});
codes.put(new ByteArray(charCode),glyphIndexEntry.getKey());
// CMap entry.
cmapBuffer.append("<");
toUnicodeBuffer.append("<");
for(int charCodeBytesIndex = 0,
charCodeBytesLength = charCode.length;
charCodeBytesIndex < charCodeBytesLength;
charCodeBytesIndex++
)
{
String hex = Integer.toHexString((int)charCode[charCodeBytesIndex]);
//TODO:improve hex padding!!!
if(hex.length() == 1)
{hex = "0" + hex;}
else
{hex = hex.substring(hex.length()-2,hex.length());}
cmapBuffer.append(hex);
toUnicodeBuffer.append(hex);
}
cmapBuffer.append("> " + code + "\n");
toUnicodeBuffer.append("> <" + getHex(glyphIndexEntry.getKey()) + ">\n");
// CID-to-GID entry.
int glyphIndex = glyphIndexEntry.getValue();
gIdBuffer.append((byte)((glyphIndex >> 8) & 0xFF));
gIdBuffer.append((byte)(glyphIndex & 0xFF));
// Width.
int width;
try
{width = glyphWidths.get(glyphIndex);if(width>1000){width=1000;}}
catch(Exception e)
{width = 0;}
widthsObject.add(new PdfInteger(width));
}
cmapBuffer.append(
"endcidchar\n"
+ "endcmap\n"
+ "CMapName currentdict /CMap defineresource pop\n"
+ "end\n"
+ "end\n"
+ "%%EndResource\n"
+ "%%EOF"
);
PdfStream cmapStream = new PdfStream(cmapBuffer);
PdfDictionary cmapHead = cmapStream.getHeader();
cmapHead.put(
PdfName.Type,
PdfName.CMap
);
cmapHead.put(
PdfName.CMapName,
new PdfName("Adobe-Identity-UCS")
);
cmapHead.put(
PdfName.CIDSystemInfo,
new PdfDictionary(
new PdfName[]
{
PdfName.Registry,
PdfName.Ordering,
PdfName.Supplement
},
new PdfDirectObject[]
{
new PdfTextString("Adobe"),
new PdfTextString("Identity"),
new PdfInteger(0)
}
)
); // Generic predefined CMap (Identity-H/V (Adobe-Identity-0)) [PDF:1.6:5.6.4].
font.put(
PdfName.Encoding,
getFile().register(cmapStream)
);
PdfStream gIdStream = new PdfStream(gIdBuffer);
cidFont.put(
PdfName.CIDToGIDMap,
getFile().register(gIdStream)
);
cidFont.put(
PdfName.W,
new PdfArray(new PdfDirectObject[]{new PdfInteger(1),widthsObject})
);
toUnicodeBuffer.append(
"endbfchar\n"
+ "endcmap\n"