如何在创建 pdf 时在图像之间添加 space - Android

How to add space between images while creating pdf - Android

我的应用程序使用用户选择的图像并使用 itextpdf 从中创建 PDF。

正在成功创建 PDF,但图像之间没有 space

例如

我的代码

public void createPdf(String dest) throws IOException, DocumentException {
    Image img = Image.getInstance(allSelectedImages.get(0).getPath());
    Document document = new Document(img);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    for (Uri image : allSelectedImages) {
        img = Image.getInstance(image.getPath());
        document.newPage();
        document.setMargins(100, 100, 100, 100);
        img.setAbsolutePosition(0, 0);
        document.add(img);
    }
    document.close();
}

您每页添加一张图片,因此图片之间的 space 相当于页面之间的 space,这由您的 PDF 查看器决定。

您可以做的是在图像周围添加一些边距 - 这是您已经在尝试做的事情,但有些事情需要修复。

这是一个示例,说明如何调整您的代码以在页面的所有边添加 100pt 边距(请注意,我正在动态计算页面大小,以便页面大小适应图像大小,以防图像不同尺寸):

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("path/to.pdf"));
document.open();
for (File image : allSelectedImages) {
    Image img = Image.getInstance(image.getPath());
    float leftMargin = 100;
    float rightMargin = 100;
    float topMargin = 100;
    float bottomMargin = 100;
    document.setPageSize(new Rectangle(img.getWidth() + leftMargin + rightMargin, img.getHeight() + topMargin + bottomMargin));
    document.newPage();
    document.setMargins(leftMargin, rightMargin, topMargin, bottomMargin);
    img.setAbsolutePosition(leftMargin, bottomMargin);
    document.add(img);
}