Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.geom.Rectangle2D;
- import java.io.File;
- import java.io.IOException;
- import java.util.LinkedList;
- import java.util.List;
- import javax.management.MXBean;
- import org.apache.pdfbox.pdmodel.PDDocument;
- import org.apache.pdfbox.pdmodel.PDPage;
- import org.apache.pdfbox.pdmodel.common.PDRectangle;
- import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
- import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
- import org.apache.pdfbox.util.PDFTextStripperByArea;
- public class Test {
- public static void main(String[] args) {
- try {
- PDDocument pddDocument = PDDocument.load(new File("./sample.pdf"));
- List allPages = pddDocument.getDocumentCatalog().getAllPages();
- for (int i = 0; i < allPages.size(); i++) {
- PDPage page = (PDPage) allPages.get(i);
- List<PDAnnotation> la = page.getAnnotations();
- for (PDAnnotation anot : la) {
- if (anot instanceof PDAnnotationTextMarkup) {
- System.out.println("Highlight found");
- processHighlight((PDAnnotationTextMarkup) anot);
- System.out.println("====");
- }
- }
- pddDocument.save(new File("./result.pdf"));
- }
- pddDocument.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- private static void processHighlight(PDAnnotationTextMarkup highlight)
- throws IOException {
- System.out.println(highlight.getRectangle());
- float[] quads = highlight.getQuadPoints();
- PDFTextStripperByArea stripper = new PDFTextStripperByArea();
- PDRectangle pagesize = highlight.getPage().findMediaBox();
- System.out.println("Points: " + quads.length);
- for (int i = 0; i < quads.length; i++)
- System.out.println(quads[i]);
- for (int i = 0; i < quads.length; i += 8) {
- stripper.setSortByPosition(true);
- Rectangle2D.Float rect = new Rectangle2D.Float(quads[i] - 1,
- pagesize.getHeight() - quads[i + 1], quads[i + 6]
- - quads[i], quads[i + 1] - quads[i + 7]);
- stripper.addRegion("" + i, rect);
- }
- stripper.extractRegions(highlight.getPage());
- List<String> lines = new LinkedList<String>();
- for (String region : stripper.getRegions())
- lines.add(stripper.getTextForRegion(region));
- // Format text and set it as comment of the annotation
- String highlightText = "";
- for (String line : lines)
- highlightText = highlightText + line;
- highlight.setContents(highlightText);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement