How to apply the superscript and subscript to PDF file with using iText5.0
843789May 5 2010 — edited May 5 2010Hi All,
I am drawing text to pdf page using the AttributedString.
when adding the Surperscript and subscript Attributes to AttributedString then
drawing aAttributedCharacterIterator from AttributedString is not working properly , but i can achieve it by TextLayout object
can any one pls let me know why AttributedString dosnt work properly.
here is the sample code
import java.awt.Graphics2D;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.AttributedString;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
public class GenPdfPage
{
public static void main(String[] args) throws DocumentException,
IOException
{
createPdfFile("d:\\temp.pdf");
}
private static void createPdfFile(String f) throws DocumentException,
IOException
{
float width = 5 * 72;
float height = 5 * 72;
PdfWriter writer = null;
Document doc = new Document(new Rectangle(width, height));
FileOutputStream fos = new FileOutputStream(f);
writer = PdfWriter.getInstance(doc, fos);
doc.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate tem = contentByte.createTemplate(width, height);
Graphics2D g2d = tem.createGraphics(width, height);
drawAttributedString(g2d);
contentByte.addTemplate(tem, 0, 0);
g2d.dispose();
doc.close();
writer.close();
fos.close();
Runtime.getRuntime().exec("cmd.exe /c start " + f);
}
private static void drawAttributedString(Graphics2D g2d)
{
String str = "18th May 1984";
AttributedString as = new AttributedString(str);
as.addAttribute(TextAttribute.SUPERSCRIPT,
TextAttribute.SUPERSCRIPT_SUPER, 2, 4);
LineBreakMeasurer lbm = new LineBreakMeasurer(as.getIterator(), g2d
.getFontRenderContext());
TextLayout tl = lbm.nextLayout(500);
tl.draw(g2d, 10, 20);
g2d.drawString(as.getIterator(), 20, 40);
}
}
Thanks
Rajesh Voruganti