简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件

时间:2022-03-17 06:37:06

一、如何生成一个pdf文件

需要导入的包:

简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件

 

我简单封装了一个生成类: 

  1 package com.jason.pdf;
  2 
  3 import java.awt.Color;
  4 import java.awt.image.BufferedImage;
  5 import java.io.BufferedReader;
  6 import java.io.ByteArrayOutputStream;
  7 import java.io.FileNotFoundException;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.io.InputStreamReader;
 11 import java.net.MalformedURLException;
 12 
 13 import javax.imageio.ImageIO;
 14 
 15 import com.lowagie.text.BadElementException;
 16 import com.lowagie.text.DocumentException;
 17 import com.lowagie.text.Element;
 18 import com.lowagie.text.Font;
 19 import com.lowagie.text.FontFactory;
 20 import com.lowagie.text.HeaderFooter;
 21 import com.lowagie.text.Image;
 22 import com.lowagie.text.Paragraph;
 23 import com.lowagie.text.Phrase;
 24 import com.lowagie.text.Rectangle;
 25 import com.lowagie.text.pdf.BaseFont;
 26 import com.lowagie.text.pdf.PdfContentByte;
 27 import com.lowagie.text.pdf.PdfPCell;
 28 import com.lowagie.text.pdf.PdfWriter;
 29 
 30 /**
 31  * PDF生成工具
 32  * @function  
 33  * @author 小风微凉
 34  * @time  2018-9-14 下午2:13:08
 35  */
 36 public class CreatePDFUtil {
 37     /**
 38      * 创建单元格
 39      * @param content    内容
 40      * @param font    字体
 41      * @return
 42      */
 43     public static PdfPCell cell(String content, Font font) {
 44         PdfPCell cell = new PdfPCell(new Phrase(content, font));
 45         cell.setBorderColor(new Color(196, 196, 196));
 46         cell.setPadding(5.0f);
 47         cell.setPaddingTop(0.5f);
 48         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
 49         cell.setHorizontalAlignment(Element.ALIGN_CENTER);
 50         return cell;
 51     }
 52     /**
 53      * 创建单元格
 54      * @param content 内容
 55      * @param font 字体
 56      * @param hAlign 上下对齐
 57      * @param vAlign 水平对齐
 58      * @return
 59      */
 60     public static PdfPCell cell(String content, Font font, int hAlign, int vAlign) {
 61         PdfPCell cell = new PdfPCell(new Phrase(content, font));
 62         cell.setBorderColor(new Color(196, 196, 196));
 63         cell.setVerticalAlignment(vAlign);
 64         cell.setHorizontalAlignment(hAlign);
 65         cell.setPadding(5.0f);
 66         cell.setPaddingTop(1.0f);
 67         return cell;
 68     }
 69     /**
 70      * 创建段落
 71      * @param content    内容
 72      * @param font   字体
 73      * @return
 74      */
 75     public static Paragraph paragraph(String content, Font font) {
 76         return new Paragraph(content, font);
 77     }
 78     /**
 79      * 创建段落
 80      * @param content    内容
 81      * @param font    字体
 82      * @param hAlign    上下对齐
 83      * @return
 84      */
 85     public static Paragraph paragraph(String content, Font font, int hAlign) {
 86         Paragraph paragraph = new Paragraph(content, font);
 87         paragraph.setAlignment(hAlign);
 88         return paragraph;
 89     }
 90     /**
 91      * 创建段落
 92      * @param content    内容
 93      * @param font    字体
 94      * @param hAlign    对齐
 95      * @param spacingBefore 空格
 96      * @return
 97      */
 98     public static Paragraph paragraph(String content, Font font, int hAlign, float spacingBefore) {
 99         Paragraph paragraph = new Paragraph(content, font);
100         paragraph.setAlignment(hAlign);
101         paragraph.setSpacingBefore(spacingBefore);
102         return paragraph;
103     }
104     /**
105      * 根据字体大小获取字体样式[支持中文]
106      * @param fontSize 字体尺寸
107      * @throws IOException 
108      * @throws DocumentException 
109      */
110     public static Font getChineseFont(int fontSize) throws DocumentException, IOException{
111         BaseFont fontChinese= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);// 设置中文字体
112         return new Font(fontChinese,  fontSize, Font.NORMAL);
113     }
114     /**
115      * 根据字体大小获取字体样式[不支持中文]
116      * @param fontSize 字体尺寸
117      * @throws IOException 
118      * @throws DocumentException 
119      */
120     public static Font getFont(int fontSize){
121         return FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, fontSize);
122     }
123     /**
124      * 读取项目图片资源文件
125      *
126      * @param filePath 以'/'开头的项目资源文件路径
127      * @return
128      */
129     public static byte[] readResourceImage(String filePath) {
130         try {
131             InputStream is = CreatePDFUtil.class.getResourceAsStream(filePath);
132             BufferedImage image = ImageIO.read(is);
133             is.close();
134             ByteArrayOutputStream os = new ByteArrayOutputStream();
135             ImageIO.write(image, "png", os);
136             return os.toByteArray();
137         } catch (FileNotFoundException e) {
138             System.out.println("FileNotFoundException:"+e.getMessage());
139         } catch (IOException e) {
140             System.out.println("IOException:"+e.getMessage());
141         }
142         return null;
143     }
144 
145     /**
146      * 读取项目资源文件内容
147      *
148      * @param filePath 以'/'开头的项目资源文件路径
149      * @return 文件内容
150      */
151     public static String readResourceContent(String filePath) {
152         StringBuilder sb = new StringBuilder();
153         try {
154             BufferedReader reader = new BufferedReader(new InputStreamReader(CreatePDFUtil.class.getResourceAsStream(filePath)));
155             String line;
156             while ((line = reader.readLine()) != null) {
157                 sb.append(line);
158                 sb.append("\n");
159             }
160             reader.close();
161         } catch (FileNotFoundException e) {
162             System.out.println("FileNotFoundException:"+e.getMessage());
163         } catch (IOException e) {
164             System.out.println("IOException:"+e.getMessage());
165         }
166         return sb.toString();
167     }
168     /**
169      * 设置页眉[默认居中]
170      * @param head 页眉数据
171      */
172     public static HeaderFooter getPagerHeader(String head,Font font){
173          HeaderFooter header=new HeaderFooter(new Phrase(head,font),false);
174          header.setBorder(Rectangle.NO_BORDER);
175          header.setAlignment(1);//居中 
176          return header;
177     }
178     /**
179      * 设置页脚[默认居右]
180      * @param head 页眉数据
181      */
182     public static HeaderFooter getPagerFooter(Font font){
183         HeaderFooter footer = new HeaderFooter(new Phrase("第:",font), new Phrase("页",font));
184         footer.setBorder(Rectangle.NO_BORDER);
185         footer.setAlignment(2);//居右
186         return footer;
187     }
188     /**
189      * 在画布的指定位置添加图片
190      * @param writer
191      * @param rectPageSize
192      * @throws MalformedURLException
193      * @throws IOException
194      * @throws DocumentException
195      */
196     public static void creatImage(PdfWriter writer,Rectangle rectPageSize) throws MalformedURLException, IOException, DocumentException{
197          byte[] bytes = CreatePDFUtil.readResourceImage("/images/icon.png");
198          if (bytes != null) {
199              Image image = Image.getInstance(bytes);
200              PdfContentByte canvas = writer.getDirectContent();
201              int pageNum=writer.getPageNumber();
202              System.out.println("当前页码:"+pageNum);
203              //向画布添加图片:
204              /**
205               * image:图片对象
206               * 50:宽度
207               * 0:倾斜角度-设置为0即可
208               * 0: 倾斜角度-设置为0即可
209               * 50:高度
210               * rectPageSize.getWidth() - 300: 图片所在y轴位置
211               * rectPageSize.getHeight() - 300:图片所在x轴位置
212               */
213              canvas.addImage(image,50, 0, 0, 50, rectPageSize.getWidth() - 300, rectPageSize.getHeight() - 300);
214          } else {
215              System.out.println("Failed to read *.png");
216          }
217     }
218 }

 使用上面这个工具类:生成一个pdf文件

  1 package com.jason.pdf;
  2 
  3 import java.awt.Color;
  4 import java.io.File;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 
  9 import com.lowagie.text.Document;
 10 import com.lowagie.text.DocumentException;
 11 import com.lowagie.text.Element;
 12 import com.lowagie.text.Font;
 13 import com.lowagie.text.HeaderFooter;
 14 import com.lowagie.text.Image;
 15 import com.lowagie.text.PageSize;
 16 import com.lowagie.text.Paragraph;
 17 import com.lowagie.text.Phrase;
 18 import com.lowagie.text.Rectangle;
 19 import com.lowagie.text.pdf.BaseFont;
 20 import com.lowagie.text.pdf.PdfContentByte;
 21 import com.lowagie.text.pdf.PdfPCell;
 22 import com.lowagie.text.pdf.PdfPTable;
 23 import com.lowagie.text.pdf.PdfWriter;
 24 
 25 public class Test1 {
 26 
 27     /**
 28      * @param args
 29      */
 30     public static void main(String[] args) {
 31         //创建pdf纸张
 32         Rectangle rectPageSize = new Rectangle(PageSize.A4 );// A4纸张:PageSize.A4
 33         //创建pdf文档对象
 34         Document document = new Document(rectPageSize, 10, 10, 10, 10);// 上、下、左、右间距
 35         try {
 36             //保存pdf文件的全路径
 37             String filePath ="./pdf-file/test.pdf";
 38             //获取文件加路径
 39             String folderPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
 40             //创建pdf文件对象
 41             File folder = new File(folderPath);
 42             if (!folder.exists()) {
 43                 folder.mkdirs();
 44             }
 45             //创建pdf读写器
 46             PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
 47             writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
 48             //设置字体
 49             Font yahei9px  = CreatePDFUtil.getChineseFont(9);
 50             Font yahei10px = CreatePDFUtil.getChineseFont(10);
 51             Font yahei11px = CreatePDFUtil.getChineseFont(11);
 52             Font yahei12px = CreatePDFUtil.getChineseFont(12);
 53             //设置页眉-页脚
 54             document.setHeader(CreatePDFUtil.getPagerHeader("这仅仅是页眉,页码在页脚处",yahei9px));            
 55             document.setFooter(CreatePDFUtil.getPagerFooter(yahei9px));
 56             //打开pdf文档-开始编辑
 57             document.open();
 58             //创建单元格
 59             document.add(CreatePDFUtil.paragraph("制单时间:2018/09/14 17:04:23", yahei9px, Paragraph.ALIGN_RIGHT));
 60             //创建表格
 61             //把表格压入pdf对象:汇总
 62             document.add(createTable());
 63            // document.add(creatDetailTable(8,new float[]{0.15f,0.15f,0.15f,0.15f,0.15f,0.15f,0.15f,0.15f}));
 64             //创建段落
 65            // document.add(CreatePDFUtil.paragraph("***the first paragraph***", yahei9px));
 66             //创建段落
 67            // document.add(CreatePDFUtil.paragraph("***the second paragraph***", yahei12px, Paragraph.ALIGN_LEFT, 10.0f));
 68             //创建段落
 69            // document.add(CreatePDFUtil.paragraph("***the third paragraph***", yahei10px, Paragraph.ALIGN_LEFT, 5.0f));
 70             //创建短语块
 71            // document.add(new Phrase("短语1", yahei10px));
 72            // Phrase p2=new Phrase("短语2", yahei12px);
 73            // document.add(p2);
 74             
 75             //加盖图片
 76            // CreatePDFUtil.creatImage(writer,rectPageSize);
 77             //关闭pdf文档编辑
 78             document.close();
 79             //关闭pdf读写器对象
 80             writer.close();
 81             System.out.println("pdf已生成");
 82         } catch (FileNotFoundException e) {
 83             System.out.println("FileNotFoundException:"+e.getMessage());
 84         } catch (IOException e) {
 85             System.out.println("IOException:"+e.getMessage());
 86         } catch (DocumentException e) {
 87             System.out.println("DocumentException:"+e.getMessage());
 88         }
 89     }
 90     public static PdfPTable createTable() throws DocumentException, IOException{
 91          Font yahei9px  = CreatePDFUtil.getChineseFont(9);
 92          Font yahei10px = CreatePDFUtil.getChineseFont(10);
 93          Font yahei11px = CreatePDFUtil.getChineseFont(11);
 94          Font yahei12px = CreatePDFUtil.getChineseFont(12);
 95         PdfPTable table = new PdfPTable(3);
 96         table.setSpacingBefore(10.0f);//距上边距
 97         table.setWidthPercentage(100);//矩形框的宽度
 98         table.setWidths(new float[]{0.25f, 0.25f, 0.5f});//列宽数组
 99         //创建单元格:1
100         PdfPCell cell = CreatePDFUtil.cell("跨行批量转账电子回单", yahei11px, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);
101         cell.setColspan(3);//设置跨列
102         cell.setBackgroundColor(Color.lightGray);
103         table.addCell(cell);
104 
105         cell = CreatePDFUtil.cell("付款信息", yahei10px);
106         cell.setRowspan(3);//设置跨行
107         table.addCell(cell);
108         table.addCell(CreatePDFUtil.cell("付款人", yahei10px));
109         table.addCell(CreatePDFUtil.cell("不会浅水", yahei10px));
110         table.addCell(CreatePDFUtil.cell("付款账号", yahei10px));
111         table.addCell(CreatePDFUtil.cell("62122619100451863", yahei10px));
112         table.addCell(CreatePDFUtil.cell("付款行", yahei10px));
113         table.addCell(CreatePDFUtil.cell("云南红塔银行", yahei10px));
114 
115         cell = CreatePDFUtil.cell("汇总信息", yahei10px);
116         cell.setRowspan(3);//设置跨行
117         table.addCell(cell);
118         table.addCell(CreatePDFUtil.cell("总金额", yahei10px));
119         table.addCell(CreatePDFUtil.cell("153,685.00", yahei10px));
120         table.addCell(CreatePDFUtil.cell("总笔数", yahei10px));
121         table.addCell(CreatePDFUtil.cell("6", yahei10px));
122         table.addCell(CreatePDFUtil.cell("交易状态", yahei10px));
123         table.addCell(CreatePDFUtil.cell("部分成功", yahei10px));
124         return table;
125     }
126     public static PdfPTable creatDetailTable(int colCount,float[] wf) throws DocumentException, IOException{
127          Font yahei9px  = CreatePDFUtil.getChineseFont(8);
128          Font yahei10px = CreatePDFUtil.getChineseFont(10);
129          Font yahei11px = CreatePDFUtil.getChineseFont(11);
130          Font yahei12px = CreatePDFUtil.getChineseFont(12);
131          PdfPTable table = new PdfPTable(colCount);
132          table.setSpacingBefore(10.0f);//距上边距
133          table.setWidthPercentage(100);//矩形框的宽度
134          table.setWidths(wf);//列宽数组
135 
136 
137          PdfPCell cell = CreatePDFUtil.cell("跨行批量转账明细信息", yahei11px, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);
138          cell.setColspan(8);//设置跨列
139          cell.setBackgroundColor(Color.lightGray);
140          table.addCell(cell);
141          //开始生成数据
142          table.addCell(CreatePDFUtil.cell("流水号", yahei10px));
143          table.addCell(CreatePDFUtil.cell("付款账号", yahei10px));
144          table.addCell(CreatePDFUtil.cell("付款户名", yahei10px));
145          table.addCell(CreatePDFUtil.cell("收款账号", yahei10px));
146          table.addCell(CreatePDFUtil.cell("收款户名", yahei10px));
147          table.addCell(CreatePDFUtil.cell("金额", yahei10px));
148          table.addCell(CreatePDFUtil.cell("交易日期", yahei10px));
149          table.addCell(CreatePDFUtil.cell("交易状态", yahei10px));
150          
151          for(int i=0;i<10;i++){
152              table.addCell(CreatePDFUtil.cell("24010010"+i, yahei9px));
153              table.addCell(CreatePDFUtil.cell("3412261910045163", yahei9px));
154              table.addCell(CreatePDFUtil.cell("张浩"+i, yahei9px));
155              table.addCell(CreatePDFUtil.cell("6231561552"+i, yahei9px));
156              table.addCell(CreatePDFUtil.cell("测试户名"+i, yahei9px));
157              table.addCell(CreatePDFUtil.cell("10"+i, yahei9px));
158              table.addCell(CreatePDFUtil.cell("2018/09/13 13:50:22", yahei9px));
159              table.addCell(CreatePDFUtil.cell("交易成功", yahei9px));
160          }         
161          return table;
162     }
163 }

