Example usage for org.apache.pdfbox.cos COSName getName

List of usage examples for org.apache.pdfbox.cos COSName getName

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSName getName.

Prototype

public String getName() 

Source Link

Document

This will get the name of this COSName object.

Usage

From source file:chiliad.parser.pdf.extractor.vectorgraphics.VectorGraphicsExtractor.java

License:Apache License

/**
 * Fill with Shading. Called by SHFill operator.
 *
 * @param shadingName The name of the Shading Dictionary to use for this
 * fill instruction./* ww  w . j  a va 2  s  . c  o m*/
 *
 * @throws IOException If there is an IO error while shade-filling the
 * clipping area.
 */
public void shFill(COSName shadingName) throws IOException {
    PDShadingResources shading = getResources().getShadings().get(shadingName.getName());
    LOG.debug("Shading = " + shading.toString());
    int shadingType = shading.getShadingType();
    Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
    Paint paint = null;
    switch (shadingType) {
    case 1:
        paint = new Type1ShadingPaint((PDShadingType1) shading, ctm, pageSize.height);
        break;
    case 2:
        paint = new AxialShadingPaint((PDShadingType2) shading, ctm, pageSize.height);
        break;
    case 3:
        paint = new RadialShadingPaint((PDShadingType3) shading, ctm, pageSize.height);
        break;
    case 4:
        paint = new Type4ShadingPaint((PDShadingType4) shading, ctm, pageSize.height);
        break;
    case 5:
        paint = new Type5ShadingPaint((PDShadingType5) shading, ctm, pageSize.height);
        break;
    case 6:
    case 7:
        // TODO
        LOG.debug("Shading type " + shadingType + " not yet supported");
        paint = new Color(0, 0, 0, 0); // transparent
        break;
    default:
        throw new IOException("Invalid ShadingType " + shadingType + " for Shading " + shadingName);
    }
    graphics.setComposite(getGraphicsState().getNonStrokeJavaComposite());
    graphics.setPaint(paint);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    graphics.fill(getGraphicsState().getCurrentClippingPath());
}

From source file:edu.umass.cs.iesl.pdf2meta.cli.extract.pdfbox.pagedrawer.Invoke.java

License:Apache License

/**
 * process : Do : Paint the specified XObject (section 4.7).
 * @param operator The operator that is being executed.
 * @param arguments List//w w  w  .j  a v  a 2 s  .c  o  m
 * @throws java.io.IOException If there is an error invoking the sub object.
 */
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    GraphicsAwarePDFStreamEngine drawer = (GraphicsAwarePDFStreamEngine) context;
    PDPage page = drawer.getPage();
    COSName objectName = (COSName) arguments.get(0);
    Map xobjects = drawer.getResources().getXObjects();
    PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
    if (xobject == null) {
        log.warn("Can't find the XObject for '" + objectName.getName() + "'");
    } else if (xobject instanceof PDXObjectImage) {
        PDXObjectImage image = (PDXObjectImage) xobject;
        try {
            image.setGraphicsState(drawer.getGraphicsState());
            BufferedImage awtImage = image.getRGBImage();
            if (awtImage == null) {
                log.warn("getRGBImage returned NULL");
                return;//TODO PKOCH
            }
            int imageWidth = awtImage.getWidth();
            int imageHeight = awtImage.getHeight();
            double pageHeight = drawer.getPageSize().getHeight();

            log.debug("imageWidth: " + imageWidth + "\t\timageHeight: " + imageHeight);

            Matrix ctm = drawer.getGraphicsState().getCurrentTransformationMatrix();
            float yScaling = ctm.getYScale();
            float angle = (float) Math.acos(ctm.getValue(0, 0) / ctm.getXScale());
            if (ctm.getValue(0, 1) < 0 && ctm.getValue(1, 0) > 0)
                angle = (-1) * angle;
            ctm.setValue(2, 1, (float) (pageHeight - ctm.getYPosition() - Math.cos(angle) * yScaling));
            ctm.setValue(2, 0, (float) (ctm.getXPosition() - Math.sin(angle) * yScaling));
            // because of the moved 0,0-reference, we have to shear in the opposite direction
            ctm.setValue(0, 1, (-1) * ctm.getValue(0, 1));
            ctm.setValue(1, 0, (-1) * ctm.getValue(1, 0));
            AffineTransform ctmAT = ctm.createAffineTransform();
            ctmAT.scale(1f / imageWidth, 1f / imageHeight);
            drawer.drawImage(awtImage, ctmAT);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e, e);
        }
    } else if (xobject instanceof PDXObjectForm) {
        // save the graphics state
        context.getGraphicsStack().push((PDGraphicsState) context.getGraphicsState().clone());

        PDXObjectForm form = (PDXObjectForm) xobject;
        COSStream invoke = (COSStream) form.getCOSObject();
        PDResources pdResources = form.getResources();
        if (pdResources == null) {
            pdResources = page.findResources();
        }
        // if there is an optional form matrix, we have to
        // map the form space to the user space
        Matrix matrix = form.getMatrix();
        if (matrix != null) {
            Matrix xobjectCTM = matrix.multiply(context.getGraphicsState().getCurrentTransformationMatrix());
            context.getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
        }
        getContext().processSubStream(page, pdResources, invoke);

        // restore the graphics state
        context.setGraphicsState((PDGraphicsState) context.getGraphicsStack().pop());
    }
}

