java itext 生成pdf文档

需要的jar包:itextpdf-5.4.4.jar,下载见附件

代码如下:

package com.itext.pdf.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.stream.FileImageInputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class MyPDF {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //1、创建一个document对象
        Rectangle rect = new Rectangle(PageSize.A4);//设置页面大小为A4纸大小
        rect = rect.rotate();//页面横向显示
        Document document = new Document(rect);
        document.setMargins(50, 50, 50, 50);//设置页边距
        try {
            //2、创建一个Writer实例
            File file = new File("D:\\pdf\\ITextTest.pdf");
            if(file.exists()){
                file.delete();
            }
            FileOutputStream fos = new FileOutputStream(file);
            PdfWriter.getInstance(document, fos);
            //3、打开文档
            document.open();
                           
            //4、为文档添加内容
            document.add(new Paragraph("一、第一章",getChineseFont()));
            document.add(new Paragraph("您刚才看到了如何将纯文本添加到 PDF 文档中。接下来,我们需要向文档中添加一些复杂的元素。首先创建一个新章",getChineseFont()));
                           
                           
            /*================================第二页========================================*/
            document.newPage();//添加新的页
                           
            document.add(new Paragraph("二、第二章",getChineseFont()));
            document.add(new Paragraph("添加表格",getChineseFont()));
                           
            float[] width = {200f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f,70f};
            PdfPTable  table = new PdfPTable(width);
            table.setSpacingBefore(25);
            table.setSpacingAfter(25);
            table.setHorizontalAlignment(0);//水平左对齐
            table.setWidthPercentage(100f);//设置百分比
            for(int row=0;row<10;row++){
                for(int i=0;i<=24;i++){
                    if(row==0){
                        if(i==0){
                            PdfPCell cell = new PdfPCell(new Phrase("日期",getChineseFont()));
                            cell.setNoWrap(true);//设置是否换行
                            cell.setFixedHeight(22);//设置固定行高
                            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直方向居中对齐
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平方向居中对齐
                            table.addCell(cell);
                        }else{
                            PdfPCell cell = new PdfPCell(new Phrase(i+"点",getChineseFont()));
                            cell.setNoWrap(true);
                            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直方向居中对齐
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平方向居中对齐
                            table.addCell(cell);
                        }
                    }else{
                        if(i==0){
                            PdfPCell cell = new PdfPCell(new Phrase(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
                            cell.setNoWrap(true);
                            cell.setFixedHeight(18);//设置固定行高
                            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直方向居中对齐
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平方向居中对齐
                            table.addCell(cell);
                        }else{
                            int a=(int) Math.random()*40;
                            PdfPCell cell = new PdfPCell(new Phrase(""+a));
                            cell.setNoWrap(false);
                            cell.setFixedHeight(18);//设置固定行高
                            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直方向居中对齐
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平方向居中对齐
                            table.addCell(cell);
                        }
                    }
                }
            }
            document.add(table);
                           
            /*================================第三页========================================*/
            document.newPage();//添加新的页
                           
            document.add(new Paragraph("三、第三章",getChineseFont()));
                           
            File imageFile = new File("D:\\pdf\\a.jpg");
            byte[] b = setImageToByteArray(imageFile);
            Image image = Image.getInstance(b);
            image.setSpacingBefore(25);
            image.setSpacingAfter(25);
            document.add(image);
                           
                           
            /*================================第四页========================================*/
            document.newPage();//添加新的页
                           
            document.add(new Paragraph("四、第四章",getChineseFont()));
            float[] width2 = {100f};
            PdfPTable  table2 = new PdfPTable(width2);
            table2.setSpacingBefore(25);
            table2.setSpacingAfter(25);
            PdfPCell cell = new PdfPCell(new Phrase("在示例代码0609中,我们添加一个从一个Jpeg文件中读入到字节数组中的图片,很明显,使用其他getInstance方法得到实例更优越,但这仅仅是一个例子,该getInstance方法在动态创建那些根本不存在的图片时非常有用。"
                    ,getChineseFont()));
            cell.setPadding(10f);
            table2.addCell(cell);
            document.add(table2);
                           
            //5、关闭文档
            document.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
                   
    //转换中文
    public static  Font getChineseFont(){
        Font fontChinese = null;
        try {
            BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf,12,Font.NORMAL);
        } catch (DocumentException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
        return fontChinese;
    }
                   
    //将图片文件转换成二进制流
    public static byte[] setImageToByteArray(File filename){
            byte[] image = null;
            try {
                FileImageInputStream fis;
                fis = new FileImageInputStream(filename);
                int streamLength = (int) fis.length();
                image = new byte[streamLength];
                fis.read(image,0,streamLength);
                fis.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                       
        return image;
    }
                   
                   
                   
                   
                   
                   
}

输出结果如下:

154242439.jpg

你可能感兴趣的:(java,java,pdf,itext)