简体   繁体   中英

How to bring image to the front(of the text/image) or send the image to the back((of the text/image)) in IText7 using java?

How to bring image to the front(of the text/image) or send the image to the back((of the text/image)) in IText7(7.0.8) using Java?

import java.io.FileNotFoundException;
import java.io.IOException;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfResources;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;

public class AddImageUnderlayToPDF {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader("c:\\Development\\test.pdf"),
                new PdfWriter("c:\\Development\\test_result.pdf"));
        ImageData img = ImageDataFactory.create("c:\\Development\\kishore signature.png");
        PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);
        under.addImage(img, 100, 0f, 0f, 100, 100, 300, false);
        under.saveState();
        pdfDoc.close();
    }
}

..but it doesn't work, it doesn't show the image in the pdf. I also I noticed an error while opening the pdf:

Acrobat PDF错误

Similar approach is working fine for the text but not the images. Any help is appreciated.

The error is the same as in your earlier question : You use a throw-away resources object, so the image resource is missing in the result.

You can fix this by using the actual page resources. Simply replace

PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), new PdfResources(), pdfDoc);

by

PdfCanvas under = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(), pdfDoc.getFirstPage().getResources(), pdfDoc);

Furthermore, drop the

under.saveState();

line as saveState only makes sense if you later use a matching restoreState .

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