/** * 图片转换pdf(jpg,png等) * @param filePath * @param pdfPath * @throws IOException */ public static boolean Image2PDF(String filePath, String pdfPath) throws IOException { boolean bool=true; File file = new File(filePath); if (file.exists()) { Document document = new Document(); FileOutputStream fos = null; try { fos = new FileOutputStream(pdfPath); PdfWriter.getInstance(document, fos); document.setPageSize(PageSize.A4); document.open(); Image image = Image.getInstance(filePath); float imageHeight = image.getScaledHeight(); float imageWidth = image.getScaledWidth(); image.setAlignment(Image.ALIGN_CENTER); int percent = getPercent(imageHeight, imageWidth); image.scalePercent(percent); document.add(image); } catch (DocumentException de) { System.out.println(de.getMessage()); bool=false; return bool; } catch (IOException ioe) { System.out.println(ioe.getMessage()); bool=false; return bool; } document.close(); fos.flush(); fos.close(); } bool=false; return bool; }
/** * 图片倍率大小 a4 * @param h * @param w * @return */ public static int getPercent(float h, float w) { int p = 0; float p2 = 0.0f; if (h > w) { p2 = 297 / h * 274; } else { p2 = 210 / w * 268; } p = Math.round(p2); return p; }