生成效果:

简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件

简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件

二、如何合并多个PDF成一个PDF文件

   如何批量操作在一个PDF的一页中合并显示两个PDF的内容。

假设:

  有简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件四个pdf文件,且均只有一页的内容,如何将这个四个pdf的内容合并,合并要求:1.pdf和2.pdf的内容合并到一页,3.pdf和4.pdf内容合并到一页。

 

下面代码的思路:

  (1)先创建一个临时pdf文件(PDF_1.pdf),先把1.pdf合并进去。

       (2)再把2.pdf合并到PDF_1.pdf中。

       (3)先创建一个临时pdf文件(PDF_2.pdf),先把3.pdf合并进去。

       (4)再把3.pdf合并到PDF_2.pdf中。

       (5)以此类推......

  (6)最后一步:合并上述所有临时pdf文件:PDF_1.pdf、PDF_2.pdf ........生成merger.pdf文件

直接贴出代码:

  1 package com.jason.test;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.File;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.nio.ByteBuffer;
  9 import java.nio.channels.FileChannel;
 10 import java.util.HashMap;
 11 import java.util.Map;
 12 
 13 import org.apache.pdfbox.multipdf.Overlay;
 14 import org.apache.pdfbox.multipdf.PDFMergerUtility;
 15 import org.apache.pdfbox.pdmodel.PDDocument;
 16 import org.apache.pdfbox.pdmodel.PDPage;
 17 import org.apache.pdfbox.pdmodel.common.PDRectangle;
 18 import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
 19 import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageXYZDestination;
 20 
 21 import com.lowagie.text.Document;
 22 import com.lowagie.text.DocumentException;
 23 import com.lowagie.text.PageSize;
 24 import com.lowagie.text.Paragraph;
 25 import com.lowagie.text.Rectangle;
 26 import com.lowagie.text.pdf.PdfWriter;
 27 
 28 public class Test4 {
 29     public static void main(String[] args) throws DocumentException, IOException {
 30         //参数准备
 31         String[] filePaths=getFiles("./test");//new String[]{"./pdf-file/test.pdf","./pdf-file/test2.pdf","./pdf-file/test3.pdf","./pdf-file/test3.pdf","./pdf-file/test3.pdf"};//,"./pdf-file/test2.pdf","./pdf-file/test3.pdf"
 32         String finlFile="./final/merger.pdf"; 
 33         //第二步:以上述pdf为基准,压入新的pdf文件
 34         int count=0;
 35         String saveFile=null;
 36         Overlay overLay=null;
 37         for(int i=0;i<filePaths.length;i++){
 38             //pdf文件个数>=2
 39             if(i%2==1){
 40                     saveFile="./dest/result"+count+".pdf";
 41                     creatNewPage(saveFile,1);
 42                     System.out.println("i="+i);
 43                     int index=0;
 44                     for(int j=i-1;j<=i;j++,index++){
 45                         //第一步:根据pdf文件个数,生成一个新的pdf
 46                         overLay = new Overlay();    
 47                         //1-基准
 48                         PDDocument _documentBase = PDDocument.load(new File(saveFile));
 49                         PDPage _pageBase = _documentBase.getPage(0);
 50                         PDRectangle _cropBoxBase = _pageBase.getCropBox();
 51                         float originalHeight = _cropBoxBase.getHeight();
 52                         _cropBoxBase.setLowerLeftY(-(PDRectangle.A4.getHeight() - _cropBoxBase.getHeight()));
 53                         _pageBase.setMediaBox(_cropBoxBase);
 54                         _pageBase.setCropBox(_cropBoxBase);
 55                         ByteArrayOutputStream _baosBase = new ByteArrayOutputStream();
 56                         _documentBase.save(_baosBase);
 57                         _documentBase.close();
 58                         overLay.setInputPDF(PDDocument.load(_baosBase.toByteArray()));
 59                         //2-上部分       
 60                          PDDocument _documentEach = PDDocument.load(new File(filePaths[j]));
 61                          PDPage _pageEach = _documentEach.getPage(0);
 62                          PDRectangle _cropBoxEach = _pageEach.getCropBox();
 63                          _pageEach.setMediaBox(_cropBoxEach);
 64                          _pageEach.setCropBox(_cropBoxEach);
 65                          //定位设置
 66                          _cropBoxEach.setLowerLeftY(-(PDRectangle.A4.getHeight() - _cropBoxEach.getHeight())-800*(index));//上(+)下(-)位置
 67                          ByteArrayOutputStream _baosEach = new ByteArrayOutputStream();
 68                          _documentEach.save(_baosEach);
 69                          _documentEach.close();
 70                          overLay.setDefaultOverlayPDF(PDDocument.load(_baosEach.toByteArray()));
 71                        //最后一步:开始合成    
 72                           Map<Integer, String> specificPageOverlayFile = new HashMap<Integer, String>();
 73                           PDDocument _doc = overLay.overlay(specificPageOverlayFile);
 74                           PDPageXYZDestination dest2 = new PDPageXYZDestination();
 75                           dest2.setPage(_doc.getPage(0));
 76                           dest2.setZoom(1f);
 77                           dest2.setTop(new Float(PDRectangle.A4.getHeight()).intValue());
 78                           PDActionGoTo action2 = new PDActionGoTo();
 79                           action2.setDestination(dest2);
 80                           _doc.getDocumentCatalog().setOpenAction(action2);
 81                           _doc.save(saveFile);
 82                     }
 83             }else if(i>=(filePaths.length/2*2)){//pdf文件个数为奇数个
 84                 saveFile="./dest/result"+count+".pdf";
 85                 creatNewPage(saveFile,1);
 86                 //第一步:根据pdf文件个数,生成一个新的pdf
 87                 overLay = new Overlay();    
 88                 //1-基准
 89                 PDDocument _documentBase = PDDocument.load(new File(saveFile));
 90                 PDPage _pageBase = _documentBase.getPage(0);
 91                 PDRectangle _cropBoxBase = _pageBase.getCropBox();
 92                 float originalHeight = _cropBoxBase.getHeight();
 93                 _cropBoxBase.setLowerLeftY(-(PDRectangle.A4.getHeight() - _cropBoxBase.getHeight()));
 94                 _pageBase.setMediaBox(_cropBoxBase);
 95                 _pageBase.setCropBox(_cropBoxBase);
 96                 ByteArrayOutputStream _baosBase = new ByteArrayOutputStream();
 97                 _documentBase.save(_baosBase);
 98                 _documentBase.close();
 99                 overLay.setInputPDF(PDDocument.load(_baosBase.toByteArray()));
100                 //2-上部分       
101                  PDDocument _documentEach = PDDocument.load(new File(filePaths[i]));
102                  PDPage _pageEach = _documentEach.getPage(0);
103                  PDRectangle _cropBoxEach = _pageEach.getCropBox();
104                  _pageEach.setMediaBox(_cropBoxEach);
105                  _pageEach.setCropBox(_cropBoxEach);
106                  //定位设置
107                  _cropBoxEach.setLowerLeftY(-(PDRectangle.A4.getHeight() - _cropBoxEach.getHeight()));//上(+)下(-)位置
108                  ByteArrayOutputStream _baosEach = new ByteArrayOutputStream();
109                  _documentEach.save(_baosEach);
110                  _documentEach.close();
111                  overLay.setDefaultOverlayPDF(PDDocument.load(_baosEach.toByteArray()));
112                //最后一步:开始合成    
113                   Map<Integer, String> specificPageOverlayFile = new HashMap<Integer, String>();
114                   PDDocument _doc = overLay.overlay(specificPageOverlayFile);
115                   PDPageXYZDestination dest2 = new PDPageXYZDestination();
116                   dest2.setPage(_doc.getPage(0));
117                   dest2.setZoom(1f);
118                   dest2.setTop(new Float(PDRectangle.A4.getHeight()).intValue());
119                   PDActionGoTo action2 = new PDActionGoTo();
120                   action2.setDestination(dest2);
121                   _doc.getDocumentCatalog().setOpenAction(action2);
122                   _doc.save(saveFile);
123                   System.out.println("pdf-file has created successfully!");
124             }
125             count++;               
126         }
127         //开始合并处理
128         PDFMergerUtility merger=new PDFMergerUtility();
129         String folder="./dest";
130         String[] fileInFolder=getFiles(folder);
131         for(int i=0;i<fileInFolder.length;i++){
132             merger.addSource(fileInFolder[i]);
133         }
134         merger.setDestinationFileName(finlFile);
135             merger.mergeDocuments();
136         System.out.println("pdf合并完成");
137         //删除临时文件:运维人员定期删除临时文件        
138     }
139     /**
140      * 获取指定文件夹下的所有文件列表
141      * @param folder
142      * @return
143      * @throws IOException
144      */
145     private static String[] getFiles(String folder) throws IOException {        
146         File _folder=new File(folder);
147         String[] filesInFolder;
148         if(_folder.isDirectory()){
149             filesInFolder=_folder.list();
150             String[] retS=new String[filesInFolder.length];
151             for(int i=0;i<filesInFolder.length;i++){
152                 retS[i]=folder+File.separator+filesInFolder[i];
153             }
154             return retS;
155         }else{
156             throw new IOException("Path is not directory!");
157         }
158     }
159     /**
160      * 生产指定页数的pdf文件
161      * @param saveFile
162      * @param pageSize
163      * @throws DocumentException
164      * @throws IOException
165      */
166     public static void creatNewPage(String saveFile,int pageSize) throws DocumentException, IOException{
167         FileOutputStream out = new FileOutputStream(saveFile);
168         Rectangle rectPageSize = new Rectangle(PageSize.A4.getWidth(),PDRectangle.A4.getHeight() );// A4纸张:PageSize.A4
169         Document document = new Document(rectPageSize, 10, 10, 10, 10);// 上、下、左、右间距          
170         PdfWriter.getInstance(document, out);        
171         if(document.getPageNumber()>=1){
172             document.open(); 
173             for(int i=0;i<pageSize;i++){
174                 document.newPage();  
175                 document.add(new Paragraph(".")); 
176             }           
177             document.close();  
178         }else{
179             document.open(); 
180             document.newPage();  
181             document.add(new Paragraph("."));
182             System.out.println("create the  first page!");
183             document.close();  
184         }        
185     }
186 }

合并效果:

第一页:

简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件

第二页:

简单测试Demo:如何用Java生成PDF,如何合并多个PDF成一个PDF文件