如何使用Java在IText7中将图像显示在文本(图像/图像)的前面(或将图像发送到背面)(文本/图像)? [英] 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?

查看:1468
本文介绍了如何使用Java在IText7中将图像显示在文本(图像/图像)的前面(或将图像发送到背面)(文本/图像)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java在IText7(7.0.8)中将图像显示在文本(图像/图像)的前面或将图像发送到文本(图像/图像)的背面?

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();
    }
}

..但是它不起作用,它不会在pdf中显示图像.我也注意到打开pdf时出现错误:

..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

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

作者

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

此外,放下

under.saveState();

saveState行仅在以后使用匹配的restoreState时才有意义.

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

这篇关于如何使用Java在IText7中将图像显示在文本(图像/图像)的前面(或将图像发送到背面)(文本/图像)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