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.
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
by
Furthermore, drop the
line as
saveState
only makes sense if you later use a matchingrestoreState
.