Search code examples
javapdfitext

coloring certain keywords in itext


The program has to turn a existing Java file (.java) into a PDF. But inside of the PDF, certain keywords have to be colored (int, double, new, ...) like in Netbeans (which I am using). So until now I turned the java file to a string and colored the keywords inside of the string with the ANSI color. But when transitioning to the PDF I can't keep the keywords colored.

Here is my marking/coloring of the keywords in the String:

public static String markKeywords(String doc, String keywords){

    String[] keywordsarr = keywords.split(",");
    
    for(int i = 0; i<keywordsarr.length;i++){
        String old = " " + keywordsarr[i] + "" ;
        String neu = " \u001B[34m" + keywordsarr[i] + "\u001B[0m";
        doc = doc.replace(old,neu);
    }
    return doc;
}

And here the transitioning to the pdf:

public static void createPDF(String doc,String loc){
    try{
        //Font font = new Font(FontFamily.COURIER, 13, Font.NORMAL, BaseColor.BLACK);
        //Create Font with Encoding
        BaseFont fontstd = BaseFont.createFont("C:\\Windows\\Fonts\\cour.ttf", BaseFont.WINANSI,
        BaseFont.EMBEDDED);
        Font font_std = new Font(fontstd, 13);
        
        //Saving pdf file in the same folder
        String targetloc = loc.replace(".java", ".pdf"); 
        
        //creating pdf
        Document document = new Document();            
        PdfWriter.getInstance(document, new FileOutputStream(targetloc));
        
        document.open();
        Paragraph p = new Paragraph();
        
        p.add(new Chunk(doc, font_std));
        document.add(p);
        document.close();
        
    }catch(Exception e){
        e.printStackTrace();
    }
}

The scripts I have to turn into PDFs are very basic, consisting only of a main and a few other methods. I also haven't found something in itext like String.replace()" which would be really great if I could change the color of the keywords that way in itext.


Solution

  • Thank you to El-Dow for the inspiration of the code. I added some Improvements, so that the lines aren´t overlapping. i also added some conditions for splitting the String, for Excample on "double[]" only "double" has to be colourded and not the Brackets.

    public static void createPDF(String doc,String loc){
        try{
            //Font font = new Font(FontFamily.COURIER, 13, Font.NORMAL, BaseColor.BLACK);
             // Font for regular text
            BaseFont fontStd = BaseFont.createFont("C:\\Windows\\Fonts\\cour.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
            Font fontRegular = new Font(fontStd, 13);
    
            // Font for keyword text
            Font fontKeyword = new Font(fontStd, 13, Font.BOLD, new BaseColor(0, 0, 255)); // blue color
            
            //Saving pdf file in the same folder
            String targetloc = loc.replace(".java", ".pdf"); 
            
            //creating pdf
            Document document = new Document();            
            PdfWriter.getInstance(document, new FileOutputStream(targetloc));            
            document.open();
            
            //Split the document into words          
            String[] words = doc.split("(?=\\[)|(?=\\.)|(?<=\\()|(?=\\=)|(?<=\\n+)|(?= )|(?<= )");
            //Split only by keywords doesn´t work, because some contain others "do" and "double"
            
            // Add each word to the document as a chunk with the appropriate font
            for (String word : words) {
                if (isKeyword(word)) {
                    Chunk chunk = new Chunk(word, fontKeyword);
                    document.add(new Phrase(chunk));
                } else {
                    Chunk chunk = new Chunk(word, fontRegular);
                    document.add(new Phrase(chunk));
                }
            }
    
            document.close();
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    private static boolean isKeyword(String word){
        String keywords = "abstract,continue,for,new,switch,assert,default,if,package,synchronized,boolean,goto,privat,this,break,double,implements,protected,throw,byte,else,import,public,throws,case,enum,instanceof,return,transient,catch,extends,int,short,try,char,final,interface,static,void,class,finally,long,strictfp,volatile,const,float,native,super,while,do";
        String[] keywordsarr = keywords.split(",");
        for (String keyword : keywordsarr){
            if(keyword.equals(word)){
                return true;
            }
        }
        return false;        
    }