使用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);
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 使用 itextpdf 合并图片生成 pdf 文件的步骤如下: 1. 导入 itextpdf 的 jar 包 2. 创建一个 Document 对象 3. 创建一个 PdfWriter 对象, 并将其与 Document 对象关联 4. 打开 Document 对象 5. 循环添加图片到 Document 对象中 6. 关闭 Document 对象 以下是一个示例代码: ```java import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfWriter; public class ImageToPdf { public static void main(String[] args) { // 创建一个 Document 对象 Document document = new Document(); try { // 创建一个 PdfWriter 对象, 并将其与 Document 对象关联 PdfWriter.getInstance(document, new FileOutputStream("images.pdf")); // 打开 Document 对象 document.open(); // 循环添加图片到 Document 对象中 for (int i = 1; i <= 3; i++) { // 创建图片对象 Image image = Image.getInstance("image" + i + ".jpg"); // 将图片添加到 Document 对象中 document.add(image); } } catch (DocumentException | IOException e) { e.printStackTrace(); } finally { // 关闭 Document 对象 document.close(); } } } ``` ### 回答2: 使用itextpdf合并多个图片生成pdf文件的步骤如下: 1. 导入itextpdf库:下载itextpdf库并将其添加到项目的类路径中。 2. 创建PdfDocument对象:使用PdfWriter类创建一个PdfDocument对象,这将用于保存和管理pdf文件。 3. 打开文档:使用PdfDocument对象的open方法打开文档,指定输出的文件路径。 4. 创建Document对象:创建一个Document对象,它是iText库中用于处理PDF文件中内容的主要类。 5. 逐个添加图片使用Image类加载每个要合并图片文件,并使用Document对象的add方法将其添加到文档中。 6. 关闭文档:使用PdfDocument对象的close方法关闭文档,确保将所有内容保存到pdf文件中。 下面是一个示例代码片段: ```java import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Image; import java.io.File; import java.io.IOException; public class ImageToPdfConverter { public static void convertToPdf(String[] imagePaths, String pdfPath) throws IOException { PdfWriter writer = new PdfWriter(pdfPath); PdfDocument pdfDocument = new PdfDocument(writer); Document document = new Document(pdfDocument); for (String imagePath : imagePaths) { Image image = new Image(ImageDataFactory.create(imagePath)); document.add(image); } document.close(); pdfDocument.close(); } public static void main(String[] args) throws IOException { String[] imagePaths = {"image1.jpg", "image2.jpg", "image3.jpg"}; String pdfPath = "output.pdf"; convertToPdf(imagePaths, pdfPath); } } ``` 在上述示例中,首先创建了PdfWriter和PdfDocument对象,然后创建了一个Document对象。接下来,使用Image类加载要合并的每个图片文件,并使用Document对象的add方法将其添加到文档中,然后关闭文档和PdfDocument对象,确保将内容保存到pdf文件中。最后,调用convertToPdf方法,传入图片文件路径数组和输出的pdf文件路径即可生成pdf文件。 ### 回答3: 使用iTextPDF库可以很方便地合并图片生成PDF文件。下面是使用iTextPDF合并图片生成PDF文件的步骤: 1.创建一个Document对象。用于存放合并后的PDF文件内容。 2.创建一个PdfWriter对象,并将Document对象与PdfWriter对象关联。 3.打开Document对象,可以使用document.open()方法。 4.创建一个Image对象,用于表示要合并图片。 5.将Image对象添加到Document对象中,可以使用document.add()方法。 6.循环以上步骤,将需要合并的所有图片都添加到Document对象中。 7.关闭Document对象,可以使用document.close()方法。 8.保存合并后的PDF文件,可以使用PdfWriter对象的close()方法。 下面是一个使用iTextPDF合并图片生成PDF文件的例子: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; import java.io.IOException; public class ImageToPdf { public static void main(String[] args) { String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg" }; String outputPath = "output.pdf"; try { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(outputPath)); document.open(); for (String imagePath : imagePaths) { Image image = Image.getInstance(imagePath); document.add(image); } document.close(); System.out.println("PDF file created successfully."); } catch (IOException | DocumentException e) { e.printStackTrace(); } } } ``` 在上面的例子中,我们创建了一个Document对象,并将其与PdfWriter对象关联。然后,我们循环遍历需要合并图片路径,创建Image对象,并将其添加到Document对象中。最后,我们关闭Document对象,并保存合并后的PDF文件。 需要注意的是,需要将iTextPDF库添加到项目的依赖中才能使用该库。在本例中,我们使用了com.itextpdf.text和com.itextpdf.text.pdf包中的类和方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值