使用itextpdf 实现PDF合并

文章目录


前言

iTextPDF是一个用于处理PDF文档的Java库。它提供了一套强大的API,可以创建、编辑和操作PDF文档。iTextPDF可以用于生成PDF报告、填充PDF表单、添加水印、合并和拆分PDF文件等。它还支持字体嵌入、表格、图像和多种文本格式。iTextPDF是一个开源库,可以免费使用,同时也有商业版提供更多功能和支持。它被广泛应用于企业应用、电子商务、、教育、金融等领域

使用步骤 

  • 引入iText相关jar包

<!-- 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.itextpdf/itext-asian -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
<!--     https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.5.13</version>
    </dependency> 

  • 相关代码示例

  •  Util类

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author: youchao
 * @description:
 * @data: 2024/1/22 15:46
 **/
public class PdfUtils {
   

public static Document createDocument(HttpServletResponse response, String fileName) {
        try {
            response.reset();
            response.setHeader("Content-Type", "application/pdf-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置大小
        return new Document(PageSize.A4, 50, 50, 80, 50);
    }

   

public static void mergePdf(Document document, List<byte[]> byteList, String path) {
        try {
            FileOutputStream os = new FileOutputStream(path);

            // 以任意一个页面创建pdf模板
            document = new Document(PageSize.A4);

            PdfCopy copy = new PdfCopy(document, os);

            // 打开文档
            document.open();
            // 遍历pdf文件
            for (byte[] bytes : byteList) {
                // 读取pdf
                PdfReader reader = new PdfReader(bytes);

                // 获取页数
                int numberOfPages = reader.getNumberOfPages();
                // 从第一页开始
                for (int i = 1; i <= numberOfPages; i++) {
                    // 新建文档页
                    document.newPage();
                    // 复制操作
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("PDF合并失败!");
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

 private byte[] inputStreamToByte(InputStream inputStream) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("InputStream转换失败!");
        }
    } 

  • 业务代码示例 

  public String margeAll() throws Exception {

        // 加载本地文件 将需要合并的PDF文件放入集合中
        List<String> paths = new ArrayList<>();  

        FileInputStream inputStream = null;

        

        //将合并后的PDF所存在的路径 可以根据业务需求转化为输出流等等
        String pdfPath = null;

        try {
            // 判断文件是否合规、以及转化为输入流
            List<byte[]> byteList = new ArrayList<>();
            for (String path : paths) {
                File file = new File(path);
                // 限制格式只能为pdf
                if (!file.exists()) {
                    throw new RuntimeException("文件不存在!");
                }
                if (file.length() <= 0) {
                    throw new RuntimeException("文件不能为空!");
                }

                String name = file.getName();
                String substring = name.substring(name.lastIndexOf(".") + 1);
                if (!substring.equals("pdf")) {
                    throw new RuntimeException("只能上传pdf格式文件!");
                }

                // 获取输入流
                inputStream = new FileInputStream(file);
                byte[] bytes = inputStreamToByte(inputStream);
                byteList.add(bytes);
            }

           

             // 1.设置输出流名称 纸张大小
            Document document = new Document(PageSize.A4);

    

            // 2.开启合并
            PdfUtils.mergePdf(document, byteList, pdfPath);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return pdfPath;
    }

总结

        以上即是使用itextpdf 实现PDF合并简单实例代码 希望可以帮助到大家!!!

  • 40
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答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包中的类和方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AKYChao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值