简体   繁体   中英

How to add an image in the last page of pdf using iText?

How do i add an image on the last page of existing PDF document. Please help me.

The following example adds an image to the second page of an existing pdf using Itext 5.

    String src = "c:/in.pdf;
    String dest = "c:/out.pdf";
    String IMG = "C:/image.jpg";

    try {

        PdfReader reader = new PdfReader(src);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(IMG);
        image.setAbsolutePosition(36, 400);
        PdfContentByte over = stamper.getOverContent(2);
        over.addImage(image);
        stamper.close();
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

The best solution for me was to create a new in-memory PDF document with the image I want to add, then copy this page to the original document.

 // Create a separate doc for image
var pdfDocWithImageOutStream = new ByteArrayOutputStream();
var pdfDocWithImage = new PdfDocument(new PdfWriter(pdfDocWithImageOutStream).setSmartMode(true));
var docWithImage = new Document(pdfDocWithImage, destinationPdf.getDefaultPageSize());

// Add image to the doc
docWithImage.add(image);

// Close the doc to save data
docWithImage.close();
pdfDocWithImage.close();

// Open the same doc for reading
pdfDocWithImage = new PdfDocument(new PdfReader(new ByteArrayInputStream(pdfDocWithImageOutStream.toByteArray())));
docWithImage = new Document(pdfDocWithImage, destinationPdf.getDefaultPageSize());

// Copy page to original (destinationPdf)
pdfDocWithImage.copyPagesTo(1, pdfDocWithImage.getNumberOfPages(), destinationPdf);

docWithImage.close();
pdfDocWithImage.close();

You can read the text from the PDF using the same ITEXT library.Try this

    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages();
    PdfTextExtractor parser =new PdfTextExtractor(new PdfReader("C:/Text.pdf"));
    parser.getTextFromPage(3); // Extracting the content from a particular page.

After you have add your data ,You can load images either from file or from a URL, like this:

   Image image1 = Image.getInstance("watermark.png");
   document.add(image1);

   String imageUrl = "http://applause-voice.com/wp-content/uploads/2011/04/1hello.jpg";
   Image image2 = Image.getInstance(new URL(imageUrl));
   document.add(image2);

If you will add this code at the end of your Java Program , then the image will automatically comes at the end of your page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM