PDFBox-Android添加图片被遮挡

使用pdfbox-android在已存在的pdf上面追加图片,需要先创建PDPageContentStream,在创建的时候需要注意设置模式为APPEND,并且将resetContext参数设置为true

val cs = PDPageContentStream(
                                        document,
                                        page,
                                        PDPageContentStream.AppendMode.APPEND,
                                        true, true
                                )

通过以上方式追加的图片能够正常显示。下面写一个完整的添加图片的示例,此处是创建新的pdf和页面:

try {
            // 根据pdf文件获取到的pdf的document
            PDDocument document = new PDDocument();

            // 创建一个新的页面
            PDPage page = new PDPage();
            document.addPage(page);

            // 将本地图片加载
           PDImageXObject bitmap= PDImageXObject.createFromFile("本地图片地址", document)

            // 创建一个内容流,用来添加图片
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // 设置坐标位置
            float x = 100; // example x coordinate
            float y = 500; // example y coordinate
            contentStream.drawImage(pdImage, x, y, pdImage.getWidth(), pdImage.getHeight());

            // 关闭并保存pdf文档
            contentStream.close();
            String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/output.pdf";
            File file = new File(filePath);
            document.save(file);

            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
posted @ 2024-03-05 16:10  乌拉小考  阅读(110)  评论(0编辑  收藏  举报