0

I am using itext7 to create pdf file ,and at the footer I am trying to add png images as follows:

PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
PdfPage page = documentEvent.getPage();
PdfCanvas canvas = new PdfCanvas(page);
byte[] signature = null; // retrieved from database
PngImageData imageData = (PngImageData) ImageDataFactory.createPng(signature);
canvas.addImageAt(imageData, 5f, 25f, false);

the original image itself has good resolution, but when the image is added to the pdf it appears with poor quality although I am adding the image without any changes or scaling.

how can I improve the image quality in the final pdf ?

Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
  • Many times I had problem with PDF viewer that it create low quality image when rendering full page. Try zooming in in viewer and check if image looks better. If it does, then your issue is not in code. – Matjaz Nov 04 '20 at 09:15
  • zooming in doesn't make image look better, but copying the same image from pdf to windows paint programs makes it looks better ! – Mahmoud Saleh Nov 04 '20 at 09:47
  • Then it is issue with viewer, not in your code. I do not have any project with itext on this pc but if I remember correctly I use similar code as you do. – Matjaz Nov 04 '20 at 11:42
  • do you think maybe different image formats may look better in itext ? – Mahmoud Saleh Nov 04 '20 at 13:20

1 Answers1

0

This is snippet of my code for adding image to PDF:

PdfContentByte cbLogo = writer.getDirectContent();

if (instanceSettings.getDocumentHeaderImageLocation() != null) {
    try {
        String encodedString = instanceSettings.getDocumentHeaderImageLocation();
        byte[] decodedBytes = Base64
                .getDecoder()
                .decode(encodedString);
        Image imgLogo = Image.getInstance(decodedBytes);
        imgLogo.scaleToFit(220f, 150f);
        imgLogo.setAbsolutePosition((writer.getPageSize().getWidth() / 4) - (imgLogo.getScaledWidth() / 2),
                writer.getPageSize().getHeight() - imgLogo.getScaledHeight() - 30);
        cbLogo.addImage(imgLogo);
    } catch (Exception e){
        ErrorHandler.handle(e);
    }
}

And here is another:

    Image qr = Image.getInstance(file.getAbsolutePath());
    qr.scaleToFit(70f, 70f);
    qr.setSpacingBefore(0);
    qr.setSpacingAfter(0);
    qr.setPaddingTop(0);
    PdfPCell cell = new PdfPCell();
    cell.setPadding(0f);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    cell.addElement(qr);

Image is of type:

import com.itextpdf.text.Image;

You can give it a try with this code. For me, both works as expected but as I said in the comments, I sometimes have dificulties viewing it in PDF application. As far as I know, itext has nothing to do with it.

Matjaz
  • 468
  • 5
  • 21