How to bring image to the front(of the text/image)

2020-04-17 04:56发布

问题:

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:

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

回答1:

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.