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

The following examples show how to use org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation. 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: ParagraphCellDrawer.java    From easytable with MIT License 6 votes vote down vote up
@SneakyThrows
@Override
public void drawContent(DrawingContext drawingContext) {
    if (drawingContext.getPage() == null) {
        throw new PageNotSetException("Page is not set in drawing context. Please ensure the page is set on table drawer.");
    }

    Paragraph paragraph = cell.getParagraph().getWrappedParagraph();

    AnnotationDrawListener annotationDrawListener = createAndGetAnnotationDrawListenerWith(drawingContext);

    float x = drawingContext.getStartingPoint().x + cell.getPaddingLeft();
    float y = drawingContext.getStartingPoint().y + getAdaptionForVerticalAlignment();

    paragraph.drawText(
            drawingContext.getContentStream(),
            new Position(x, y),
            ALIGNMENT_MAP.getOrDefault(cell.getSettings().getHorizontalAlignment(), Alignment.Left),
            annotationDrawListener
    );

    annotationDrawListener.afterPage(null);
    annotationDrawListener.afterRender();
    drawingContext.getPage().getAnnotations().forEach(PDAnnotation::constructAppearances);
}
 
Example #2
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Update the StructParents and StructParent values in a PDPage.
 *
 * @param page the new page
 * @param structParentOffset the offset which should be applied
 */
private void updateStructParentEntries(PDPage page, int structParentOffset) throws IOException
{
    if (page.getStructParents() >= 0)
    {
        page.setStructParents(page.getStructParents() + structParentOffset);
    }
    List<PDAnnotation> annots = page.getAnnotations();
    List<PDAnnotation> newannots = new ArrayList<PDAnnotation>();
    for (PDAnnotation annot : annots)
    {
        if (annot.getStructParent() >= 0)
        {
            annot.setStructParent(annot.getStructParent() + structParentOffset);
        }
        newannots.add(annot);
    }
    page.setAnnotations(newannots);
}
 
Example #3
Source File: PDAcroForm.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Check if there needs to be a scaling transformation applied.
 * 
 * @param annotation
 * @param rotation 
 * @return the need for a scaling transformation.
 */    
private boolean resolveNeedsScaling(PDAnnotation annotation, int rotation)
{
    PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream();
    // Check if there is a transformation within the XObjects content
    PDResources resources = appearanceStream.getResources();
    if (resources != null && resources.getXObjectNames().iterator().hasNext())
    {
        return true;
    }
    PDRectangle bbox = appearanceStream.getBBox();
    PDRectangle fieldRect = annotation.getRectangle();
    if (rotation == 90 || rotation == 270)
    {
        return Float.compare(bbox.getWidth(),  fieldRect.getHeight()) != 0 ||
               Float.compare(bbox.getHeight(), fieldRect.getWidth()) != 0;
    }
    else
    {
        return Float.compare(bbox.getWidth(),  fieldRect.getWidth()) != 0 ||
               Float.compare(bbox.getHeight(), fieldRect.getHeight()) != 0;
    }
}
 
Example #4
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Draws the page to the requested context.
 * 
 * @param g The graphics context to draw onto.
 * @param pageSize The size of the page to draw.
 * @throws IOException If there is an IO error while drawing the page.
 */
public void drawPage(Graphics g, PDRectangle pageSize) throws IOException
{
    graphics = (Graphics2D) g;
    xform = graphics.getTransform();
    initialClip = graphics.getClip();
    this.pageSize = pageSize;

    setRenderingHints();

    graphics.translate(0, pageSize.getHeight());
    graphics.scale(1, -1);

    // adjust for non-(0,0) crop box
    graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());

    processPage(getPage());

    for (PDAnnotation annotation : getPage().getAnnotations(annotationFilter))
    {
        showAnnotation(annotation);
    }

    graphics = null;
}
 
Example #5
Source File: PDPage.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will return a list of the annotations for this page.
 *
 * @param annotationFilter the annotation filter provided allowing to filter out specific annotations
 * @return List of the PDAnnotation objects, never null. The returned list is backed by the
 * annotations COSArray, so any adding or deleting in this list will change the document too.
 * 
 * @throws IOException If there is an error while creating the annotation list.
 */
public List<PDAnnotation> getAnnotations(AnnotationFilter annotationFilter) throws IOException
{
    COSBase base = page.getDictionaryObject(COSName.ANNOTS);
    if (base instanceof COSArray)
    {
        COSArray annots = (COSArray) base;
        List<PDAnnotation> actuals = new ArrayList<PDAnnotation>();
        for (int i = 0; i < annots.size(); i++)
        {
            COSBase item = annots.getObject(i);
            if (item == null)
            {
                continue;
            }
            PDAnnotation createdAnnotation = PDAnnotation.createAnnotation(item);
            if (annotationFilter.accept(createdAnnotation))
            {
                actuals.add(createdAnnotation);
            }
        }
        return new COSArrayList<PDAnnotation>(actuals, annots);
    }
    return new COSArrayList<PDAnnotation>(page, COSName.ANNOTS);
}
 
