how to know if a field is on a particular page?

后端 未结 4 1905
梦谈多话
梦谈多话 2020-12-06 13:34

The PDFbox content stream is done per page, but the fields come from the form which comes from the catalog, which comes from the pdf doc itself. So I\'m not sure which field

4条回答
  •  误落风尘
    2020-12-06 14:26

    This example uses Lucee (cfml) https://lucee.org/

    A big thank you to mkl as his answer above is invaluable and I couldn't have built this function without his help.

    Call the function: pageForSignature(doc, fieldName) and it will return the page no that the fieldname resides on. Returns -1 if fieldName not found.

      
      try{
    
      /*
      java is used by using CreateObject()
      */
    
      variables.File = CreateObject("java", "java.io.File");
    
      //references lucee bundle directory - typically on tomcat: /usr/local/tomcat/lucee-server/bundles
      variables.PDDocument = CreateObject("java", "org.apache.pdfbox.pdmodel.PDDocument", "org.apache.pdfbox.app", "2.0.18")
    
      function determineSafe(doc, widget){
    
        var i = '';
        var widgetObject = widget.getCOSObject();
        var pages = doc.getPages();
        var annotation = '';
        var annotationObject = '';
    
        for (i = 0; i < pages.getCount(); i=i+1){
    
        for (annotation in pages.get(i).getAnnotations()){
            if(annotation.getSubtype() eq 'widget'){
                annotationObject = annotation.getCOSObject();
                if (annotationObject.equals(widgetObject)){
                    return i;
                }
            }
        }
    
        }
        return -1;
      }
    
      function pageForSignature(doc, fieldName){
        try{
        var acroForm = doc.getDocumentCatalog().getAcroForm();
        var field = '';
        var widget = '';
        var annotation = '';
        var pageNo = '';
    
        for(field in acroForm.getFields()){
    
        if(field.getPartialName() == fieldName){
    
            for(widget in field.getWidgets()){
    
               for(annotation in widget.getPage().getAnnotations()){
    
                 if(annotation.getSubtype() == 'widget'){
    
                    pageNo = determineSafe(doc, widget);
                    doc.close();
                    return pageNo;
                 }
               }
    
            }
        }
      }
    return -1;  
    }catch(e){
        doc.close();
    writeDump(label="catch error",var='#e#');
      }
    } 
    
    doc = PDDocument.init().load(File.init('/**********/myfile.pdf'));
    
    //returns no,  page numbers start at 0
    pageNo = pageForSignature(doc, 'twtzceuxvx');
    
    writeDump(label="pageForSignature(doc, fieldName)", var="#pageNo#");
    

提交回复
热议问题