iText生成rtf文件简单例子

最近研究用java生成word文档,原来打算用poi的,但是在word2003下乱码,因为rtf格式用word也可以打开,itext对这个的支持不错,下面是它的一个简单例子。
[b]
1.需要的包[/b]
(1)itext-2.0.4.jar
(2)iTextAsian.jar

[b]2.源码[/b]

import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;

/**
* @author new
*/
public class RtfMain
{
private static final String FILE_NAME = "e:/itext_rtf.rtf";

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
RtfMain rtfMain = new RtfMain();
rtfMain.createRTFContext(FILE_NAME);

}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}



public void createRTFContext(String path)throws DocumentException,
IOException
{
Document document = new Document(PageSize.A4);
RtfWriter2.getInstance(document, new FileOutputStream(path));
document.open();
//设置中文字体
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//标题字体风格
Font titleFont= new Font(bfChinese, 12, Font.BOLD);

//正文字体风格
Font contextFont= new Font(bfChinese, 10, Font.NORMAL);

Paragraph title = new Paragraph("标题");
//设置标题格式对齐方式
title.setAlignment(Element.ALIGN_CENTER);
title.setFont(titleFont);
document.add(title);

String contextString = "iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。";
Paragraph context = new Paragraph(contextString);
//正文格式左对齐
context.setAlignment(Element.ALIGN_LEFT);
context.setFont(contextFont);
//离上一段落(标题)空的行数
context.setSpacingBefore(20);
//设置第一行空的列数
context.setFirstLineIndent(20);

document.add(context);

// //在表格末尾添加图片
// Image png=Image.getInstance("d:\\duck.jpg");
// document.add(png);
document.close();
}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值