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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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(50505050);//设置页边距
        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;
    }
                    
                    
                    
                    
                    
                    
}

输出结果如下:

java itext 生成pdf文档