问题
I am trying to output a Euro symbol to a PDF using Core Graphics. I have the following code, which uses NSMacOSRomanStringEncoding (I had to use this to get £ and $ symbols to appear correctly), but the Euro symbol comes out as ¤
CGRect pageRect = CGRectMake(0, 0, 800, 1150);
CFMutableDataRef pdfData = (CFMutableDataRef) [NSMutableData dataWithCapacity:0];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(pdfData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, nil);
CGContextSelectFont(pdfContext, "Helvetica", 15, kCGEncodingMacRoman);
CGContextSetTextDrawingMode (pdfContext, kCGTextFill);
CGContextSetRGBFillColor (pdfContext, 0, 0, 0, 1);
const char *ctext = [@"€" cStringUsingEncoding:NSMacOSRomanStringEncoding];
CGContextShowTextAtPoint(pdfContext, 10, 10, ctext, strlen(ctext));
回答1:
You should be able to use CGContextShowGlyphsAtPoint
to draw the Euro symbol. The catch is that you need to pass that function a CGGlyph
as input, rather than a Unicode character. Furthermore, the mapping from Unicode characters to CGGlyphs
is font-dependent and often nontrivial. (Sometimes it's a simple offset that you can guess based on trial and error.)
It looks like Core Text has a function CTFontGetGlyphsForCharacters
which might perform the transformation; I've never used it in practice, though:
http://developer.apple.com/library/mac/#documentation/Carbon/Reference/CTFontRef/Reference/reference.html
Also: if you use CGContextShowGlyphsAtPoint
you will need to replace the call to CGContextSelectFont
with CGContextSetFont
and CGContextSetFontSize
instead.
回答2:
Thats because MacRomanEncoding
doesn't contain euro symbol by default, see this quote from "PDF reference 1.7" (Section D.1 Latin Character Set and Encodings):
- In PDF 1.3, the euro character was added to the Adobe standard Latin character set. It is encoded as 200 in WinAnsiEncoding and 240 in PDFDocEncoding, assigning codes that were previously unused. Apple changed the Mac OS Latin-text encoding for code 333 from the currency character to the euro character. However, this incompatible change has not been reflected in PDF’s MacRomanEncoding, which continues to map code 333 to currency. If the euro character is desired, an encoding dictionary can be used to specify this single difference from MacRomanEncoding.
来源:https://stackoverflow.com/questions/7505143/how-to-output-a-euro-symbol-in-a-pdf