org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DetermineWidgetPage.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/22074449/how-to-know-if-a-field-is-on-a-particular-page">
 * how to know if a field is on a particular page?
 * </a>
 * <p>
 * This sample document contains the optional page entry in its annotations.
 * Thus, the fast method returns the same result as the safe one.
 * </p>
 */
@Test
public void testTestDuplicateField2() throws IOException
{
    System.out.println("test_duplicate_field2.pdf\n=================");
    try (   InputStream resource = getClass().getResourceAsStream("test_duplicate_field2.pdf")    )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
        if (acroForm != null)
        {
            for (PDField field : acroForm.getFieldTree())
            {
                System.out.println(field.getFullyQualifiedName());
                for (PDAnnotationWidget widget : field.getWidgets())
                {
                    System.out.print(widget.getAnnotationName() != null ? widget.getAnnotationName() : "(NN)");
                    System.out.printf(" - fast: %s", determineFast(document, widget));
                    System.out.printf(" - safe: %s\n", determineSafe(document, widget));
                }
            }
        }
    }
    System.out.println();
}
 
Example #2
Source File: PDTerminalField.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the widget annotations associated with this field.
 *
 * @return The list of widget annotations. Be aware that this list is <i>not</i> backed by the
 * actual widget collection of the field, so adding or deleting has no effect on the PDF
 * document until you call {@link #setWidgets(java.util.List) setWidgets()} with the modified
 * list.
 */
@Override
public List<PDAnnotationWidget> getWidgets()
{
    List<PDAnnotationWidget> widgets = new ArrayList<PDAnnotationWidget>();
    COSArray kids = (COSArray)getCOSObject().getDictionaryObject(COSName.KIDS);
    if (kids == null)
    {
        // the field itself is a widget
        widgets.add(new PDAnnotationWidget(getCOSObject()));
    }
    else if (kids.size() > 0)
    {
        // there are multiple widgets
        for (int i = 0; i < kids.size(); i++)
        {
            COSBase kid = kids.getObject(i);
            if (kid instanceof COSDictionary)
            {
                widgets.add(new PDAnnotationWidget((COSDictionary)kid));
            }
        }
    }
    return widgets;
}
 
Example #3
Source File: PDCheckBox.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Get the value which sets the check box to the On state.
 * 
 * <p>The On value should be 'Yes' but other values are possible
 * so we need to look for that. On the other hand the Off value shall
 * always be 'Off'. If not set or not part of the normal appearance keys
 * 'Off' is the default</p>
 *
 * @return the value setting the check box to the On state. 
 *          If an empty string is returned there is no appearance definition.
 */
public String getOnValue()
{
    PDAnnotationWidget widget = this.getWidgets().get(0);
    PDAppearanceDictionary apDictionary = widget.getAppearance();
    
    String onValue = "";
    if (apDictionary != null) 
    {
        PDAppearanceEntry normalAppearance = apDictionary.getNormalAppearance();
        if (normalAppearance != null)
        {
            Set<COSName> entries = normalAppearance.getSubDictionary().keySet();
            for (COSName entry : entries)
            {
                if (COSName.Off.compareTo(entry) != 0)
                {
                    onValue = entry.getName();
                }
            }
        }
    }
    return onValue;
}
 
Example #4
Source File: PDSignatureField.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
void constructAppearances() throws IOException
{
    PDAnnotationWidget widget = this.getWidgets().get(0);
    if (widget != null)
    {
        // check if the signature is visible
        if (widget.getRectangle() == null ||
            widget.getRectangle().getHeight() == 0 && widget.getRectangle().getWidth() == 0 ||
            widget.isNoView() ||  widget.isHidden())
        {
            return;
        }

        // TODO: implement appearance generation for signatures
        LOG.warn("Appearance generation for signature fields not yet implemented - you need to generate/update that manually");
    }
}
 
Example #5
Source File: PDButton.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void updateByValue(String value) throws IOException
{
    getCOSObject().setName(COSName.V, value);
    // update the appearance state (AS)
    for (PDAnnotationWidget widget : getWidgets())
    {
        if (widget.getAppearance() == null)
        {
            continue;
        }
        PDAppearanceEntry appearanceEntry = widget.getAppearance().getNormalAppearance();
        if (((COSDictionary) appearanceEntry.getCOSObject()).containsKey(value))
        {
            widget.setAppearanceState(value);
        }
        else
        {
            widget.setAppearanceState(COSName.Off.getName());
        }
    }
}
 
Example #6
Source File: PDButton.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private String getOnValueForWidget(PDAnnotationWidget widget)
{
    PDAppearanceDictionary apDictionary = widget.getAppearance();
    if (apDictionary != null) 
    {
        PDAppearanceEntry normalAppearance = apDictionary.getNormalAppearance();
        if (normalAppearance != null)
        {
            Set<COSName> entries = normalAppearance.getSubDictionary().keySet();
            for (COSName entry : entries)
            {
                if (COSName.Off.compareTo(entry) != 0)
                {
                    return entry.getName();
                }
            }
        }
    }
    return "";
}
 
Example #7
Source File: PDVisibleSigBuilder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void createSignature(PDSignatureField pdSignatureField, PDPage page, String signerName)
        throws IOException
{
    PDSignature pdSignature = new PDSignature();
    PDAnnotationWidget widget = pdSignatureField.getWidgets().get(0);
    pdSignatureField.setValue(pdSignature);
    widget.setPage(page);
    page.getAnnotations().add(widget);
    if (!signerName.isEmpty())
    {
        pdSignature.setName(signerName);
    }
    pdfStructure.setPdSignature(pdSignature);
    LOG.info("PDSignature has been created");
}
 
Example #8
Source File: PDButton.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Get the values to set individual buttons within a group to the on state.
 * 
 * <p>The On value could be an arbitrary string as long as it is within the limitations of
 * a PDF name object. The Off value shall always be 'Off'. If not set or not part of the normal
 * appearance keys 'Off' is the default</p>
 *
 * @return the potential values setting the check box to the On state. 
 *         If an empty Set is returned there is no appearance definition.
 */
public Set<String> getOnValues()
{
    // we need a set as the field can appear multiple times
    Set<String> onValues = new LinkedHashSet<String>();
    
    if (getExportValues().size() > 0)
    {
        onValues.addAll(getExportValues());
        return onValues;
    }
    
    List<PDAnnotationWidget> widgets = this.getWidgets();
    for (PDAnnotationWidget widget : widgets)
    {
    	onValues.add(getOnValueForWidget(widget));
    }        
    return onValues;
}
 
Example #9
Source File: DetermineWidgetPage.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/22074449/how-to-know-if-a-field-is-on-a-particular-page">
 * how to know if a field is on a particular page?
 * </a>
 * <p>
 * This sample document does not contain the optional page entry in its annotations.
 * Thus, the fast method fails in contrast to the safe one.
 * </p>
 */
@Test
public void testAFieldTwice() throws IOException
{
    System.out.println("aFieldTwice.pdf\n=================");
    try (   InputStream resource = getClass().getResourceAsStream("aFieldTwice.pdf")    )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
        if (acroForm != null)
        {
            for (PDField field : acroForm.getFieldTree())
            {
                System.out.println(field.getFullyQualifiedName());
                for (PDAnnotationWidget widget : field.getWidgets())
                {
                    System.out.print(widget.getAnnotationName() != null ? widget.getAnnotationName() : "(NN)");
                    System.out.printf(" - fast: %s", determineFast(document, widget));
                    System.out.printf(" - safe: %s\n", determineSafe(document, widget));
                }
            }
        }
    }
    System.out.println();
}
 
