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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29331838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:04:31  来源:igfitidea点击:

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

javaimagepdfitext

提问by aurelianr

I have the following code but this code add only the last image into pdf.

我有以下代码,但此代码仅将最后一个图像添加到 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());
    }

Would you give me a hint about how to update the code in order to add all the images into the exported pdf? imagePathsList contains all the paths of images that that I want to add into a single pdf.

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

Best Regards, Aurelian

最好的问候,奥勒良

回答by Bruno Lowagie

Take a look at the MultipleImagesexample and you'll discover that there are two errors in your code:

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

  1. You create a page with size 595 x 842 user units, and you add every image to that page regardless of the dimensions of the image.
  2. You claim that only one image is added, but that's not true. You are adding allthe images on top of each otheron the same page. The last image covers all the preceding images.
  1. 您创建一个大小为 595 x 842 用户单位的页面,然后将每个图像添加到该页面,而不管图像的尺寸如何。
  2. 您声称只添加了一张图片,但事实并非如此。您正在同一页面上将所有图像叠加在一起。最后一张图片涵盖了所有前面的图片。

Take a look at my code:

看看我的代码:

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();
}

I create a Documentinstance using the size of the first image. I then loop over an array of images, setting the page size of the next page to the size of each image beforeI trigger a newPage()[*]. Then I add the image at coordinate 0, 0 because now the size of the image will match the size of each page.

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

[*]The newPage()method only has effect if something was added to the current page. The first time you go through the loop, nothing has been added yet, so nothing happens. This is why you need set the page size to the size of the first image when you create the Documentinstance.

[*]newPage()方法只有在当前页面添加了一些东西时才有效。第一次执行循环时,还没有添加任何内容,因此什么也没有发生。这就是为什么在创建Document实例时需要将页面大小设置为第一个图像的大小。

回答by Shyam Kumar

Android has the feature "PdfDocument" to achieve this,

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
}

}

}

finally enable the storage permission in manifest, this should works

最后在清单中启用存储权限,这应该有效