Thursday, July 30, 2009

Set,Specify PDF font type in Flying Soucer & iText

The following Java code shows you how to provide the font face for the created PDF output as same as in the input HTML or XHTML.

public static void createPDF(String url, String pdf)
throws IOException, DocumentException {
OutputStream os = null;
try {
os = new FileOutputStream(pdf);

ITextRenderer renderer = new ITextRenderer();
ResourceLoaderUserAgent callback = new ResourceLoaderUserAgent(renderer.getOutputDevice());
renderer.getSharedContext ().setUserAgentCallback(callback);

Document doc = XMLResource.load(new InputSource(url)).getDocument();

renderer.getFontResolver().addFont("C:\\Windows\\Fonts\\Verdana.TTF","UTF-8", BaseFont.NOT_EMBEDDED);
renderer.setDocument(doc, url);

os = null;
} finally {
if (os != null) {
try {
} catch (IOException e) {
// ignore

"renderer.getFontResolver().addFont()" is the key method used the set the font face information of the PDF generated.

"BaseFont.NOT_EMBEDDED" specify not to embed the font in generated PDF.

"url" is the input HTML/XHTML file path.

"pdf" is the generated PDF file path.

Please find the input XHTML/HTML below:

<style type="text/css">
font-family: "Verdana";
<body style="font-size:16px">
<center style="font-size:24px">
<b>Hi Prasad...</b></center>

You can similarly embed the font in the generated PDF by changing parameters passed to "renderer.getFontResolver().addFont"

Thanks, have a nice day!

No comments:

Post a Comment