Example #10
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private PDAppearanceStream prepareNormalAppearanceStream(PDAnnotationWidget widget)
{
    PDAppearanceStream appearanceStream = new PDAppearanceStream(field.getAcroForm().getDocument());

    // Calculate the entries for the bounding box and the transformation matrix
    // settings for the appearance stream
    int rotation = resolveRotation(widget);
    PDRectangle rect = widget.getRectangle();
    Matrix matrix = Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0);
    Point2D.Float point2D = matrix.transformPoint(rect.getWidth(), rect.getHeight());

    PDRectangle bbox = new PDRectangle(Math.abs((float) point2D.getX()), Math.abs((float) point2D.getY()));
    appearanceStream.setBBox(bbox);

    AffineTransform at = calculateMatrix(bbox, rotation);
    if (!at.isIdentity())
    {
        appearanceStream.setMatrix(at);
    }
    appearanceStream.setFormType(1);
    appearanceStream.setResources(new PDResources());
    return appearanceStream;
}
 
Example #11
Source File: ReadForm.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/36964496/pdfbox-2-0-overcoming-dictionary-key-encoding">
 * PDFBox 2.0: Overcoming dictionary key encoding
 * </a>
 * <br/>
 * <a href="http://www.stockholm.se/PageFiles/85478/KYF%20211%20Best%C3%A4llning%202014.pdf">
 * KYF 211 Best&auml;llning 2014.pdf
 * </a>
 * 
 * <p>
 * Indeed, the special characters in the names are replaced by the Unicode replacement
 * character. PDFBox, when parsing a PDF name, immediately interprets its bytes as UTF-8
 * encoded which fails in the document at hand.
 * </p>
 */
