记录只为自己以后方便查找。
转载参考 pdf合并:http://www.cnblogs.com/MoreThinking/archive/2017/07/27/7245433.html
图片转pdf : http://blog.csdn.net/haunghui6579/article/details/8900987
itext生成pdf:http://www.cnblogs.com/dengjiali/articles/2521301.html
itextpdf将图片转成pdf:
引用maven依赖:
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.12</version>
</dependency>
public String index3() { try { String imagePath = "D:/5.jpg"; String pdfPath = "D:/test.pdf"; BufferedImage img = ImageIO.read(new File(imagePath)); FileOutputStream fos = new FileOutputStream(pdfPath); Document doc = new Document(null, 0, 0, 0, 0); doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); Image image = Image.getInstance(imagePath); PdfWriter.getInstance(doc, fos); doc.open(); doc.add(image); doc.close(); } catch (IOException e) { e.printStackTrace(); } catch (BadElementException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return "index3"; }
pdfbox将多张pdf合成一张
引用maven依赖
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.5</version> </dependency>
public String index4() throws Exception { //pdf合并工具类 PDFMergerUtility mergePdf = new PDFMergerUtility(); String folder = "D:/testfile"; String destinationFileName = "mergedTest.pdf"; String[] filesInFolder = getFiles(folder); for(int i = 0; i < filesInFolder.length; i++){ //循环添加要合并的pdf存放的路径 //File.separatorChar 与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\'。 mergePdf.addSource(folder + File.separatorChar + filesInFolder[i]); } //设置合并生成pdf文件名称 mergePdf.setDestinationFileName(folder + File.separator + destinationFileName); //合并pdf mergePdf.mergeDocuments(); return "index4"; } private String[] getFiles(String folder) throws IOException { //获取文件夹下的全部文件 File _folder = new File(folder); String[] filesInFolder; if(_folder.isDirectory()){ filesInFolder = _folder.list(); return filesInFolder; } else { throw new IOException("Path is not a directory"); } }