生活随笔
收集整理的這篇文章主要介紹了
Java实现图片转PDF
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.導(dǎo)入依賴
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>com.itextpdf</groupId> ? ? ? ? ? ? <artifactId>itextpdf</artifactId> ? ? ? ? ? ? <version>5.5.13</version> ? ? ? ? </dependency> ? ? ? ? <!-- https://mvnrepository.com/artifact/com.lowagie/itext --> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>com.lowagie</groupId> ? ? ? ? ? ? <artifactId>itext</artifactId> ? ? ? ? ? ? <version>4.2.1</version> ? ? ? ? </dependency> |
2.實現(xiàn)圖片轉(zhuǎn)PDF的工具類
| package util; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.Image; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfWriter; public class PicToPdfUtil { ?? ?public static void convert(String source, String target) { ?? ??? ?Document document = new Document(); ?? ??? ?// 設(shè)置文檔頁邊距 ?? ??? ?document.setMargins(0, 0, 0, 0); ?? ??? ?FileOutputStream fos = null; ?? ??? ?try { ?? ??? ??? ?fos = new FileOutputStream(target); ?? ??? ??? ?PdfWriter.getInstance(document, fos); ?? ??? ??? ?// 打開文檔 ?? ??? ??? ?document.open(); ?? ??? ??? ?// 獲取圖片的寬高 ?? ??? ??? ?Image image = Image.getInstance(source); ?? ??? ??? ?float imageHeight = image.getScaledHeight(); ?? ??? ??? ?float imageWidth = image.getScaledWidth(); ?? ??? ??? ?// 設(shè)置頁面寬高與圖片一致 ?? ??? ??? ?Rectangle rectangle = new Rectangle(imageWidth, imageHeight); ?? ??? ??? ?document.setPageSize(rectangle); ?? ??? ??? ?// 圖片居中 ?? ??? ??? ?image.setAlignment(Image.ALIGN_CENTER); ?? ??? ??? ?// 新建一頁添加圖片 ?? ??? ??? ?document.newPage(); ?? ??? ??? ?document.add(image); ?? ??? ?} catch (Exception ioe) { ?? ??? ??? ?System.out.println(ioe.getMessage()); ?? ??? ?} finally { ?? ??? ??? ?// 關(guān)閉文檔 ?? ??? ??? ?document.close(); ?? ??? ??? ?try { ?? ??? ??? ??? ?fos.flush(); ?? ??? ??? ??? ?fos.close(); ?? ??? ??? ?} catch (IOException e) { ?? ??? ??? ??? ?e.printStackTrace(); ?? ??? ??? ?} ?? ??? ?} ?? ?} } ? |
3.測試
| public static void main(String[] args) {String source = "D:/image/車輛顏色.png";String target = "D:/aaa/1.pdf";convert(source, target);
} |
?
總結(jié)
以上是生活随笔為你收集整理的Java实现图片转PDF的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。