@Test
public void testReadFormOptions() throws IOException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("KYF 211 Best\u00e4llning 2014.pdf") )
    {
        PDDocument pdfDocument = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
        
        PDField field = acroForm.getField("Krematorier");
        List<PDAnnotationWidget> widgets = field.getWidgets();
        System.out.println("Field Name: " + field.getPartialName() + " (" + widgets.size() + ")");
        for (PDAnnotationWidget annot : widgets) {
          PDAppearanceDictionary ap = annot.getAppearance();
          Set<COSName> keys = ((COSDictionary)(ap.getCOSObject().getDictionaryObject("N"))).keySet();
          ArrayList<String> keyList = new ArrayList<>(keys.size());
          for (COSName cosKey : keys) {keyList.add(cosKey.getName());}
          System.out.println(String.join("|", keyList));
        }
    }
}
 
Example #12
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/** @see #signAndLockExistingFieldWithLock(PDDocument, OutputStream, SignatureInterface) */
boolean lockFields(List<PDField> fields, Predicate<PDField> shallBeLocked) {
    boolean isUpdated = false;
    if (fields != null) {
        for (PDField field : fields) {
            boolean isUpdatedField = false;
            if (shallBeLocked.test(field)) {
                field.setFieldFlags(field.getFieldFlags() | 1);
                if (field instanceof PDTerminalField) {
                    for (PDAnnotationWidget widget : ((PDTerminalField)field).getWidgets())
                        widget.setLocked(true);
                }
                isUpdatedField = true;
            }
            if (field instanceof PDNonTerminalField) {
                if (lockFields(((PDNonTerminalField)field).getChildren(), shallBeLocked))
                    isUpdatedField = true;
            }
            if (isUpdatedField) {
                field.getCOSObject().setNeedToBeUpdated(true);
                isUpdated = true;
            }
        }
    }
    return isUpdated;
}
 
Example #13
Source File: DetermineWidgetPage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
int determineSafe(PDDocument document, PDAnnotationWidget widget) throws IOException
{
    COSDictionary widgetObject = widget.getCOSObject();
    PDPageTree pages = document.getPages();
    for (int i = 0; i < pages.getCount(); i++)
    {
        for (PDAnnotation annotation : pages.get(i).getAnnotations())
        {
            COSDictionary annotationObject = annotation.getCOSObject();
            if (annotationObject.equals(widgetObject))
                return i;
        }
    }
    return -1;
}
 
