Java多張圖片合成PDF


 

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;

/**
 * 圖片轉pdf工具類
 * 
 * @author Administrator
 *
 */
public class Img2PdfUtil {

    private static Logger logger = Logger.getLogger(Img2PdfUtil.class);

    /**
     * 
     * @param outPdfFilepath 生成pdf文件路徑
     * @param imageFiles 需要轉換的圖片File類Array,按array的順序合成圖片
     */
    public static void imagesToPdf(String outPdfFilepath, File[] imageFiles) throws Exception {

        logger.info("進入圖片合成PDF工具方法");

        File file = new File(outPdfFilepath);
        // 第一步:創建一個document對象。
        Document document = new Document();
        document.setMargins(0, 0, 0, 0);
        // 第二步:
        // 創建一個PdfWriter實例,
        PdfWriter.getInstance(document, new FileOutputStream(file));
        // 第三步:打開文檔。
        document.open();
        // 第四步:在文檔中增加圖片。
        int len = imageFiles.length;

        for (int i = 0; i < len; i++) {
            if (imageFiles[i].getName().toLowerCase().endsWith(".bmp")
                    || imageFiles[i].getName().toLowerCase().endsWith(".jpg")
                    || imageFiles[i].getName().toLowerCase().endsWith(".jpeg")
                    || imageFiles[i].getName().toLowerCase().endsWith(".gif")
                    || imageFiles[i].getName().toLowerCase().endsWith(".png")) {
                String temp = imageFiles[i].getAbsolutePath();
                logger.info("圖片路徑:"+temp);
                Image img = Image.getInstance(temp);
                img.setAlignment(Image.ALIGN_CENTER);
                img.scaleAbsolute(597, 844);// 直接設定顯示尺寸
                // 根據圖片大小設置頁面,一定要先設置頁面,再newPage(),否則無效
                //document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
                document.setPageSize(new Rectangle(597, 844));
                document.newPage();
                document.add(img);
            }
        }
        // 第五步:關閉文檔。
        document.close();
        logger.info("圖片合成PDF完成");
    }
    
    public static void main(String[] args) {
        String outPdfPath = "C:\\Users\\Administrator\\Desktop\\廣東\\需求\\20190104已確認需求\\Img2PdfTest\\Img2pdf.pdf";
        String imagesPath = "C:\\Users\\Administrator\\Desktop\\廣東\\需求\\20190104已確認需求\\Img2PdfTest";
        String[] imgNameArray = new String[] { "1_0.png", "1_1.png", "1_2.png", "1_3.png", "1_4.png", "1_5.png",
                "1_6.png", "1_7.png", "1_8.png", "1_9.png", "1_10.png", "1_11.png", };
        // imagesToPdf(outPdfPath, imagesPath, imgNameArray);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM