Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

c# - iTextSharp international text

I have a table in asp.net page,and trying to export it as a PDF file,I have couple of international characters that are not shown in generated PDF file,any suggestions,

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The key for proper display of alternate characters sets (Russian, Chinese, Japanese, etc.) is to use IDENTITY_H encoding when creating the BaseFont.

Dim bfR As iTextSharp.text.pdf.BaseFont
  bfR = iTextSharp.text.pdf.BaseFont.CreateFont("MyFavoriteFont.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED)

IDENTITY_H provides unicode support for your chosen font, so you should be able to display pretty much any character. I've used it for Russian, Greek, and all the different European language letters.

EDIT - 2013-May-28

This also works for v5.0.2 of iTextSharp.

EDIT - 2015-June-23

Given below is a complete code sample (in C#):

private void CreatePdf()
{
  string testText = "???ě???";
  string tmpFile = @"C:est.pdf";
  string myFont = @"C:<<valid path to the font you want>>verdana.ttf";
  iTextSharp.text.Rectangle pgeSize = new iTextSharp.text.Rectangle(595, 792);
  iTextSharp.text.Document doc = new iTextSharp.text.Document(pgeSize, 10, 10, 10, 10);
  iTextSharp.text.pdf.PdfWriter wrtr;
  wrtr = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
      new System.IO.FileStream(tmpFile, System.IO.FileMode.Create));
  doc.Open();
  doc.NewPage();
  iTextSharp.text.pdf.BaseFont bfR;
  bfR = iTextSharp.text.pdf.BaseFont.CreateFont(myFont,
    iTextSharp.text.pdf.BaseFont.IDENTITY_H,
    iTextSharp.text.pdf.BaseFont.EMBEDDED);

  iTextSharp.text.BaseColor clrBlack = 
      new iTextSharp.text.BaseColor(0, 0, 0);
  iTextSharp.text.Font fntHead =
      new iTextSharp.text.Font(bfR, 12, iTextSharp.text.Font.NORMAL, clrBlack);

  iTextSharp.text.Paragraph pgr = 
      new iTextSharp.text.Paragraph(testText, fntHead);
  doc.Add(pgr);
  doc.Close();
}

This is a screenshot of the pdf file that is created:

sample pdf

An important point to remember is that if the font you have chosen does not support the characters you are trying to send to the pdf file, nothing you do in iTextSharp is going to change that. Verdana nicely displays the characters from all the European fonts I know of. Other fonts may not be able to display as many characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...