Example #14
Source File: PDAnnotationBleach.java    From DocBleach with MIT License 5 votes vote down vote up
void sanitizeWidgetAnnotation(PDAnnotationWidget annotationWidget) {
  if (annotationWidget.getAction() != null) {
    LOGGER.debug(
        "Found&Removed action on annotation widget, was {}", annotationWidget.getAction());
    pdfBleachSession.recordJavascriptThreat("Annotation", "External widget");
    annotationWidget.setAction(null);
  }
  sanitizeAnnotationActions(annotationWidget.getActions());
}
 
Example #15
Source File: ListFormFields.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/44817793/the-method-getkids-is-undefined-for-the-type-pdfield">
 * The method getKids() is undefined for the type PDField
 * </a>
 * <br/>
 * <a href="https://issues.apache.org/jira/secure/attachment/12651245/field%20name%20test.pdf">
 * field name test.pdf
 * </a>
 * <p>
 * The problems referred to don't exist anymore.
 * </p>
 */
@Test
public void testListFieldsInFieldNameTest() throws InvalidPasswordException, IOException
{
    PDDocument doc = Loader.loadPDF(getClass().getResourceAsStream("field name test.pdf"));
    PDAcroForm form = doc.getDocumentCatalog().getAcroForm();
    List<PDField> fields = form.getFields();
    for (int i=0; i<fields.size(); i++) {
        PDField f = fields.get(i);
        if (f instanceof PDTerminalField)
        {
            System.out.printf("%s, %s widgets\n", f.getFullyQualifiedName(), f.getWidgets().size());
            for (PDAnnotationWidget widget : f.getWidgets())
                System.out.printf("  %s\n", widget.getAnnotationName());
        }
        else if (f instanceof PDNonTerminalField)
        {
            List<PDField> kids = ((PDNonTerminalField)f).getChildren();
            for (int j=0; j<kids.size(); j++) {
                if (kids.get(j) instanceof PDField) {
                    PDField kidField = (PDField) kids.get(j);
                    System.out.println(kidField.getFullyQualifiedName());
                }
            } 
        }
    }
}
 
Example #16
Source File: RemoveField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
void removeWidgets(PDField targetField) throws IOException {
    if (targetField instanceof PDTerminalField) {
        List<PDAnnotationWidget> widgets = ((PDTerminalField)targetField).getWidgets();
        for (PDAnnotationWidget widget : widgets) {
            PDPage page = widget.getPage();
            if (page != null) {
                List<PDAnnotation> annotations = page.getAnnotations();
                boolean removed = false;
                for (PDAnnotation annotation : annotations) {
                    if (annotation.getCOSObject().equals(widget.getCOSObject()))
                    {
                        removed = annotations.remove(annotation);
                        break;
                    }
                }
                if (!removed)
                    System.out.println("Inconsistent annotation definition: Page annotations do not include the target widget.");
            } else {
                System.out.println("Widget annotation does not have an associated page; cannot remove widget.");
                // TODO: In this case iterate all pages and try to find and remove widget in all of them
            }
        }
    } else if (targetField instanceof PDNonTerminalField) {
        List<PDField> childFields = ((PDNonTerminalField)targetField).getChildren();
        for (PDField field : childFields)
            removeWidgets(field);
    } else {
        System.out.println("Target field is neither terminal nor non-terminal; cannot remove widgets.");
    }
}
 
