3

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();
Chandhan Sai
  • 103
  • 1
  • 12

1 Answers1

3

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.

Tilman Hausherr
  • 17,731
  • 7
  • 58
  • 97
  • 1
    Its working thanks you very much.I was thinking were to chage append mode.I was creating an new output stream with append mode which doesnt work.Now i am getting expected output.Now i need to make it transperent or create a red stroke box.I can do it slowly :). – Chandhan Sai Jan 06 '19 at 11:46