Highlighting text

This is a code example of iText PDF, discover more.

31st May 2016
iText PDF

Switch code for this example

HighLightByAddingContent.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * This example was written in answer to the question:
  10.  * http://stackoverflow.com/questions/33952183
  11.  */
  12. package com.itextpdf.samples.sandbox.stamper;
  13.  
  14. import com.itextpdf.kernel.color.Color;
  15. import com.itextpdf.kernel.pdf.PdfDocument;
  16. import com.itextpdf.kernel.pdf.PdfReader;
  17. import com.itextpdf.kernel.pdf.PdfWriter;
  18. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  19. import com.itextpdf.samples.GenericTest;
  20. import com.itextpdf.test.annotations.type.SampleTest;
  21.  
  22. import java.io.File;
  23.  
  24. import org.junit.experimental.categories.Category;
  25.  
  26. @Category(SampleTest.class)
  27. public class HighLightByAddingContent extends GenericTest {
  28.     public static final String DEST
  29.             = "./target/test/resources/sandbox/stamper/high_light_by_adding_content.pdf";
  30.     public static final String SRC
  31.             = "./src/test/resources/pdfs/hello.pdf";
  32.  
  33.     public static void main(String[] args) throws Exception {
  34.         File file = new File(DEST);
  35.         file.getParentFile().mkdirs();
  36.         new HighLightByAddingContent().manipulatePdf(DEST);
  37.     }
  38.  
  39.     @Override
  40.     protected void manipulatePdf(String dest) throws Exception {
  41.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
  42.         PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(),
  43.                 pdfDoc.getFirstPage().getResources(), pdfDoc);
  44.         canvas.saveState();
  45.         canvas.setFillColor(Color.YELLOW);
  46.         canvas.rectangle(36, 786, 66, 16);
  47.         canvas.fill();
  48.         canvas.restoreState();
  49.         pdfDoc.close();
  50.     }
  51. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now