Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText : How does add image to top of PDF page

Tags:

java

itext

I going to convert tiff to pdf file, but image displayed bottom of page, how to start image from top of the pdf page.

private static String convertTiff2Pdf(String tiff) {

        // target path PDF
        String pdf = null;
        try {

            pdf = tiff.substring(0, tiff.lastIndexOf('.') + 1) + "pdf";

            // New document A4 standard (LETTER)
            Document document = new Document();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));

            document.setMarginMirroring(true);
            int pages = 0;
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            RandomAccessFileOrArray ra = null;
            int comps = 0;
            ra = new RandomAccessFileOrArray(tiff);
            comps = TiffImage.getNumberOfPages(ra);

            // Convertion statement
            for (int c = 0; c < comps; ++c) {
                Image img = TiffImage.getTiffImage(ra, c+1);

                   if (img != null) {


                  img.scalePercent(7200f / img.getDpiX(), 7200f / img.getDpiY());

                    img.setAbsolutePosition(0, 0); 
                    img.scaleAbsolute(600, 250); 

                    cb.addImage(img);


                    document.newPage();
                    ++pages;
                }
            }

            ra.close();
            document.close();

        } catch (Exception e) {
          System.out.println(e);
            pdf = null;
        }

       System.out.println("[" + tiff + "] -> [" + pdf + "] OK");
        return pdf;



    }
like image 906
nag Avatar asked Dec 11 '22 08:12

nag


1 Answers

You are creating a new document with A4 pages (as opposed to using the LETTER format). These pages have a width of 595 pt and a height of 842 pt. The origin of the coordinate system (0, 0) is in the lower-left corner, which is exactly where you're adding the image using the method setAbsolutePosition(0, 0);

Surprisingly, you don't adapt the size of the page to the size of the image. Instead you want to add the image at the top of the page. In this case, you need to change the coordinates of the absolute position like this:

img.setAbsolutePosition(0, PageSize.A4.getHeight() - img.getScaledHeight());

If img.getScaledHeight() exceeds PageSize.A4.getHeight() (which is equal to 842), your image will be clipped at the bottom. The image will be clipped on the right if img.getScaledWidth() exceeds PageSize.A4.getWidth() (which is equal to 595).

like image 87
Bruno Lowagie Avatar answered Dec 13 '22 21:12

Bruno Lowagie