【问题标题】: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?如何使用java在IText7中将图像放在前面(文本/图像)或将图像发送到后面((文本/图像))?
【发布时间】:2018-11-09 19:07:20
【问题描述】:

如何使用 Java 在 IText7(7.0.8) 中将图像置于(文本/图像)的前面或将图像发送至(文本/图像)的后面?

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 时也注意到了一个错误:

类似的方法适用于文本但不适用于图像。任何帮助表示赞赏。

【问题讨论】:

  • “但它不起作用。” - 以何种方式不起作用?图像根本不显示吗?或者它是否显示但没有所有内容?还是以其他方式失败?
  • 图片不显示。我在 Acrobat 中打开时也看到错误。我用更详细的信息更新了我的帖子。

标签: java image itext itext7


【解决方案1】:

错误与您的earlier question 相同:您使用一次性资源对象,因此结果中缺少图像资源。

您可以通过使用实际的页面资源来解决此问题。简单替换

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 时才有意义。

【讨论】:

  • 它现在正在工作。感谢您的即时帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2022-07-26
  • 2020-07-07
  • 2014-03-30
  • 1970-01-01
相关资源
最近更新 更多