From source file:eu.europa.ec.markt.dss.signature.pdf.pdfbox.PdfBoxDict.java

License:Open Source License

@Override
public boolean hasANameWithValue(String name, String value) {
    COSName pdfName = (COSName) wrapped.getDictionaryObject(name);
    if (pdfName == null) {
        return false;
    }/*from  w w  w.j a va  2  s.co m*/
    return pdfName.getName().equals(value);
}

From source file:eu.europa.ec.markt.dss.signature.pdf.pdfbox.PdfBoxDict.java

License:Open Source License

@Override
public String[] list() throws IOException {
    final Set<COSName> cosNames = wrapped.keySet();
    List<String> result = new ArrayList<String>(cosNames.size());
    for (final COSName cosName : cosNames) {
        final String name = cosName.getName();
        result.add(name);//from  w  w w  . j a v a2  s .c  o  m
    }
    return result.toArray(new String[result.size()]);
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxDict.java

License:Open Source License

@Override
public String[] list() {
    final Set<COSName> cosNames = wrapped.keySet();
    List<String> result = new ArrayList<String>(cosNames.size());
    for (final COSName cosName : cosNames) {
        final String name = cosName.getName();
        result.add(name);/*  ww  w .ja  v a 2 s.  c o  m*/
    }
    return result.toArray(new String[result.size()]);
}

From source file:function.PrintImageLocations.java

License:Apache License

/**
 * This is used to handle an operation.//from www  .  ja  va2  s.  c o m
 *
 * @param operator The operation to perform.
 * @param arguments The list of arguments.
 *
 * @throws IOException If there is an error processing the operation.
 */
protected void processOperator(PDFOperator operator, List arguments) throws IOException {
    String operation = operator.getOperation();
    if (INVOKE_OPERATOR.equals(operation)) {
        COSName objectName = (COSName) arguments.get(0);
        Map<String, PDXObject> xobjects = getResources().getXObjects();
        PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
        if (xobject instanceof PDXObjectImage) {
            PDXObjectImage image = (PDXObjectImage) xobject;
            PDPage page = getCurrentPage();
            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();
            double pageHeight = page.getMediaBox().getHeight();
            //System.out.println("*******************************************************************");
            System.out.println("Found image [" + objectName.getName() + "]");

            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
            float yScaling = ctmNew.getYScale();
            float angle = (float) Math.acos(ctmNew.getValue(0, 0) / ctmNew.getXScale());
            if (ctmNew.getValue(0, 1) < 0 && ctmNew.getValue(1, 0) > 0) {
                angle = (-1) * angle;
            }
            ctmNew.setValue(2, 1, (float) (pageHeight - ctmNew.getYPosition() - Math.cos(angle) * yScaling));
            ctmNew.setValue(2, 0, (float) (ctmNew.getXPosition() - Math.sin(angle) * yScaling));
            // because of the moved 0,0-reference, we have to shear in the opposite direction
            ctmNew.setValue(0, 1, (-1) * ctmNew.getValue(0, 1));
            ctmNew.setValue(1, 0, (-1) * ctmNew.getValue(1, 0));
            AffineTransform ctmAT = ctmNew.createAffineTransform();
            ctmAT.scale(1f / imageWidth, 1f / imageHeight);

            float imageXScale = ctmNew.getXScale();
            float imageYScale = ctmNew.getYScale();
            System.out.println("position = " + ctmNew.getXPosition() + ", " + ctmNew.getYPosition());
            // size in pixel
            System.out.println("size = " + imageWidth + "px, " + imageHeight + "px");
            // size in page units
            System.out.println("size = " + imageXScale + ", " + imageYScale);
            // size in inches 
            imageXScale /= 72;
            imageYScale /= 72;
            System.out.println("size = " + imageXScale + "in, " + imageYScale + "in");
            // size in millimeter
            imageXScale *= 25.4;
            imageYScale *= 25.4;
            System.out.println("size = " + imageXScale + "mm, " + imageYScale + "mm");
            System.out.println();
            System.out.printf("dpi  = %.0f dpi (X), %.0f dpi (Y) %n",
                    image.getWidth() * 72 / ctmNew.getXScale(), image.getHeight() * 72 / ctmNew.getYScale());

        } else if (xobject instanceof PDXObjectForm) {
            // save the graphics state
            getGraphicsStack().push((PDGraphicsState) getGraphicsState().clone());
            PDPage page = getCurrentPage();

            PDXObjectForm form = (PDXObjectForm) xobject;
            COSStream invoke = (COSStream) form.getCOSObject();
            PDResources pdResources = form.getResources();
            if (pdResources == null) {
                pdResources = page.findResources();
            }
            // if there is an optional form matrix, we have to
            // map the form space to the user space
            Matrix matrix = form.getMatrix();
            if (matrix != null) {
                Matrix xobjectCTM = matrix.multiply(getGraphicsState().getCurrentTransformationMatrix());
                getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
            }
            processSubStream(page, pdResources, invoke);

            // restore the graphics state
            setGraphicsState((PDGraphicsState) getGraphicsStack().pop());
        }

    } else {
        super.processOperator(operator, arguments);
    }
}

From source file:mj.ocraptor.extraction.tika.parser.pdf.PDFParser.java

License:Apache License

private void extractMetadata(PDDocument document, Metadata metadata) throws TikaException {
    PDDocumentInformation info = document.getDocumentInformation();
    metadata.set(PagedText.N_PAGES, document.getNumberOfPages());
    addMetadata(metadata, TikaCoreProperties.TITLE, info.getTitle());
    addMetadata(metadata, TikaCoreProperties.CREATOR, info.getAuthor());
    addMetadata(metadata, TikaCoreProperties.CREATOR_TOOL, info.getCreator());
    addMetadata(metadata, TikaCoreProperties.KEYWORDS, info.getKeywords());
    addMetadata(metadata, "producer", info.getProducer());
    // TODO: Move to description in Tika 2.0
    addMetadata(metadata, TikaCoreProperties.TRANSITION_SUBJECT_TO_OO_SUBJECT, info.getSubject());
    addMetadata(metadata, "trapped", info.getTrapped());
    try {//from w ww.  j  a va2s  .c o m
        // TODO Remove these in Tika 2.0
        addMetadata(metadata, "created", info.getCreationDate());
        addMetadata(metadata, TikaCoreProperties.CREATED, info.getCreationDate());
    } catch (IOException e) {
        // Invalid date format, just ignore
    }
    try {
        Calendar modified = info.getModificationDate();
        addMetadata(metadata, Metadata.LAST_MODIFIED, modified);
        addMetadata(metadata, TikaCoreProperties.MODIFIED, modified);
    } catch (IOException e) {
        // Invalid date format, just ignore
    }

    // All remaining metadata is custom
    // Copy this over as-is
    List<String> handledMetadata = Arrays.asList(new String[] { "Author", "Creator", "CreationDate", "ModDate",
            "Keywords", "Producer", "Subject", "Title", "Trapped" });
    for (COSName key : info.getDictionary().keySet()) {
        String name = key.getName();
        if (!handledMetadata.contains(name)) {
            addMetadata(metadata, name, info.getDictionary().getDictionaryObject(key));
        }
    }
}

From source file:net.padaf.preflight.actions.ActionManagerFactory.java

License:Apache License

/**
 * This method extract actions from the given dictionary. An action is
 * identified by the following entries :
 * <UL>//  ww  w  .jav  a2 s . co m
 * <li>A (Action) : Available in Annotations, Outline items
 * <li>OpenAction (OpenAction) : Available in the Catalog dictionary
 * <li>AA (Additional Action) : Available in the Catalog dictionary,
 * Annotations, Pages
 * </UL>
 * 
 * If there are no action, an empty list is returned.
 * 
 * @param dictionary
 * @param cDoc
 * @return
 * @throws ValidationException
 */
public final List<AbstractActionManager> getActions(COSDictionary dictionary, COSDocument cDoc)
        throws ValidationException {

    List<AbstractActionManager> result = new ArrayList<AbstractActionManager>(0);
    Map<COSObjectKey, Boolean> alreadyCreated = new HashMap<COSObjectKey, Boolean>();

    COSBase aDict = dictionary.getDictionaryObject(DICTIONARY_KEY_ACTION);
    if (aDict != null) {
        callCreateAction(aDict, cDoc, result, alreadyCreated);
    }

    COSBase oaDict = dictionary.getDictionaryObject(DICTIONARY_KEY_OPEN_ACTION);
    if (oaDict != null) {
        if (!COSUtils.isArray(oaDict, cDoc)) {
            callCreateAction(oaDict, cDoc, result, alreadyCreated);
        }
        // else Nothing to do because of an array contains a Destination not an
        // action.
    }

    COSBase aa = dictionary.getDictionaryObject(DICTIONARY_KEY_ADDITIONAL_ACTION);
    if (aa != null) {
        COSDictionary aaDict = COSUtils.getAsDictionary(aa, cDoc);
        if (aaDict != null) {
            for (Object key : aaDict.keySet()) {
                COSName name = (COSName) key;
                callCreateAction(aaDict.getItem(name), cDoc, result, name.getName(), alreadyCreated);
            }
        }
    }
    return result;
}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * Create an instance of ExtGStateContainer using a Resource dictionary and a
 * COSDocument. This constructor initializes the listOfExtGState attribute
 * using the given Resource dictionary and the COSDocument.
 * /*from w  ww  .  j a  v a 2 s .c o  m*/
 * @param resources
 *          a resource COSDictionary
 * @param cDoc
 *          the COSDocument which contains the Resource dictionary
 * @throws ValidationException
 *           thrown if a the Extended Graphic State isn't valid
 */
public ExtGStateContainer(COSDictionary resources, COSDocument cDoc) throws ValidationException {
    this.cDoc = cDoc;
    COSBase egsEntry = resources.getItem(COSName.getPDFName(TRANPARENCY_DICTIONARY_KEY_EXTGSTATE));
    COSDictionary extGStates = COSUtils.getAsDictionary(egsEntry, cDoc);

    if (extGStates != null) {
        for (Object object : extGStates.keySet()) {
            COSName key = (COSName) object;
            if (key.getName().matches(TRANPARENCY_DICTIONARY_KEY_EXTGSTATE_ENTRY_REGEX)) {
                COSBase gsBase = extGStates.getItem(key);
                COSDictionary gsDict = COSUtils.getAsDictionary(gsBase, cDoc);
                if (gsDict == null) {
                    throw new ValidationException("The Extended Graphics State dictionary is invalid");
                }
                this.listOfExtGState.add(gsDict);
            }
        }
    }
    //else  if there are no ExtGState, the list will be empty.

}

From source file:net.padaf.preflight.helpers.StreamValidationHelper.java

License:Apache License

/**
 * Check dictionary entries. Only the Length entry is mandatory. In a PDF/A
 * file, F, FFilter and FDecodeParms are forbidden
 * //  w  w  w. j a va 2s .  co  m
 * @param streamObj
 * @param result
 */
protected void checkDictionaryEntries(COSStream streamObj, List<ValidationError> result) {
    boolean len = false;
    boolean f = false;
    boolean ffilter = false;
    boolean fdecParams = false;

    for (Object key : streamObj.keyList()) {
        if (!(key instanceof COSName)) {
            result.add(new ValidationResult.ValidationError(
                    ValidationConstants.ERROR_SYNTAX_DICTIONARY_KEY_INVALID,
                    "Invalid key in The Stream dictionary"));
            return;
        }
        COSName cosName = (COSName) key;
        if (cosName.getName().equals(STREAM_DICTIONARY_KEY_LENGHT)) {
            len = true;
        }
        if (cosName.getName().equals(STREAM_DICTIONARY_KEY_F)) {
            f = true;
        }
        if (cosName.getName().equals(STREAM_DICTIONARY_KEY_FFILTER)) {
            ffilter = true;
        }
        if (cosName.getName().equals(STREAM_DICTIONARY_KEY_FDECODEPARAMS)) {
            fdecParams = true;
        }
    }

    if (!len) {
        result.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_STREAM_LENGTH_MISSING,
                "Stream length is missing"));
    }

    if (f || ffilter || fdecParams) {
        result.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_STREAM_FX_KEYS,
                "F, FFilter or FDecodeParms keys are present in the stream dictionary"));
    }
}