Itext PDF writer, Is there any way to allow unicod

2019-07-16 17:54发布

问题:

I have been trying to create PDF files using Itext PDF writer. I have found that Superscript (0,4,5,6,7,8,9) and Subscript (0,1,2,3,4,5,6,7,8,9) are not allowed in the default font. Only Superscript 1,2,3 are allowed in PDF texts in the default setting.

A String in my PDF contains subscript and superscript characters, is there a way i can display them in PDF?

I searched and found:

  1. setTextRise() method is used to change the displacement of the text with respect to the current line, I cannot use it as i don't know which characters are to super/sub scripted.
  2. Is there a setting to change the encoding/font of the text to UTF-8, so that it allows all the unicode symbols?

Or some other way, because i have to show chemical symbols like H₂SO⁴, O₂ etc.

It'd be of great help, thanks!

回答1:

Please take a look at the SubSuperScript example I wrote in answer to your question. I'm writing H₂SO⁴ like this:

BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 10);
Paragraph p = new Paragraph("H\u2082SO\u2074", f);
document.add(p);

I've found the values of the specific characters on Wikipedia: http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts

As you can see, iText is perfectly capable to show the special characters written in subscript or superscript: sub_superscript.pdf

The main problem I had when I wrote this example was finding a font that supported the specific glyphs. That's what I explained in my earlier comment. I ended up using a font called "Carbo Regular".



回答2:

I could get to solve the issue by using this piece of code:

I had to register a new font "Arial Unicode MS"

FontFactory.register("Path/to/font/arial unicode ms.ttf","Arial Unicode MS");

Then while writing in the pdf i had to use this font with my string:

FontFactory.getFont("Arial Unicode MS",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);