Highlight a text PDF Box Reader

Viewed 622

I want to highlight a perticular text in the pdf.I have writen the following code but i am getting empty pdf with the box.I want to show the existing pdf content and the box should be drawn on the text so it will act as a text highliter.

      File file = new File(pdfName);
      PDDocument document = PDDocument.load(file);

      PDPage page = document.getPage(0);

      //Instantiating the PDPageContentStream class
      PDPageContentStream contentStream = new PDPageContentStream(document, page);

      //Setting the non stroking color
      contentStream.setNonStrokingColor(Color.DARK_GRAY);

      //Drawing a rectangle 
      contentStream.addRect(data.get(0).getX(), data.get(0).getY(), data.get(0).getWidth(), data.get(0).getHeight());

      //Drawing a rectangle
      contentStream.fill();

      System.out.println("rectangle added");

      //Closing the ContentStream object
      contentStream.close();

      //Saving the document
      //File file2 = new File("CompareOutput.pdf");

      //File fileOutput = new File("CompareOutput.pdf");
      document.save("CompareOutput.pdf");

      //Closing the document
      document.close();
1 Answers

Instead of

PDPageContentStream contentStream = new PDPageContentStream(document, page);

use

PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true))

This way your new content stream is appended.

However I expect another problem, you may want the "highlight" to be transparent. Have a look at this answer.

Related