Reputation: 484
I'm using Android's built-in PrintedPdfDocument to draw PDFs with a Canvas as outlined in this document's example code:
private void drawPage(PdfDocument.Page page) {
Canvas canvas = page.getCanvas();
// units are in points (1/72 of an inch)
int titleBaseLine = 72;
int leftMargin = 54;
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(36);
canvas.drawText("Test Title", leftMargin, titleBaseLine, paint);
paint.setTextSize(11);
canvas.drawText("Test paragraph", leftMargin, titleBaseLine + 25, paint);
paint.setColor(Color.BLUE);
canvas.drawRect(100, 100, 172, 172, paint);
}
Is it possible to add emoji text to this document? I cannot figure out how to set character sets/encodings.
Whenever I try adding emoji output it shows up garbled in the pdf.
This is the code which saves the pdf:
mPdfDocument = new PrintedPdfDocument(context, printAttributes);
mCurrentPage = mPdfDocument.startPage(1);
Canvas canvas = mCurrentPage.getCanvas();
... // add stuff to canvas
mPdfDocument.finishPage(mCurrentPage);
FileOutputStream fos = new FileOutputStream(new File(path));
mPdfDocument.writeTo(fos);
fos.close();
Thanks!
Upvotes: 1
Views: 925
Reputation: 484
I got the answer. Here is some sample code:
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSansEmoji.ttf");
paint.setTypeface(typeface);
You can find the OpenSansEmoji.ttf typeface here or find some other emoji font.
Place this file in your assets/fonts folder in your Android project.
Upvotes: 1
Reputation: 208
Create a string with the unicode value of the emoji. Then pass the string to drawText method:
String smileyFace = new String(Character.toChars(0x1F603))); //0x1F603 = Smile emoji
canvas.drawText(smileyFace, leftMargin, titleBaseLine, paint);
Upvotes: 0