Example #6
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 #7
Source File: Splitter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void processAnnotations(PDPage imported) throws IOException
{
    List<PDAnnotation> annotations = imported.getAnnotations();
    for (PDAnnotation annotation : annotations)
    {
        if (annotation instanceof PDAnnotationLink)
        {
            PDAnnotationLink link = (PDAnnotationLink)annotation;   
            PDDestination destination = link.getDestination();
            if (destination == null && link.getAction() != null)
            {
                PDAction action = link.getAction();
                if (action instanceof PDActionGoTo)
                {
                    destination = ((PDActionGoTo)action).getDestination();
                }
            }
            if (destination instanceof PDPageDestination)
            {
                // TODO preserve links to pages within the splitted result  
                ((PDPageDestination) destination).setPage(null);
            }
        }
        // TODO preserve links to pages within the splitted result  
        annotation.setPage(null);
    }
}
 
Example #8
Source File: PDFStreamEngine.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Shows the given annotation.
 *
 * @param annotation An annotation on the current page.
 * @throws IOException If an error occurred reading the annotation
 */
public void showAnnotation(PDAnnotation annotation) throws IOException
{
    PDAppearanceStream appearanceStream = getAppearance(annotation);
    if (appearanceStream != null)
    {
        processAnnotation(annotation, appearanceStream);
    }
}
 
Example #9
Source File: PDObjectReference.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Gets a higher-level object for the referenced object.
 * Currently this method may return a {@link PDAnnotation},
 * a {@link PDXObject} or <code>null</code>.
 * 
 * @return a higher-level object for the referenced object
 */
public COSObjectable getReferencedObject()
{
    COSBase obj = this.getCOSObject().getDictionaryObject(COSName.OBJ);
    if (!(obj instanceof COSDictionary))
    {
        return null;
    }
    try
    {
        if (obj instanceof COSStream)
        {
            PDXObject xobject = PDXObject.createXObject(obj, null); // <-- TODO: valid?
            if (xobject != null)
            {
                return xobject;
            }
        }
        COSDictionary objDictionary  = (COSDictionary)obj;
        PDAnnotation annotation = PDAnnotation.createAnnotation(obj);
        /*
         * COSName.TYPE is optional, so if annotation is of type unknown and
         * COSName.TYPE is not COSName.ANNOT it still may be an annotation.
         * TODO shall we return the annotation object instead of null?
         * what else can be the target of the object reference?
         */
        if (!(annotation instanceof PDAnnotationUnknown) 
                || COSName.ANNOT.equals(objDictionary.getDictionaryObject(COSName.TYPE))) 
        {
            return annotation;
        }
    }
    catch (IOException exception)
    {
        // this can only happen if the target is an XObject.
    }
    return null;
}
 
Example #10
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 #11
Source File: PDPage.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will return a list of the annotations for this page.
 *
 * @return List of the PDAnnotation objects, never null. The returned list is backed by the
 * annotations COSArray, so any adding or deleting in this list will change the document too.
 * 
 * @throws IOException If there is an error while creating the annotation list.
 */
public List<PDAnnotation> getAnnotations() throws IOException
{
    return getAnnotations(new AnnotationFilter()
    {
        @Override
        public boolean accept(PDAnnotation annotation)
        {
            return true;
        }
    });
}
 
Example #12
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 #13
Source File: RemoveStrikeoutComment.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45812696/pdfbox-delete-comment-maintain-strikethrough">
 * PDFBox delete comment maintain strikethrough
 * </a>
 * <br/>
 * <a href="https://expirebox.com/files/3d955e6df4ca5874c38dbf92fc43b5af.pdf">
 * only_fields.pdf
 * </a>
 * <a href="https://file.io/DTvqhC">
 * (alternative download)
 * </a>
 * <p>
 * Due to a bug in the <code>COSArrayList</code> usage for page annotations,
 * the indirect reference to the annotation in question is not removed from
 * the actual page annotations array.
 * </p>
 */
@Test
public void testRemoveLikeStephan() throws IOException {
    try (InputStream resource = getClass().getResourceAsStream("only_fields.pdf")) {
        PDDocument document = Loader.loadPDF(resource);
        List<PDAnnotation> annotations = new ArrayList<>();
        PDPageTree allPages = document.getDocumentCatalog().getPages();

        for (int i = 0; i < allPages.getCount(); i++) {
            PDPage page = allPages.get(i);
            annotations = page.getAnnotations();

            List<PDAnnotation> annotationToRemove = new ArrayList<PDAnnotation>();

            if (annotations.size() < 1)
                continue;
            else {
                for (PDAnnotation annotation : annotations) {

                    if (annotation.getContents() != null
                            && annotation.getContents().equals("Sample Strikethrough")) {
                        annotationToRemove.add(annotation);
                    }
                }
                annotations.removeAll(annotationToRemove);
            }
        }

        document.save(new File(RESULT_FOLDER, "only_fields-removeLikeStephan.pdf"));
    }
}
 
