1. 程式人生 > >Java POI 生成PDF文件,很給力!

Java POI 生成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成功!");
     }
    
    
}