Java 圖片生成PDF
阿新 • • 發佈:2021-06-17
public static void main(String[] args) { String imageFolderPath = "E:\\Tencet\\圖片\\test\\"; try { //pdfPath 生成的PDF地址 預設在使用者選擇的目錄下 String pdfPath = imageFolderPath + System.nanoTime() + ".pdf"; File file = new File(imageFolderPath); File[] files = file.listFiles(); if (files == null || files.length == 0) { return; } // 根據名稱排序 sort(files); String imagePath; FileOutputStream fos = new FileOutputStream(pdfPath); // 建立文件 Document doc = new Document(null, 0, 0, 0, 0); // 寫入PDF文件 PdfWriter.getInstance(doc, fos); // 讀取圖片流 BufferedImage img; // 例項化圖片 Image image; // 迴圈獲取圖片資料夾內的圖片 for (File file1 : files) { if (file1.getName().endsWith(".jpg") || file1.getName().endsWith(".png") || file1.getName().endsWith(".jpeg") || file1.getName().endsWith(".tif") || file1.getName().endsWith(".gif")) { imagePath = imageFolderPath + "/" + file1.getName(); // 讀取圖片流 img = ImageIO.read(new File(imagePath)); // 根據圖片大小設定文件大小 doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); // 例項化圖片 image = Image.getInstance(imagePath); // 新增圖片到文件 doc.open(); doc.add(image); } } // 關閉文件 doc.close(); fos.close(); } catch (IOException | DocumentException e) { e.printStackTrace(); } }