Example #17
Source File: AddFormField.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
     * <a href="https://stackoverflow.com/questions/46433388/pdfbox-could-not-find-font-helv">
     * PDFbox Could not find font: /Helv
     * </a>
     * <br/>
     * <a href="https://drive.google.com/file/d/0B2--NSDOiujoR3hOZFYteUl2UE0/view?usp=sharing">
     * 4.pdf
     * </a>
     * <p>
     * The cause is a combination of the OP and the source PDF not providing
     * a default appearance for the text field and PDFBox providing defaults
     * inconsequentially.
     * </p>
     * <p>
     * This is fixed here by setting the default appearance explicitly.
     * </p>
     */
    @Test
    public void testAddFieldLikeEugenePodoliako() throws IOException {
        try (   InputStream originalStream = getClass().getResourceAsStream("4.pdf") )
        {
            PDDocument pdf = Loader.loadPDF(originalStream);
            PDDocumentCatalog docCatalog = pdf.getDocumentCatalog();
            PDAcroForm acroForm = docCatalog.getAcroForm();
            PDPage page = pdf.getPage(0);

            PDTextField textBox = new PDTextField(acroForm);
            textBox.setPartialName("SampleField");
            acroForm.getFields().add(textBox);
            PDAnnotationWidget widget = textBox.getWidgets().get(0);
            PDRectangle rect = new PDRectangle(0, 0, 0, 0);
            widget.setRectangle(rect);
            widget.setPage(page);
//  Unnecessary code from OP
//            widget.setAppearance(acroForm.getFields().get(0).getWidgets().get(0).getAppearance());
//  Fix added to set default appearance accordingly
            textBox.setDefaultAppearance(acroForm.getFields().get(0).getCOSObject().getString("DA"));

            widget.setPrinted(false);

            page.getAnnotations().add(widget);

            acroForm.refreshAppearances();
            acroForm.flatten();
            pdf.save(new File(RESULT_FOLDER, "4-add-field.pdf"));
            pdf.close();
        }
    }
 
Example #18
Source File: CheckImageFieldFilled.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/** @see #testCheckAcroFormGsa500Pdf_v4() */
boolean isFieldFilledAcroForm(PDAcroForm acroForm, String fieldName) throws IOException {
    for (PDField field : acroForm.getFieldTree()) {
        if (field instanceof PDPushButton && fieldName.equals(field.getPartialName())) {
            for (final PDAnnotationWidget widget : field.getWidgets()) {
                WidgetImageChecker checker = new WidgetImageChecker(widget);
                if (checker.hasImages())
                    return true;
            }
        }
    }
    return false;
}
 
Example #19
Source File: PDTerminalField.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Sets the field's widget annotations.
 *
 * @param children The list of widget annotations.
 */
public void setWidgets(List<PDAnnotationWidget> children)
{
    COSArray kidsArray = COSArrayList.converterToCOSArray(children);
    getCOSObject().setItem(COSName.KIDS, kidsArray);
    for (PDAnnotationWidget widget : children)
    {
        widget.getCOSObject().setItem(COSName.PARENT, this);
    }
}
 
Example #20
Source File: ExtractAppearanceText.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49427615/how-to-extract-label-text-from-push-button-using-apache-pdfbox">
 * How to extract label text from Push button using Apache PDFBox?
 * </a>
 * <p>
 * This method extracts the text from the normal appearance streams
 * of the form fields in the given PDF document.
 * </p>
 * @see #testBtn()
 * @see #testKYF211Beställning2014()
 */
