How to make annotation like highlighting, strikethrough, underline, draw, add text, etc in android for a pdf viewer?
Solution 1:
Your question seems to be what are methods to allow users to annotate over a PDF file in android/java, so here is one method for you, although it may not be the best solution.
I'd like to point out that it is not actually necessary to edit the actual PDF file just to allow users to add and view annotations. Your application could just store the data for annotations separately, store those annotations for each file, and load them when the file is loaded.
That means it won't create a new PDF file with those annotations placed it, but instead it will just store user-data for each PDF file which is loaded into your app, and display that when the user loads the PDF file again. (So it appears to be annotated).
Example:
- Read PDF file text, text-formatting & images into your app
- Display a document (like a word-processor)
- Allow the user to edit & annotate the document
- Save changes & annotation-data in your app (not the PDF file)
- When loading the file again, apply changes & annotations previously stored.
Your annotation class might look something like this:
class Annotations implements Serializable {
public Annotations() {
annotations = new HashSet<Annotation>();
}
public ArrayList<Annotation> getAnnotations() {
return new ArrayList<Annotation>(annotations);
}
public Annotation annotate(int starpos, int endpos) {
Annotation a = new Annotation(startpos, endpos);
annotations.add(a);
return a;
}
public void unannotate(Annotation a) {
annotations.remove(a);
}
static enum AnnotationTypes {
HIGHLIGHT, UNDERLINE;
}
class Annotation {
int startPos, endPos;
AnnotationTypes type;
Color color;
Annotation(int start, int end) {
startPos = start;
endPos = end;
}
public void update(int start, int end) {
startPos = start;
endPos = end;
}
public void highlight(int red, int green, int blue) {
type = AnnotationTypes.HIGHLIGHT;
color = new Color(red, green, blue);
}
public void underline(int red, int green, int blue) {
type = AnnotationTypes.UNDERLINE;
color = new Color(red, green, blue);
}
// getters
...
}
private Set<Annotation> annotations;
}
So you're just storing the annotation-display data here, and when you load the file and its respective (serialized) Annotations object, you can use each annotation to affect how you display characters between the startPos
and endPos
in your document.
Although i've used int
s for the two positions startPos
and endPos
, you could also use two or more variables to refer to array indexes, SQLite database table indexes, char positions for simple text documents; whatever your implementation is you could just change that so that you know where to start annotating and where to end annotating with that AnnotationType.
Also, you could set up property change listeners so that when the annotation properties are changed they fire off methods to update your display/view.