从特定位置的pdf中提取图像

时间:2018-04-09 09:07:12

标签: c# itext

我已经使用itextsharp在pdf中插入了图像,如下所示,我尝试了所有可能的解决方案,使用坐标提取它。

String pathin = pdf.src;
String pathout = "C:\\....";
string signedFile = System.IO.Path.GetTempFileName();
PdfReader reader = new PdfReader(pathin);
FileStream fs = new FileStream(pathout, FileMode.Create);
PdfStamper stamper = new PdfStamper(reader, fs);
PdfContentByte cb = stamper.GetOverContent(1);
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(imageFileName);
image1.RotationDegrees = 270f;
image1.Alignment = Element.ALIGN_TOP;
image1.SetAbsolutePosition(0,0);
image1.ScalePercent(50f, 50f);

cb.AddImage(image1);
stamper.Close();
fs.Close();
Console.Read();
pdf.src = pathout;

有没有办法使用itextsharp从位置(0,0)中提取图像?

1 个答案:

答案 0 :(得分:2)

伪码:

  • 实施IEventListener
  • 解析您感兴趣的页面,CanvasProcessor在其构造函数中执行IEventListener实现,每次完成文本,图像或路径的渲染时,它都会通知{{1} }
  • IEventListener有一个名为IEventListener的方法。其中一种类型将负责图像
  • eventOccurred(IEventData data, EventType type)投射到IEventData
  • ImageRenderInfo对象
  • 派生坐标
  • 如果坐标恰好包含ImageRenderInfo,则(暂时)将图片存储在Point(0, 0)
  • 的变量中

代码示例(java,iText7)
免责声明:以下代码无法处理轮播

IEventListener

这是调用此类的主要方法

class MyImageSeek implements IEventListener{

private int pageNr = 0;
private Map<Integer, Map<Rectangle, BufferedImage>> images = new HashMap<>();

public MyImageSeek(PdfDocument pdfDocument){
    PdfCanvasProcessor canvasProcessor = new PdfCanvasProcessor(this);
    for(int i=1;i<=pdfDocument.getNumberOfPages();i++) {
        images.put(i, new HashMap<Rectangle, BufferedImage>());
        pageNr = i;
        canvasProcessor.processPageContent(pdfDocument.getPage(i));
    }
}

@Override
public void eventOccurred(IEventData data, EventType type) {
    if(type != EventType.RENDER_IMAGE)
        return;
    ImageRenderInfo imageRenderInfo = (ImageRenderInfo) data;

    int x = (int) imageRenderInfo.getStartPoint().get(0);
    int y = (int) imageRenderInfo.getStartPoint().get(1);
    int w = (int) imageRenderInfo.getImageCtm().get(Matrix.I11);
    int h = (int) imageRenderInfo.getImageCtm().get(Matrix.I22);

    try {
        images.get(pageNr).put(new Rectangle(x,y,w,h), imageRenderInfo.getImage().getBufferedImage());
    } catch (IOException e) {}
}

@Override
public Set<EventType> getSupportedEvents() {
    return null;
}

public Map<Rectangle, BufferedImage> getImages(int pageNr){
    return images.get(pageNr);
}
}