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

使用iTextPDF库实现每张图片单独占一页的问题求助

iTextPDF库实现每张图片单独占一页的问题求助

老哥,我看你用iTextPDF做图片转PDF的功能,本来想每张图片单独占一页,但现在所有图都堆在第一页上了,我帮你瞅了瞅代码,发现问题所在啦!

先看你遇到的情况:你期望图片数量和PDF页数一致,但实际所有图片都叠在第一页,核心问题是你虽然循环创建了新页面,但没有把图片正确绑定到对应的新页面上。

先给你分析下代码里的问题点:

  • 循环变量写错了:函数参数是listOfURIs,但你循环里写的是for (uri in URIList),这明显是笔误,会导致没法正确遍历所有图片(如果这是你输入时的手滑,那重点看第二个问题)
  • 分页逻辑的核心问题:你每次循环都调用了pdfDocument.addNewPage(tamanio),但document.add(image)默认是往当前的页面(也就是第一页)添加内容,document并没有自动切换到你新创建的页面,所以所有图片都堆到第一页了。

下面是修改后的代码,我帮你调整了分页的逻辑,确保每张图片都能单独占一页:

private fun pdf(name: String, tamanio: PageSize, listOfURIs: List<Uri>) {

    Log.d("PDF", "PDF file name: ${getUniqueName(name)}")

    // Directory where the PDF file will be stored
    val outputPdfDir = documentsDirectory
    outputPdfDir.mkdirs()// Create the directory if it does not exist

    // Full path of the output PDF file
    val outputPdfFilePath = File(outputPdfDir, getUniqueName(name))
    Log.d("PDF", "Set output $outputPdfFilePath")

    // Create a new PDF document
    val pdfWriter = PdfWriter(outputPdfFilePath)
    val pdfDocument = PdfDocument(pdfWriter)
    pdfDocument.defaultPageSize = tamanio
    val document = Document(pdfDocument)

    // 修正循环变量,和函数参数保持一致
    for (uri in listOfURIs) {
        val bitmap = BitmapFactory.decodeFile(uri.path)
        // 增加空判断,避免图片解码失败导致崩溃
        if (bitmap == null) {
            Log.w("PDF", "没法解码这张图片:${uri.path}")
            continue
        }

        // Convert the image into a byte array
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
        val byteArray = byteArrayOutputStream.toByteArray()

        // Create an image from the byte array
        val imageData = ImageDataFactory.create(byteArray)
        val image = Image(imageData)

        // 添加新页面,并获取这个页面的引用
        val newPage = pdfDocument.addNewPage(tamanio)
        // 获取当前页面的Canvas,用来绘制内容
        val canvas = Canvas(newPage)

        // 把图片缩放到页面大小
        image.scaleToFit(newPage.pageSize.width, newPage.pageSize.height)
        // 设置图片位置为页面左上角
        image.setFixedPosition(0f, 0f)

        // 将图片添加到当前页面的Canvas上,这样就绑定到新页面了
        canvas.add(image)
    }

    //close the document
    document.close()

    // Display a success message
    Toast.makeText(this, "PDF创建成功啦", Toast.LENGTH_SHORT).show()
    Log.d("PDF", "PDF保存路径:${outputPdfFilePath.absolutePath}")

    // Navigate back to the main activity
    val intent = Intent(this, MainActivity::class.java)
    startActivity(intent)
    finish()
}

我主要做了这些修改:

  • 修正了循环变量的笔误,确保能遍历所有传入的图片
  • 增加了Bitmap的空判断,避免图片解码失败导致程序崩溃
  • 不再使用document.add(image),而是获取新创建页面的Canvas对象,把图片添加到这个Canvas上,这样每张图片都会和对应的新页面绑定,保证每张图单独占一页
  • 去掉了你原来代码里重复弹出的成功Toast,避免重复提示

这样修改后,你再运行应该就能实现每张图片单独占一页的效果啦!

备注:内容来源于stack exchange,提问作者Hugo Jiménez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 08:53:12