public void showNormalFieldAppearanceTexts(PDDocument document) throws IOException {
    PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();

    if (acroForm != null) {
        SimpleXObjectTextStripper stripper = new SimpleXObjectTextStripper();

        for (PDField field : acroForm.getFieldTree()) {
            if (field instanceof PDTerminalField) {
                PDTerminalField terminalField = (PDTerminalField) field;
                System.out.println();
                System.out.println("* " + terminalField.getFullyQualifiedName());
                for (PDAnnotationWidget widget : terminalField.getWidgets()) {
                    PDAppearanceDictionary appearance = widget.getAppearance();
                    if (appearance != null) {
                        PDAppearanceEntry normal = appearance.getNormalAppearance();
                        if (normal != null) {
                            Map<COSName, PDAppearanceStream> streams = normal.isSubDictionary() ? normal.getSubDictionary() :
                                Collections.singletonMap(COSName.DEFAULT, normal.getAppearanceStream());
                            for (Map.Entry<COSName, PDAppearanceStream> entry : streams.entrySet()) {
                                String text = stripper.getText(entry.getValue());
                                System.out.printf("  * %s: %s\n", entry.getKey().getName(), text);
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example #21
Source File: PDButton.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void updateByOption(String value) throws IOException
{
    List<PDAnnotationWidget> widgets = getWidgets();
    List<String> options = getExportValues();
    
    if (widgets.size() != options.size())
    {
        throw new IllegalArgumentException("The number of options doesn't match the number of widgets");
    }
    
    if (value.equals(COSName.Off.getName()))
    {
        updateByValue(value);
    }
    else
    {
        // the value is the index of the matching option
        int optionsIndex = options.indexOf(value);

        // get the values the options are pointing to as
        // this might not be numerical
        // see PDFBOX-3682
        if (optionsIndex != -1)
        {
            updateByValue(getOnValue(optionsIndex));
        }
    }
}
 
Example #22
Source File: PDButton.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private String getOnValue(int index)
{
    List<PDAnnotationWidget> widgets = this.getWidgets();
    if (index < widgets.size())
    {
        return getOnValueForWidget(widgets.get(index));
    }
    return "";
}
 
Example #23
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Resolve the bounding box.
 * 
 * @param fieldWidget the annotation widget.
 * @param appearanceStream the annotations appearance stream.
 * @return the resolved boundingBox.
 */
private PDRectangle resolveBoundingBox(PDAnnotationWidget fieldWidget,
                                       PDAppearanceStream appearanceStream)
{
    PDRectangle boundingBox = appearanceStream.getBBox();
    if (boundingBox == null)
    {
        boundingBox = fieldWidget.getRectangle().createRetranslatedRectangle();
    }
    return boundingBox;
}
 
Example #24
Source File: PDAnnotationBleach.java    From DocBleach with MIT License 5 votes vote down vote up
void sanitizeAnnotation(PDAnnotation annotation) {
  if (annotation instanceof PDAnnotationLink) {
    sanitizeLinkAnnotation((PDAnnotationLink) annotation);
  }

  if (annotation instanceof PDAnnotationWidget) {
    sanitizeWidgetAnnotation((PDAnnotationWidget) annotation);
  }
}
 
Example #25
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private int resolveRotation(PDAnnotationWidget widget)
{
    PDAppearanceCharacteristicsDictionary  characteristicsDictionary = widget.getAppearanceCharacteristics();
    if (characteristicsDictionary != null)
    {
        // 0 is the default value if the R key doesn't exist
        return characteristicsDictionary.getRotation();
    }
    return 0;
}
 
Example #26
Source File: PDAnnotationBleachTest.java    From DocBleach with MIT License 5 votes vote down vote up
@Test
void sanitizeAnnotationWidgetAction() {
  PDAnnotationWidget annotationWidget = new PDAnnotationWidget();
  annotationWidget.setAction(new PDActionJavaScript());

  instance.sanitizeWidgetAnnotation(annotationWidget);

  assertThreatsFound(session, 1);
  assertNull(annotationWidget.getAction());
  reset(session);

  instance.sanitizeWidgetAnnotation(annotationWidget);
  assertThreatsFound(session, 0);
}
 
Example #27
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void validateAndEnsureAcroFormResources()
{
    // add font resources which might be available at the field 
    // level but are not at the AcroForm level to the AcroForm
    // to match Adobe Reader/Acrobat behavior        
    if (field.getAcroForm().getDefaultResources() == null)
    {
        return;
    }
    
    PDResources acroFormResources = field.getAcroForm().getDefaultResources();
    
    for (PDAnnotationWidget widget : field.getWidgets())
    {
        if (widget.getNormalAppearanceStream() != null && widget.getNormalAppearanceStream().getResources() != null)
        {
            PDResources widgetResources = widget.getNormalAppearanceStream().getResources();
            for (COSName fontResourceName : widgetResources.getFontNames())
            {
                try
                {
                    if (acroFormResources.getFont(fontResourceName) == null)
                    {
                        LOG.debug("Adding font resource " + fontResourceName + " from widget to AcroForm");
                        acroFormResources.put(fontResourceName, widgetResources.getFont(fontResourceName));
                    }
                }
                catch (IOException e)
                {
                    LOG.warn("Unable to match field level font with AcroForm font");
                }
            }
        }
    }
}
 
Example #28
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Check if the widget already exists in the annotation list
 *
 * @param acroFormFields the list of AcroForm fields.
 * @param signatureField the signature field.
 * @return true if the widget already existed in the annotation list, false if not.
 */
private boolean checkSignatureAnnotation(List<PDAnnotation> annotations, PDAnnotationWidget widget)
{
    for (PDAnnotation annotation : annotations)
    {
        if (annotation.getCOSObject().equals(widget.getCOSObject()))
        {
            return true;
        }
    }
    return false;
}
 
Example #29
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private PDDefaultAppearanceString getWidgetDefaultAppearanceString(PDAnnotationWidget widget) throws IOException
{
    COSString da = (COSString) widget.getCOSObject().getDictionaryObject(COSName.DA);
    PDResources dr = field.getAcroForm().getDefaultResources();
    return new PDDefaultAppearanceString(da, dr);
}
 
Example #30
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void draw() throws IOException {
	try (PDDocument doc = new PDDocument(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
		
		PDPage originalPage = document.getPage(parameters.getPage() - 1);
		SignatureFieldDimensionAndPositionBuilder dimensionAndPositionBuilder = 
				new SignatureFieldDimensionAndPositionBuilder(parameters, originalPage, pdFont);
		SignatureFieldDimensionAndPosition dimensionAndPosition = dimensionAndPositionBuilder.build();
		// create a new page
		PDPage page = new PDPage(originalPage.getMediaBox());
		doc.addPage(page);
		PDAcroForm acroForm = new PDAcroForm(doc);
           doc.getDocumentCatalog().setAcroForm(acroForm);
           PDSignatureField signatureField = new PDSignatureField(acroForm);
           PDAnnotationWidget widget = signatureField.getWidgets().get(0);
           List<PDField> acroFormFields = acroForm.getFields();
           acroForm.setSignaturesExist(true);
           acroForm.setAppendOnly(true);
           acroForm.getCOSObject().setDirect(true);
           acroFormFields.add(signatureField);

           PDRectangle rectangle = getPdRectangle(dimensionAndPosition, page);
           widget.setRectangle(rectangle);
           
           PDStream stream = new PDStream(doc);
           PDFormXObject form = new PDFormXObject(stream);
           PDResources res = new PDResources();
           form.setResources(res);
           form.setFormType(1);
           
           form.setBBox(new PDRectangle(rectangle.getWidth(), rectangle.getHeight()));
           
           PDAppearanceDictionary appearance = new PDAppearanceDictionary();
           appearance.getCOSObject().setDirect(true);
           PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject());
           appearance.setNormalAppearance(appearanceStream);
           widget.setAppearance(appearance);
           
           try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))
           {
           	rotateSignature(cs, rectangle, dimensionAndPosition);
           	setFieldBackground(cs, parameters.getBackgroundColor());
           	setText(cs, dimensionAndPosition, parameters);
           	setImage(cs, doc, dimensionAndPosition, parameters.getImage());
           }
           
           doc.save(baos);
           
           try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()))
           {
       		signatureOptions.setVisualSignature(bais);
       		signatureOptions.setPage(parameters.getPage() - 1);
           }
           
       }
}