Example usage for org.apache.pdfbox.cos COSString setValue

List of usage examples for org.apache.pdfbox.cos COSString setValue

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSString setValue.

Prototype

public void setValue(byte[] value) 

Source Link

Document

Sets the raw value of this string.

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 w  w  w. ja v  a 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);
        }
    }
}