天天看点

使用itextpdf切割、合并pdf以及合并多个图片成为pdf使用itextpdf切割、合并pdf以及合并多个图片成为pdf

使用itextpdf切割、合并pdf以及合并多个图片成为pdf

按页切割PDF文件

import java.util.List;
import java.util.Map;

/**
 * 切割接口(由于在我们的项目中不止需要切割PDF,还有其他ppt、word等文件的切割,所以此处给定了一个接口,无需其他文件类型的可不使用此接口)
 */
public interface ISplit {
    List<Map<String, String>> split(String filePath) throws Exception;
}

           
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 切割pdf文件
 */
@Log4j2
@Component
public class SplitPdf implements ISplit {

    //文件路径前缀
    @Value("${filePathPrefix}")
    private String filePathPrefix;
    //远程文件访问域名
    @Value("${resources.domain}")
    private String resourcesDomain;

    @Autowired
    public SplitPdf(PptServiceClient pptServiceClient, FileServiceClient fileServiceClient) {
        this.pptServiceClient = pptServiceClient;
        this.fileServiceClient = fileServiceClient;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, String>> split(String filePath) throws Exception {
        List<Map<String, String>> mapList = new ArrayList<>();
        Document document = null;
        PdfCopy copy = null;
        //这里是远程文件,所以用的new URL,本地文件可以直接传入路径
        PdfReader reader = new PdfReader(new URL(resourcesDomain + filePath));
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            String perPagePath = splitPage(reader, filePathPrefix + filePath, i, i);
            HashMap<String, String> map = new HashMap<>();
            //FileTypeEnum是文件类型枚举,可自己实现
            map.put(FileTypeEnum.PDF.getType().toLowerCase(), perPagePath);
            mapList.add(map);
        }
        //返回值可自己指定,此处是本人项目需要
        return mapList;
    }

    private String splitPage(PdfReader reader, String filePath, Integer from, Integer end) throws DocumentException, IOException {
    	//创建文件夹路径(可自己实现)
        //FilePathUtil.mkDirsIfNotExists(filePath);
        Document document;
        PdfCopy copy;
        //此处是因为itextpdf在切割时是从1开始的
        if (from == 0) {
            from = 1;
        }
        int a = filePath.lastIndexOf("/");
        String staticPath = filePath.substring(0, a);
        String staticName = filePath.substring(a, filePath.lastIndexOf(".pdf"));

        String saveFileName = staticName + "_" + from + ".pdf";
        String saveFilePath = staticPath + saveFileName;
        document = new Document(reader.getPageSize(1));
        copy = new PdfCopy(document, new FileOutputStream(saveFilePath));
        document.open();
        for (int j = from; j <= end; j++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, j);
            copy.addPage(page);
        }
        document.close();
        return saveFilePath.substring(filePathPrefix.length());
    }
}

           

合并多个PDF文件

import java.util.List;

/**
 * 合并接口
 */
public interface IMerge {
    String merge(List<String> filePathList, String toPath);
}
           
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * 合并多个PDF
 */
@Log4j2
@Component
public class MergePdf implements IMerge {

    @Value("${filePathPrefix}")
    private String filePathPrefix;
    @Value("${resources.domain}")
    private String resourcesDomain;

    @Override
    public String merge(List<String> filePathList, String toPath) {

        try {
            Document document = new Document();
            if (toPath == null) {
                toPath = "/files/upload" + getFilePathByDate() + "/" + UUID.randomUUID().toString().replace("-", "") + ".pdf";
            }
            FilePathUtil.mkDirsIfNotExists(filePathPrefix + toPath);
            OutputStream bos = new FileOutputStream(filePathPrefix + toPath);
            PdfCopy copy = new PdfCopy(document, bos);
            document.open();
            for (String filePath : filePathList) {
                PdfReader reader = new PdfReader(new URL(resourcesDomain + filePath));
                copy.addDocument(reader);
                copy.freeReader(reader);
                reader.close();
            }
            document.close();
        } catch (DocumentException | IOException | ResponseException e) {
            log.error("合并PDF文件失败,msg={}", e.getMessage());
            return null;
        }
        return toPath;
    }

    private String getFilePathByDate() {
        Calendar calendar = Calendar.getInstance();
        return "/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1);
    }
}

           

合并多张图片到PDF文件

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * 合并图片成为PDF
 */
@Log4j2
@Component
public class MergePicture implements IMerge {
    @Value("${filePathPrefix}")
    private String filePathPrefix;
    @Value("${resources.domain}")
    private String resourcesDomain;


    @Override
    public String merge(List<String> filePathList, String toPath) {
        try {
            Document document = new Document();
            if (toPath == null) {
                toPath = "/files/upload" + getFilePathByDate() + "/" + UUID.randomUUID().toString().replace("-", "") + ".pdf";
            }
            FilePathUtil.mkDirsIfNotExists(filePathPrefix + toPath);
            OutputStream os = new FileOutputStream(filePathPrefix + toPath);

            PdfWriter.getInstance(document, os);
            document.open();

            for (String filePath : filePathList) {
                document.newPage();
                BufferedImage img = ImageIO.read(new URL(resourcesDomain + filePath));

                int width = img.getWidth();
                int height = img.getHeight();
                int percent = getPercent2(height, width);

                Image image = Image.getInstance(new URL(resourcesDomain + filePath));
                //设置图片居中
                image.setAlignment(Image.MIDDLE);
                //设置图片缩放百分比,表示显示的大小是原来图像的多少比例
                image.scalePercent(percent + 3);

                document.add(image);
            }

            document.close();
        } catch (IOException | DocumentException e) {
            log.error("合并图片失败,msg={}", e.getMessage());
            return null;
        }
        return toPath;
    }

    /**
     * 将每张图片统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
     */
    private int getPercent2(float h, float w) {
        int p;
        float p2;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

	/**
	* 此处为本人项目中设定的文件路径:格式为\files\upload\2022\6\
	*/
    private String getFilePathByDate() {
        Calendar calendar = Calendar.getInstance();
        return "/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1);
    }
}