如何使用iText PdfStamper将内容添加到PDF [英] How to add Content to a PDF using iText PdfStamper

查看:5874
本文介绍了如何使用iText PdfStamper将内容添加到PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个系统,我必须在现有的PDF文档中添加一些图像。

I'm developing a System in which I have to add some images to an existing PDF Document.

这适用于iText 5.1.3,但是对于某些人而言在包含扫描图像的PDF中,它不会添加任何图像。

This works great with iText 5.1.3, but for some reason in a PDF that contains a scanned image it won't add any of the images.

这是 PDF文档无法使用PdfStamper修改

Here's the link to the PDF Document that can't be modified with PdfStamper

这里是代码

  PdfReader reader = new PdfReader("Registro celular_OR.pdf");
  PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("DocStamped.pdf"));
  Image img = Image.getInstance("someImage.jpg");
  img.setAbsolutePosition(0, 0);
  img.scaleAbsolute(50f, 50f);
  PdfContentByte over = null;

  int total = reader.getNumberOfPages() + 1;
  for(int i = 1; i < total; i++) {
    System.out.println("Procesando Pagina: " + i);
    over = stamper.getOverContent(i);
    over.addImage(img);

    over.beginText();
    BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
    over.setFontAndSize(bf_times, 8);
    over.showTextAligned(PdfContentByte.ALIGN_CENTER, "TEXTO PRUEBA", 50, 50, 0);
    over.endText();
  }
  stamper.close();


推荐答案

PDF页面不需要左下角拐角在(0,0)。它可以在坐标系中的任何位置。所以A4页面可以是(0,0,595,842),但也可能是(1000,2000,1595,2842)

A PDF page does not need to have its lower left corner at (0, 0). It can be anywhere in the coordinate system. So an A4 page can be (0, 0, 595, 842), but it might as well be (1000, 2000, 1595, 2842).

您将图像定位在(0,0)

img.setAbsolutePosition(0, 0);

但是本文档的页面定义为(0,15366,469) ,15728)。图像实际上已添加到输出文档中,但它位于页面的可见区域之外。

But the page of this document is defined as (0, 15366, 469, 15728). The image is actually added to the output document, but it's outside the visible area of the page.

您必须获取页面的坐标才能定位图像。在循环内,执行以下操作:

You have to get the coordinates of the page to position the image. Inside the loop, do this:

img.setAbsolutePosition(reader.getPageSize(i).getLeft(), reader.getPageSize(i).getBottom());

这篇关于如何使用iText PdfStamper将内容添加到PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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