You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用lowagie itext将多页TIFF文档转换为PDF

使用iText 2.1.7(Lowagie)将多页TIFF转换为PDF

1. 引入依赖

如果使用Maven,在pom.xml中添加以下依赖:

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
</dependency>

手动导入的话,直接下载iText 2.1.7的jar文件引入项目即可。

2. 核心实现代码

以下是完整的转换逻辑,包含多页TIFF读取、PDF生成的完整流程:

import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.codec.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;

import java.io.FileOutputStream;
import java.io.IOException;

public class TiffToPdfConverter {
    public static void main(String[] args) {
        String tiffFilePath = "input.tif";
        String pdfFilePath = "output.pdf";

        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));
            document.open();

            // 读取多页TIFF文件
            RandomAccessFileOrArray tiffFile = new RandomAccessFileOrArray(tiffFilePath);
            int totalPages = TiffImage.getNumberOfPages(tiffFile);

            // 循环处理每一页
            for (int pageNum = 1; pageNum <= totalPages; pageNum++) {
                Image tiffPage = TiffImage.getTiffImage(tiffFile, pageNum);
                if (tiffPage != null) {
                    // 匹配PDF页面尺寸与TIFF页尺寸
                    document.setPageSize(new com.lowagie.text.Rectangle(tiffPage.getWidth(), tiffPage.getHeight()));
                    document.newPage();
                    document.add(tiffPage);
                }
            }

            tiffFile.close();
        } catch (IOException | com.lowagie.text.DocumentException e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen()) {
                document.close();
            }
        }
    }
}

3. 关键细节说明

  • 多页TIFF处理:借助RandomAccessFileOrArray高效读取TIFF文件,通过TiffImage.getNumberOfPages获取总页数,循环遍历每一页内容。
  • 页面尺寸适配:默认PDF页面为A4,通过document.setPageSize将页面尺寸设置为当前TIFF页的宽高,避免图片缩放、变形。
  • 资源回收:在finally块中确保Document关闭,避免资源泄漏。

内容的提问来源于stack exchange,提问作者Timothy Noon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:57:05