itext导出word和pdf

最近工作中遇到导出word及pdf,之前使用poi导出过xls,导出word和pdf则没有接触过。通过在网上查阅部分资料和自己的实际编写,对导出word及pdf总结如下:
本文通过itext导出word及pdf,并且word导出后缀为.doc
1.导出word
package com.mydoc.test;  
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.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;
/**
* 创建word文档 步骤:
* 1,建立文档
* 2,创建一个书写器
* 3,打开文档
* 4,向文档中写入数据
* 5,关闭文档
*/
public class WordDemo {

public WordDemo() {
}

/**
* @param args
*/
public static void main(String[] args) {
// 创建word文档,并设置纸张的大小
Document document = new Document(PageSize.A4);
try {
RtfWriter2.getInstance(document,new FileOutputStream("D:/wordTest.doc"));
document.open();
//设置合同头
Paragraph ph = new Paragraph();
Font f = new Font();
Paragraph p = new Paragraph("出口合同", new Font(Font.NORMAL, 18, Font.BOLDITALIC, new Color(0, 0, 0)) );
p.setAlignment(1);
document.add(p);
ph.setFont(f);

// 设置中文字体
// BaseFont bfFont =
// BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
// Font chinaFont = new Font();
/*
* 创建有三列的表格
*/
Table table = new Table(3);
table.setBorderWidth(1);
table.setBorderColor(Color.BLACK);
table.setPadding(0);
table.setSpacing(0);

/*
* 添加表头的元素
*/
Cell cell = new Cell("表头");//单元格
cell.setHeader(true);
cell.setColspan(2);//设置表格为2列
cell.setRowspan(2);//设置表格为2行
table.addCell(cell);
table.endHeaders();// 表头结束

// 表格的主体
cell = new Cell("right data");
table.addCell(cell);
table.addCell("1,3");
table.addCell(new Paragraph("2,3"));
table.addCell(new Paragraph("3,3"));
document.add(table);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

2.导出pdf
public void exportPdf() {
Document document=null;
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 设置中文字体
Font headFont = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小

//第一步:创建一个document对象。
document = new Document();
//第二步:创建一个PdfWriter实例,将文件输出流指向一个文件。
PdfWriter.getInstance(document, new FileOutputStream("D:/test/123.pdf"));
//第三步:打开文档。
document.open();
Paragraph title = new Paragraph("你好,Pdf!", headFont);
//第四步:在文档中增加一个段落。
document.add(title);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(document!=null){
//第五步:关闭文档。
document.close();
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值