Search code examples
javaapachepdfpdfboxtext-formatting

Equally Space the characters in Apache PDF Box PDF creation


I am trying to create PDF file using Apache PDFBox and the content is plain text message of 80 chars per line. When I tried to create the PDF , I noticed that the space , _ and other characters occupy different amount of width on the line and I couldn't format them equally like how we do in text editors. Can somebody help me to format them ?

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;


public class SampleTest {
    public static void main(String[] args) throws Exception {
        PDDocument document = new PDDocument();     
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);     
        String text =   "---------------------------\n" +
                        "------------ABC------------\n" +
                        "A                         B\n" +
                        "***************************\n" +   
                        "A  B  C  D  E  F  G  H  I  \n" +
                        "---------------------------";
        String[] textArray = text.split("\n");

        PDPageContentStream contentStream = new PDPageContentStream(document, page);        
        contentStream.beginText();      
        contentStream.setFont( PDType1Font.TIMES_ROMAN, 10 );
        contentStream.setLeading(4f);
        contentStream.newLineAtOffset(40, 750);  

        for(String line : textArray){
            contentStream.showText(line);
            contentStream.newLine();
            contentStream.newLine();    
        }
        contentStream.endText();
        contentStream.close();

        document.save("C:\\PDF-Samples\\file.pdf");
        document.close();
        System.out.println("Done");
    }
}

Solution

  • To do that you need to change the font to a fixed-width one (like PDType1Font.html.COURIER).

    Some reading: https://en.wikipedia.org/wiki/Monospaced_font


    To compute the text width, you can use:

    // result in unit of text space, suitable to use with moveTextPositionByAmount()
    (font.getStringWidth(text) / 1000.0f) * (1.0f * fontSize) // font is a PDFont