Example usage for org.apache.pdfbox.contentstream.operator Operator getName

List of usage examples for org.apache.pdfbox.contentstream.operator Operator getName

Introduction

In this page you can find the example usage for org.apache.pdfbox.contentstream.operator Operator getName.

Prototype

public String getName() 

Source Link

Document

This will get the name of the operator.

Usage

From source file:airviewer.TextInAnnotationReplacer.java

License:Apache License

static void replaceText(PDDocument document, PDAnnotation anAnnotation, String newContents) {

    if (null != anAnnotation.getAppearance() && null != anAnnotation.getAppearance().getNormalAppearance()) {
        try {//from   www  . j a  va 2  s  .c o  m
            PDAppearanceStream annotationAppearanceStream = anAnnotation.getAppearance().getNormalAppearance()
                    .getAppearanceStream();

            PDFStreamParser parser = new PDFStreamParser(annotationAppearanceStream);
            parser.parse();
            List<Object> tokens = parser.getTokens();
            for (int j = 0; j < tokens.size(); j++) {
                Object next = tokens.get(j);
                if (next instanceof Operator) {
                    Operator op = (Operator) next;
                    //Tj and TJ are the two operators that display strings in a PDF
                    if (op.getName().equals("Tj")) {
                        // Tj takes one operand and that is the string to display so lets update that operator
                        COSString previous = (COSString) tokens.get(j - 1);
                        previous.setValue(newContents.getBytes(Charset.forName("UTF-8")));
                    } else if (op.getName().equals("TJ")) {
                        COSArray previous = (COSArray) tokens.get(j - 1);
                        for (int k = 0; k < previous.size(); k++) {
                            Object arrElement = previous.getObject(k);
                            if (arrElement instanceof COSString) {
                                COSString cosString = (COSString) arrElement;
                                cosString.setValue(newContents.getBytes(Charset.forName("UTF-8")));
                            }
                        }
                    }
                }
            }

            try (OutputStream out = annotationAppearanceStream.getStream().createOutputStream()) {
                ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
                tokenWriter.writeTokens(tokens);
            }

            anAnnotation.getAppearance().setNormalAppearance(annotationAppearanceStream);
        } catch (IOException ex) {
            Logger.getLogger(TextInAnnotationReplacer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.pdfbox2.placeholder.SignaturePlaceholderExtractor.java

License:EUPL

@Override
protected void processOperator(Operator operator, List<COSBase> arguments) throws IOException {
    String operation = operator.getName();
    if (operation.equals("Do")) {
        COSName objectName = (COSName) arguments.get(0);
        PDXObject xobject = (PDXObject) getResources().getXObject(objectName);
        if (xobject instanceof PDImageXObject) {
            try {
                PDImageXObject image = (PDImageXObject) xobject;
                SignaturePlaceholderData data = checkImage(image);
                if (data != null) {
                    PDPage page = getCurrentPage();
                    Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
                    int pageRotation = page.getRotation();
                    pageRotation = pageRotation % 360;
                    double rotationInRadians = Math.toRadians(pageRotation);//(page.findRotation() * Math.PI) / 180;

                    AffineTransform rotation = new AffineTransform();
                    rotation.setToRotation(rotationInRadians);
                    AffineTransform rotationInverse = rotation.createInverse();
                    Matrix rotationInverseMatrix = new Matrix();
                    rotationInverseMatrix.setFromAffineTransform(rotationInverse);
                    Matrix rotationMatrix = new Matrix();
                    rotationMatrix.setFromAffineTransform(rotation);

                    Matrix unrotatedCTM = ctm.multiply(rotationInverseMatrix);

                    float x = unrotatedCTM.getXPosition();
                    float yPos = unrotatedCTM.getYPosition();
                    float yScale = unrotatedCTM.getScaleY();
                    float y = yPos + yScale;
                    float w = unrotatedCTM.getScaleX();
                    ;//from  w  w  w  .j  av  a2s.  c o m

                    logger.debug("Page height: {}", page.getCropBox().getHeight());
                    logger.debug("Page width: {}", page.getCropBox().getWidth());

                    if (pageRotation == 90) {
                        y = page.getCropBox().getWidth() - (y * (-1));
                    } else if (pageRotation == 180) {
                        x = page.getCropBox().getWidth() + x;
                        y = page.getCropBox().getHeight() - (y * (-1));
                    } else if (pageRotation == 270) {
                        x = page.getCropBox().getHeight() + x;
                    }

                    String posString = "p:" + currentPage + ";x:" + x + ";y:" + y + ";w:" + w;

                    logger.debug("Found Placeholder at: {}", posString);
                    try {
                        data.setTablePos(new TablePos(posString));
                        data.setPlaceholderName(objectName.getName());
                        placeholders.add(data);
                    } catch (PdfAsException e) {
                        throw new IOException();
                    }
                }
            } catch (NoninvertibleTransformException e) {
                throw new IOException(e);
            }
        }
    } else {
        super.processOperator(operator, arguments);
    }
}

From source file:com.fngry.monk.biz.demo.pdf.pdfbox.PrintImageLocations.java

License:Apache License

/**
 * This is used to handle an operation./*from   w  w w  .  j a v  a 2s  . c  o m*/
 *
 * @param operator The operation to perform.
 * @param operands The list of arguments.
 *
 * @throws IOException If there is an error processing the operation.
 */
@Override
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
    String operation = operator.getName();
    if ("Do".equals(operation)) {
        COSName objectName = (COSName) operands.get(0);
        PDXObject xobject = getResources().getXObject(objectName);
        if (xobject instanceof PDImageXObject) {
            PDImageXObject image = (PDImageXObject) xobject;

            if ("png".equals(image.getSuffix())) {
                return;
            }

            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();

            //                System.out.println("Found image [" + objectName.getName() + "]");

            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
            float imageXScale = ctmNew.getScalingFactorX();
            float imageYScale = ctmNew.getScalingFactorY();

            // position in user space units. 1 unit = 1/72 inch at 72 dpi
            //                System.out.println("position in PDF = " + ctmNew.getTranslateX() + ", " + ctmNew.getTranslateY() + " in user space units");
            //                // raw size in pixels
            //                System.out.println("raw image size  = " + imageWidth + ", " + imageHeight + " in pixels");
            //                // displayed size in user space units
            //                System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in user space units");

            // displayed size in inches at 72 dpi rendering
            //                imageXScale /= 72;
            //                imageYScale /= 72;
            //                System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in inches at 72 dpi rendering");
            //                // displayed size in millimeters at 72 dpi rendering
            //                imageXScale *= 25.4;
            //                imageYScale *= 25.4;
            //                System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in millimeters at 72 dpi rendering");
            System.out.println();

            //                BufferedImage bufferImage = image.getImage();
            //                ByteArrayOutputStream os = new ByteArrayOutputStream();
            //                ImageIO.write(bufferImage, image.getSuffix(), os);
            //
            //                String fileName = this.pageName + "_" + objectName.getName() + "." + image.getSuffix();
            //                Path outputFile = new File("/Users/gaorongyu/Downloads/temp/"
            //                        + this.pageName + "_" + objectName.getName() + "." + image.getSuffix()).toPath();

            ImageInfo imageInfo = new ImageInfo((int) ctmNew.getTranslateX(), (int) ctmNew.getTranslateY(),
                    (int) imageXScale, (int) imageYScale);
            imageInfo.setImage(image);
            imageInfo.setObjectName(objectName);

            imageInfoList.add(imageInfo);
            //                java.nio.file.Files.copy(new ByteArrayInputStream(os.toByteArray()), outputFile);

        } else if (xobject instanceof PDFormXObject) {
            PDFormXObject form = (PDFormXObject) xobject;
            showForm(form);
        }
    } else {
        super.processOperator(operator, operands);
    }
}

From source file:org.apache.fop.render.pdf.pdfbox.MergeFontsPDFWriter.java

License:Apache License

protected void readPDFArguments(Operator op, Collection<COSBase> arguments) throws IOException {
    for (COSBase c : arguments) {
        if (c instanceof COSName) {
            COSName cn = (COSName) c;/* ww w .ja  v a2  s  .  c  o  m*/
            COSDictionary fontData = (COSDictionary) fonts.getDictionaryObject(cn.getName());
            String internalName = fontsToRemove.get(cn);
            if (internalName == null && fontData != null) {
                internalName = getNewFont(fontData, fontInfo, fontsToRemove.values());
            }
            if (fontData == null || internalName == null) {
                s.append("/" + key.getName(cn));
                if (op.getName().equals("Tf")) {
                    font = null;
                    oldFont = null;
                }
            } else {
                s.append("/" + internalName);
                fontsToRemove.put(cn, internalName);
                font = fontInfo.getUsedFonts().get(internalName);
                oldFont = getFont(fontData);
            }
            s.append(" ");
        } else if (c instanceof COSString && font != null && ((FOPPDFFont) font).size() != 1) {
            List<String> word = readCOSString((COSString) c, oldFont);
            if (word == null) {
                s.append(PDFText.escapeString(getString((COSString) c)));
            } else {
                String x = getMappedWord(word, font, ((COSString) c).getBytes());
                if (x == null) {
                    s.append(PDFText.escapeString(getString((COSString) c)));
                } else {
                    s.append(x);
                }
            }
        } else {
            processArg(op, c);
        }
    }
}

From source file:org.apache.fop.render.pdf.pdfbox.PDFWriter.java

License:Apache License

public String writeText(PDStream pdStream) throws IOException {
    PDFStreamParser pdfStreamParser = new PDFStreamParser(pdStream);
    pdfStreamParser.parse();/* w  ww  .j a  v  a  2s .c om*/
    List<Object> it = pdfStreamParser.getTokens();
    List<COSBase> arguments = new ArrayList<COSBase>();
    for (Object o : it) {
        if (o instanceof Operator) {
            Operator op = (Operator) o;
            readPDFArguments(op, arguments);
            s.append(op.getName() + "\n");
            arguments.clear();
            if (op.getImageParameters() != null) {
                for (Map.Entry<COSName, COSBase> cn : op.getImageParameters().entrySet()) {
                    arguments.add(cn.getKey());
                    arguments.add(cn.getValue());
                }
                readPDFArguments(op, arguments);
                s.append("ID " + new String(op.getImageData(), "ISO-8859-1"));
                arguments.clear();
                s.append("EI\n");
            }
        } else {
            arguments.add((COSBase) o);
        }
    }
    return s.toString();
}

From source file:org.apache.fop.render.pdf.pdfbox.PDFWriter.java

License:Apache License

protected void processArg(Operator op, COSBase c) throws IOException {
    if (c instanceof COSInteger) {
        s.append(((COSInteger) c).intValue());
        s.append(" ");
    } else if (c instanceof COSFloat) {
        float f = ((COSFloat) c).floatValue();
        s.append(new DecimalFormat("#.####", new DecimalFormatSymbols(Locale.US)).format(f));
        s.append(" ");
    } else if (c instanceof COSName) {
        COSName cn = (COSName) c;/* w  w  w .  j  av a2 s .  co  m*/
        s.append("/" + key.getName(cn));
        s.append(" ");
    } else if (c instanceof COSString) {
        s.append("<" + ((COSString) c).toHexString() + ">");
    } else if (c instanceof COSArray) {
        s.append("[");
        readPDFArguments(op, (Collection<COSBase>) ((COSArray) c).toList());
        s.append("] ");
    } else if (c instanceof COSDictionary) {
        Collection<COSBase> dictArgs = new ArrayList<COSBase>();
        if (currentMCID != 0 && op.getName().equals("BDC")) {
            for (Map.Entry<COSName, COSBase> cn : ((COSDictionary) c).entrySet()) {
                if (cn.getKey().getName().equals("MCID")) {
                    updateMCID(cn, dictArgs);
                } else {
                    dictArgs.add(cn.getKey());
                    dictArgs.add(cn.getValue());
                }
            }
        } else {
            for (Map.Entry<COSName, COSBase> cn : ((COSDictionary) c).entrySet()) {
                dictArgs.add(cn.getKey());
                dictArgs.add(cn.getValue());
            }
        }
        s.append("<<");
        readPDFArguments(op, dictArgs);
        s.append(">>");
    } else if (c instanceof COSBoolean) {
        s.append(((COSBoolean) c).getValue());
    } else {
        throw new IOException(c + " not supported");
    }
}

From source file:org.fit.pdfdom.PDFBoxTree.java

License:Open Source License

@Override
protected void processOperator(Operator operator, List<COSBase> arguments) throws IOException {
    String operation = operator.getName();
    /*System.out.println("Operator: " + operation + ":" + arguments.size());
    if (operation.equals("sc") || operation.equals("cs"))
    {/* w  w w  . j a  v  a  2  s . com*/
    System.out.print("  ");
    for (int i = 0; i < arguments.size(); i++)
        System.out.print(arguments.get(i) + " ");
    System.out.println();
    }*/

    //word spacing
    if (operation.equals("Tw")) {
        style.setWordSpacing(getLength(arguments.get(0)));
    }

    //letter spacing
    else if (operation.equals("Tc")) {
        style.setLetterSpacing(getLength(arguments.get(0)));
    }

    //graphics
    else if (operation.equals("m")) //move
    {
        if (!disableGraphics) {
            if (arguments.size() == 2) {
                float[] pos = transformPosition(getLength(arguments.get(0)), getLength(arguments.get(1)));
                path_x = pos[0];
                path_y = pos[1];
                path_start_x = pos[0];
                path_start_y = pos[1];
            }
        }
    } else if (operation.equals("l")) //line
    {
        if (!disableGraphics) {
            if (arguments.size() == 2) {
                float[] pos = transformPosition(getLength(arguments.get(0)), getLength(arguments.get(1)));
                graphicsPath.add(new PathSegment(path_x, path_y, pos[0], pos[1]));
                path_x = pos[0];
                path_y = pos[1];
            }
        }
    } else if (operation.equals("h")) //end subpath
    {
        if (!disableGraphics) {
            graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y));
        }
    }

    //rectangle
    else if (operation.equals("re")) {
        if (!disableGraphics) {
            if (arguments.size() == 4) {
                float x = getLength(arguments.get(0));
                float y = getLength(arguments.get(1));
                float width = getLength(arguments.get(2));
                float height = getLength(arguments.get(3));

                float[] p1 = transformPosition(x, y);
                float[] p2 = transformPosition(x + width, y + height);

                graphicsPath.add(new PathSegment(p1[0], p1[1], p2[0], p1[1]));
                graphicsPath.add(new PathSegment(p2[0], p1[1], p2[0], p2[1]));
                graphicsPath.add(new PathSegment(p2[0], p2[1], p1[0], p2[1]));
                graphicsPath.add(new PathSegment(p1[0], p2[1], p1[0], p1[1]));
            }
        }
    }

    //fill
    else if (operation.equals("f") || operation.equals("F") || operation.equals("f*")) {
        renderPath(graphicsPath, false, true);
        graphicsPath.removeAllElements();
    }

    //stroke
    else if (operation.equals("S")) {
        renderPath(graphicsPath, true, false);
        graphicsPath.removeAllElements();
    } else if (operation.equals("s")) {
        graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y));
        renderPath(graphicsPath, true, false);
        graphicsPath.removeAllElements();
    }

    //stroke and fill
    else if (operation.equals("B") || operation.equals("B*")) {
        renderPath(graphicsPath, true, true);
        graphicsPath.removeAllElements();
    } else if (operation.equals("b") || operation.equals("b*")) {
        graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y));
        renderPath(graphicsPath, true, true);
        graphicsPath.removeAllElements();
    }

    //cancel path
    else if (operation.equals("n")) {
        graphicsPath.removeAllElements();
    }

    //invoke named object - images
    else if (operation.equals("Do")) {
        if (!disableImages)
            processImageOperation(arguments);
    }

    super.processOperator(operator, arguments);
}