Search code examples
itextpdf-generationscaling

Scale image to fill multiple pages with iText


I am trying to scale an image with iText (on a new PDF document) in order to make it fill the width of the page without streching, so that it could take several pages.

I've found a lot of solutions but they were pretty complicated and I don't really like coding like that. The best solution I've found till now (from another question on SO) is using PdfTable but it always uses a single page, scaling the image.

// Load image from external storage
Image image = Image.getInstance(path + "/img.png");
// Calculate ratio
float width = PageSize.A4.getWidth();
float heightRatio = image.getHeight() * width / image.getWidth();
Document document = new Document();
document.open();
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100);
PdfPCell c = new PdfPCell(image, true);
c.setBorder(PdfPCell.NO_BORDER);
c.setPadding(0);
// Set image dimensions
c.getImage().scaleToFit(width, heightRatio);
table.addCell(c);
document.add(table);
// Write PDF file
document.close();

Any suggestions?


Solution

  • Ok I finally decided to go the way I didn't want to go, since it seems to be the only way: adding the same image to every page and setting the proper vertical offset to each one. The offset gets calculated as the number of pages left to draw + the gap the remains blank. For each step I decrement the number of pages until there's nothing left to draw.

    // Open new PDF file
    Document document = new Document();
    PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(getSharedDirPath() + File.separator + "file.pdf"));
    
    document.open();
    PdfContentByte content = pdfWriter.getDirectContent();
    
    // Load image from external folder
    Image image = Image.getInstance(path + "/img.png");
    image.scaleAbsolute(PageSize.A4);
    image.setAbsolutePosition(0, 0);
    
    float width = PageSize.A4.getWidth();
    float heightRatio = image.getHeight() * width / image.getWidth();
    int nPages = (int) (heightRatio / PageSize.A4.getHeight());
    float difference = heightRatio % PageSize.A4.getHeight();
    
    while (nPages >= 0) {
        document.newPage();
        content.addImage(image, width, 0, 0, heightRatio, 0, -((--nPages * PageSize.A4.getHeight()) + difference));
    }
    
    // Write PDF file
    document.close();
    

    Honestly I don't like this solution, I thought it was possible to auto-adjust dimensions as I do in a text editor, but after all it was not very difficult.....it just took me three days to figure out how the whole PDF thing worked.