Search code examples
javaandroidpdfitext

How to add space between images while creating pdf - Android


My app is using user-selected images and creating a PDF out of it using itextpdf.

It is successfully creating PDF but there is no space between images

Ex.

Screen Shot of the error

My Code

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

Solution

  • You are adding one image per page, so the space between images is equivalent to the space between pages which is determined by your PDF viewer.

    What you can do it adding some margins around your images - this is what you are trying to do already but there are some things that need to be fixed.

    Here is an example on how your code can be adapted to add 100pt margin for all sides of the page (note that I am calculating page sizes dynamically so that the page size adapts to the image size in case images are of different size):

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