生成PDF文档例子

package poi.itext;

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

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.BaseFont;

/**
 * 创建Pdf文档
 * @author Administrator
 *
 */

public class HelloPdf
{
    public static void main(String[] args)throws Exception
    {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);

        // 第一步,创建document对象
        Rectangle rectPageSize = new Rectangle(PageSize.A4);
       
        //下面代码设置页面横置
        //rectPageSize = rectPageSize.rotate();
       
        //创建document对象并指定边距
        Document doc = new Document(rectPageSize,50,50,50,50);
        Document document = new Document();
        try
        {
            // 第二步,将Document实例和文件输出流用PdfWriter类绑定在一起
            //从而完成向Document写,即写入PDF文档
            PdfWriter.getInstance(document,new FileOutputStream("src/poi/itext/HelloWorld.pdf"));
            //第3步,打开文档
            document.open();
            //第3步,向文档添加文字. 文档由段组成
            document.add(new Paragraph("Hello World"));

            Paragraph par = new Paragraph("世界你好",FontChinese);
            document.add(par);

            PdfPTable table = new PdfPTable(3);
            for(int i=0;i<12;i++)
            {
                if (i == 0)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.setColspan(3);
                    cell.setBackgroundColor(new Color(180,180,180));
                    cell.addElement(new Paragraph("表格头" , FontChinese));
                    table.addCell(cell);
                }
                else
                {
                    PdfPCell cell = new PdfPCell();
                    cell.addElement(new Paragraph("表格内容" , FontChinese));
                    table.addCell(cell);
                }
            }
            document.add(table);

        }
        catch (DocumentException de)
        {
            System.err.println(de.getMessage());
        }
        catch (IOException ioe)
        {
            System.err.println(ioe.getMessage());
        }
        //关闭document
        document.close();
       
        System.out.println("生成HelloPdf成功!");
     }
   
   
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值