0

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");
    }
}
Raja
  • 627
  • 1
  • 9
  • 24

1 Answers1

1

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
  • Thanks for the help ! It worked. Do you know if any framework can equally space the content to fill the line ? – Raja Dec 08 '16 at 12:38
  • I mean scaling the text line. – Raja Dec 08 '16 at 12:40
  • 2
    No framework for that. You need to use math, i.e. get the string length, the line length, and calculate a font size (or space size between glyphs). PDFBox is rather low level, unlike itext. – Tilman Hausherr Dec 08 '16 at 13:16
  • 1
    @Raja you might be interested in [this answer](http://stackoverflow.com/a/20681996/1729265). – mkl Dec 08 '16 at 20:56