java 將pdf多頁轉換成一張圖片,支援指定頁數

來源:互聯網
上載者:User

標籤:圖片   pdf   pdf轉圖片   java   

代碼:

/** * 將pdf中的maxPage頁,轉換成一張圖片 *  * @param pdfFile *            pdf的路徑 * @param outpath *            輸出的圖片的路徑[包括名稱] * @param maxPage *            pdf的頁數 *            【比如Pdf有3頁,如果maxPage=2,則將pdf中的前2頁轉成圖片,如果超過pdf實際頁數,則按實際頁數轉換】 */private static void pdf2multiImage(String pdfFile, String outpath, int maxPage) {try {InputStream is = new FileInputStream(pdfFile);PDDocument pdf = PDDocument.load(is, true);List<PDPage> pages = pdf.getDocumentCatalog().getAllPages();List<BufferedImage> piclist = new ArrayList<BufferedImage>();int actSize = pages.size(); // pdf中實際的頁數if (actSize < maxPage) maxPage = actSize;for (int i = 0; i < maxPage; i++) {piclist.add(pages.get(i).convertToImage());}yPic(piclist, outpath);is.close();} catch (IOException e) {e.printStackTrace();}}/** * 將寬度相同的圖片,豎向追加在一起 ##注意:寬度必須相同 *  * @param piclist *            檔案流數組 * @param outPath *            輸出路徑 */public static void yPic(List<BufferedImage> piclist, String outPath) {// 縱向處理圖片if (piclist == null || piclist.size() <= 0) {System.out.println("圖片數組為空白!");return;}try {int height = 0, // 總高度width = 0, // 總寬度_height = 0, // 臨時的高度 , 或儲存位移高度__height = 0, // 臨時的高度,主要儲存每個高度picNum = piclist.size();// 圖片的數量File fileImg = null; // 儲存讀取出的圖片int[] heightArray = new int[picNum]; // 儲存每個檔案的高度BufferedImage buffer = null; // 儲存圖片流List<int[]> imgRGB = new ArrayList<int[]>(); // 儲存所有的圖片的RGBint[] _imgRGB; // 儲存一張圖片中的RGB資料for (int i = 0; i < picNum; i++) {buffer = piclist.get(i);heightArray[i] = _height = buffer.getHeight();// 圖片高度if (i == 0) {width = buffer.getWidth();// 圖片寬度}height += _height; // 擷取總高度_imgRGB = new int[width * _height];// 從圖片中讀取RGB_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);imgRGB.add(_imgRGB);}_height = 0; // 設定位移高度為0// 產生新圖片BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int i = 0; i < picNum; i++) {__height = heightArray[i];if (i != 0) _height += __height; // 計算位移高度imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 寫入流中}File outFile = new File(outPath);ImageIO.write(imageResult, "jpg", outFile);// 寫圖片} catch (Exception e) {e.printStackTrace();}}


調用:
public static void main(String[] args) {pdf2multiImage("f:/bak/aa.pdf", "f:/bak/bbbbb.jpg", 4);}

轉換圖片,需要兩個jar包:commons-logging.jar
pdfbox-1.6.0.jar

java 將pdf多頁轉換成一張圖片,支援指定頁數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.