简体   繁体   中英

How do I find out which images are where in a PDF?

I am using ITextSharp trying to parse a PDF I have no control over. It doesn't use AcroForm, but it does use images of checkboxes. I can find and extract the two checkbox images themselves (checked and unchecked), but I cannot figure out how to get the references to those images.

How do I find out how many times each image is referenced, and where that reference is placed?

I found a way to get what I needed via the IRenderListener, starting with this comment: http://3d.5341.com/list/27/1036159.html

public static void Main()
{
    string inputStream = "whatever.pdf";

    PdfReader reader = new PdfReader(inputStream);

    var parser = new PdfReaderContentParser(reader);
    var imgScan = new FormListener();

    for (int i=1; i<=reader.NumberOfPages; ++i)
        parser.ProcessContent(1, imgScan);

    reader.Close();

    foreach (var r in imgScan.CheckBoxBoxes)
    {
        r.Dump();
    }
}

public class CheckboxBox
{
    public CheckboxBox()
    {
        this.CheckboxStates = new List<bool>();
    }

    public string Name { get;set; }
    public List<bool> CheckboxStates {get;set;}
}

public class FormListener : IRenderListener
{
    public List<CheckboxBox> CheckBoxBoxes { get;set;}
    private CheckboxBox m_CurrentCheckboxBox { get;set;}
    public FormListener()
    {
        this.CheckBoxBoxes = new List<CheckboxBox>();
        this.BeginNewBox();
    }

    public void BeginTextBlock()  {}
    public void EndTextBlock() {}

    private void BeginNewBox()
    {
        this.m_CurrentCheckboxBox = new CheckboxBox();
        this.CheckBoxBoxes.Add(this.m_CurrentCheckboxBox);
    }

    private bool IsNewBoxStarting(TextRenderInfo renderInfo)
    {
        return Regex.IsMatch(renderInfo.GetText(), @"\d+\.");
    }

    public void RenderText(TextRenderInfo renderInfo) { 
        if (this.IsNewBoxStarting(renderInfo))
            BeginNewBox();

        this.m_CurrentCheckboxBox.Name += renderInfo.GetText() + " ";
    }

    private bool GetCheckboxState(ImageRenderInfo renderInfo)
    {
        var n = renderInfo.GetRef().Number;
        return n == 21; // MagicNumberOfYesCheckboxImage;
    }

    public void RenderImage(ImageRenderInfo renderInfo)
    {
        this.m_CurrentCheckboxBox.CheckboxStates.Add(this.GetCheckboxState(renderInfo));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM