Java iText显示unicode字符时出现问题
我需要一些关于android上iText的帮助。我正在创建一个PDF,需要它显示像:ā,ū,ē,ķ,č这样的字符。下面是我用来创建自定义字体的代码Java iText显示unicode字符时出现问题,java,android,pdf,itext,pdf-generation,Java,Android,Pdf,Itext,Pdf Generation,我需要一些关于android上iText的帮助。我正在创建一个PDF,需要它显示像:ā,ū,ē,ķ,č这样的字符。下面是我用来创建自定义字体的代码 BaseFont bf; { try { bf = BaseFont.createFont("c:/windows/fonts/CAMBRIA.TTC", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } catch (DocumentException e) { e
BaseFont bf;
{
try {
bf = BaseFont.createFont("c:/windows/fonts/CAMBRIA.TTC", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Font smallFont = new Font(bf, 12);
这是我如何使用它的一个例子
PdfPTable table_start = new PdfPTable(3);
PdfPCell name = new PdfPCell(new Paragraph("Objekts: " + view0.getText().toString(), smallFont));
当我在视图中显示从另一个活动中获取的字符串时,文本看起来正常,但当创建PDF时,所有特殊字符都消失了。遵循以下步骤:
将Unicode文本转换为ANSI字体支持的文本
然后使用ANSI字体生成pdf
首先,您必须转换Unicode文本,如下所示:
然后创建PDF
PDF的单元格创建
答案其实相当简单。我所要做的就是在assets文件夹中放置一种支持Unicode字符的字体,然后更改:
bf = BaseFont.createFont("c:/windows/fonts/CAMBRIA.TTC", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
到
我在调用BaseFont.createFont API时,在编码参数中使用了BaseFont.IDENTITY_H,它起了作用。OP也使用了IDENTITY_H。他的问题本质上是他使用了Android上某些Windows系统c:/Windows/fonts/CAMBRIA.TTC的字体路径,请参见他的答案。
public void CreateBanglaMemoTableFormat(List<PDFTableData> items) {
Document doc = new Document(PageSize.A4.rotate());
try {
setYourFont();
doc = new Document(new Rectangle(818.3f, 609f));
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyPDF";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "newPDFFile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph();
p1.setAlignment(Paragraph.ALIGN_LEFT);
p1.setFont(f_textFont);
p1.add(formattedMsg);
PdfPTable tt = masteraTableCreation(p1);
doc.add(tt);
}
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
} finally {
doc.close();
}
}
public void setYourFont() throws DocumentException, IOException {
try {
bf = BaseFont.createFont("/fontname", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
f_textFont = new Font(bf, 10);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private PdfPTable masteraTableCreation(Paragraph celV1) {
float[] columnWidths = {236};
PdfPTable mainTable = new PdfPTable(columnWidths);
mainTable.getDefaultCell().setPaddingRight(5);
mainTable.setTotalWidth(786f);
mainTable.setLockedWidth(true);
PdfPCell cell;
//region Row 1
// column 1
cell = new PdfPCell(new Phrase(celV1));
cell.setBorder(Rectangle.NO_BORDER);
mainTable.addCell(cell);
return mainTable;
}
bf = BaseFont.createFont("c:/windows/fonts/CAMBRIA.TTC", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
bf_smallfont = BaseFont.createFont("assets/times.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);