使用 java 使用 iText 将多个图像添加到单个 pdf 文件中

Add multiple images into a single pdf file with iText using java

我有以下代码,但此代码仅将最后一张图片添加到 pdf 中。

    try {
        filePath = (filePath != null && filePath.endsWith(".pdf")) ? filePath
                : filePath + ".pdf";
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filePath));
        document.open();    
        // document.add(new Paragraph("Image Example"));
        for (String imageIpath : imagePathsList) {

            // Add Image
            Image image1 = Image.getInstance(imageIpath);
            // Fixed Positioning
            image1.setAbsolutePosition(10f, 10f);
            // Scale to new height and new width of image
            image1.scaleAbsolute(600, 800);
            // image1.scalePercent(0.5f);
            // Add to document
            document.add(image1);
            //document.bottom();


        }
        writer.close();

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

你能给我一个关于如何更新代码以便将所有图像添加到导出的 pdf 中的提示吗? imagePathsList 包含我想添加到单个 pdf 中的所有图像路径。

此致, 奥勒良

看一下 MultipleImages 示例,您会发现代码中有两个错误:

  1. 您创建了一个大小为 595 x 842 用户单位的页面,并且无论图像的尺寸如何,您都将每个图像添加到该页面。
  2. 您声称只添加了一张图片,但事实并非如此。您正在 同一页面 上添加所有 个图像彼此。最后一张图片覆盖了前面的所有图片。

看看我的代码:

public void createPdf(String dest) throws IOException, DocumentException {
    Image img = Image.getInstance(IMAGES[0]);
    Document document = new Document(img);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    for (String image : IMAGES) {
        img = Image.getInstance(image);
        document.setPageSize(img);
        document.newPage();
        img.setAbsolutePosition(0, 0);
        document.add(img);
    }
    document.close();
}

我使用第一张图片的大小创建了一个 Document 实例。然后我遍历图像数组,将下一页的页面大小设置为每个图像的大小 before 我触发 newPage() [*] 。然后我在坐标 0, 0 添加图像,因为现在图像的大小将匹配每个页面的大小。

[*] newPage() 方法仅在向当前页面添加内容时才有效。第一次执行循环时,尚未添加任何内容,因此什么也不会发生。这就是为什么您需要在创建 Document 实例时将页面大小设置为第一张图像的大小。

Android 具有 "PdfDocument" 功能来实现此目的,

class Main2Activity : AppCompatActivity() {

private var imgFiles: Array<File?>? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)

    imgFiles= arrayOfNulls(2)

    imgFiles!![0] = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/doc1.png")
    imgFiles!![1] = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/doc3.png")



    val file = getOutputFile(File(Environment.getExternalStorageDirectory().absolutePath)
            , "/output.pdf")

    val fOut = FileOutputStream(file)
    val document = PdfDocument()

    var i = 0
    imgFiles?.forEach {
        i++
        val bitmap = BitmapFactory.decodeFile(it?.path)
        val pageInfo = PdfDocument.PageInfo.Builder(bitmap.width, bitmap.height, i).create()
        val page = document.startPage(pageInfo)
        val canvas = page?.canvas
        val paint = Paint()
        canvas?.drawPaint(paint)
        paint.color = Color.BLUE;
        canvas?.drawBitmap(bitmap, 0f, 0f, null)
        document.finishPage(page)
        bitmap.recycle()
    }
    document.writeTo(fOut)
    document.close()        

}

private fun getOutputFile(path: File, fileName: String): File? {
    if (!path.exists()) {
        path.mkdirs()
    }
    val file = File(path, fileName)
    try {
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()

    } catch (e: Exception) {
        e.printStackTrace()
    }
    return file
}

}

终于在清单中启用了存储权限,这应该可以了