Drawing source code with highlighted keywords using the TextLine component.
Example_32.pdf — the PDF this example creates.
package examples;
import java.io.*;
import java.util.*;
import com.pdfjet.*;
import com.pdfjet.fonts.*;
/**
* Example_32.java
*/
public class Example_32 {
public Example_32() throws Exception {
PDF pdf = new PDF(
new BufferedOutputStream(new FileOutputStream("Example_32.pdf")));
pdf.setCompliance(Compliance.PDF_UA_1);
pdf.setTitle("The Source Code of Example_02");
Font font = new Font(pdf, JetBrainsMono.Regular);
// The longest line of Example_02 is 107 characters: at 8 points a
// landscape page holds them.
font.setSize(8f);
Map<String, Integer> colors = new HashMap<String, Integer>();
colors.put("new", Color.firebrick);
colors.put("class", Color.blue);
colors.put("void", Color.green);
float[] grayColor = new float[] {0.2f, 0.2f, 0.2f};
Page page = new Page(pdf, Letter.LANDSCAPE);
float x = 50f;
float y = 50f;
// A heading on the first page, which PAC asks a document for
new TextLine(font, "The Source Code of Example_02")
.setStructureType(StructElem.H1)
.setFontSize(14f)
.setLocation(x, 32f)
.drawOn(page);
float leading = font.getBodyHeight();
List<String> lines = Content.linesOfTextFile("examples/Example_02.java");
for (String line : lines) {
new TextLine(font, line).setTextColor(grayColor).setHighlightColors(colors).setLocation(x, y).drawOn(page);
y += leading;
if (y > (page.getHeight() - 20f)) {
page = new Page(pdf, Letter.LANDSCAPE);
y = 50f;
}
}
pdf.complete();
}
public static void main(String[] args) throws Exception {
long time0 = System.currentTimeMillis();
new Example_32();
long time1 = System.currentTimeMillis();
System.out.printf("Example_32 => %4d ms%n", time1 - time0);
}
} // End of Example_32.java
©2026 PDFjet Software.