Example #14
Source File: RemoveStrikeoutComment.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/45812696/pdfbox-delete-comment-maintain-strikethrough">
 * PDFBox delete comment maintain strikethrough
 * </a>
 * <br/>
 * <a href="https://expirebox.com/files/3d955e6df4ca5874c38dbf92fc43b5af.pdf">
 * only_fields.pdf
 * </a>
 * <a href="https://file.io/DTvqhC">
 * (alternative download)
 * </a>
 * <p>
 * The OP only wanted the comment removed, not the strike-through. Thus, we must
 * not remove the annotation but merely the comment building attributes.
 * </p>
 */
@Test
public void testRemoveLikeStephanImproved() throws IOException {
    final COSName POPUP = COSName.getPDFName("Popup");
    try (InputStream resource = getClass().getResourceAsStream("only_fields.pdf")) {
        PDDocument document = Loader.loadPDF(resource);
        List<PDAnnotation> annotations = new ArrayList<>();
        PDPageTree allPages = document.getDocumentCatalog().getPages();

        List<COSObjectable> objectsToRemove = new ArrayList<>();

        for (int i = 0; i < allPages.getCount(); i++) {
            PDPage page = allPages.get(i);
            annotations = page.getAnnotations();

            for (PDAnnotation annotation : annotations) {
                if ("StrikeOut".equals(annotation.getSubtype()))
                {
                    COSDictionary annotationDict = annotation.getCOSObject();
                    COSBase popup = annotationDict.getItem(POPUP);
                    annotationDict.removeItem(POPUP);
                    annotationDict.removeItem(COSName.CONTENTS); // plain text comment
                    annotationDict.removeItem(COSName.RC);       // rich text comment
                    annotationDict.removeItem(COSName.T);        // author

                    if (popup != null)
                        objectsToRemove.add(popup);
                }
            }

            annotations.removeAll(objectsToRemove);
        }

        document.save(new File(RESULT_FOLDER, "only_fields-removeImproved.pdf"));
    }
}
 
Example #15
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 #16
Source File: PDFreeTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDFreeTextAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #17
Source File: PDPolylineAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDPolylineAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}
 
Example #18
Source File: PDLineAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDLineAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}
 
Example #19
Source File: PDPolylineAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDPolylineAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #20
Source File: AnnotationBorder.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
static AnnotationBorder getAnnotationBorder(PDAnnotation annotation,
        PDBorderStyleDictionary borderStyle)
{
    AnnotationBorder ab = new AnnotationBorder();
    if (borderStyle == null)
    {
        COSArray border = annotation.getBorder();
        if (border.size() >= 3 && border.getObject(2) instanceof COSNumber)
        {
            ab.width = ((COSNumber) border.getObject(2)).floatValue();
        }
        if (border.size() > 3)
        {
            COSBase base3 = border.getObject(3);
            if (base3 instanceof COSArray)
            {
                ab.dashArray = ((COSArray) base3).toFloatArray();
            }
        }
    }
    else
    {
        ab.width = borderStyle.getWidth();
        if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_DASHED))
        {
            ab.dashArray = borderStyle.getDashStyle().getDashArray();
        }
        if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_UNDERLINE))
        {
            ab.underline = true;
        }
    }
    if (ab.dashArray != null)
    {
        boolean allZero = true;
        for (float f : ab.dashArray)
        {
            if (Float.compare(f, 0) != 0)
            {
                allZero = false;
                break;
            }
        }
        if (allZero)
        {
            ab.dashArray = null;
        }
    }
    return ab;
}
 
Example #21
Source File: PDFreeTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDFreeTextAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}
 
Example #22
Source File: PDUnderlineAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDUnderlineAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #23
Source File: PDUnderlineAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDUnderlineAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}
 
Example #24
Source File: PDPolygonAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDPolygonAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #25
Source File: PDLineAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDLineAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #26
Source File: PDTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDTextAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}
 
Example #27
Source File: PDTextAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDTextAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #28
Source File: PDSquareAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDSquareAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}
 
Example #29
Source File: PDSquareAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDSquareAppearanceHandler(PDAnnotation annotation, PDDocument document)
{
    super(annotation, document);
}
 
Example #30
Source File: PDSquigglyAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
public PDSquigglyAppearanceHandler(PDAnnotation annotation)
{
    super(annotation);
}