PDFBox - Single drawString method call to generate both normal and bold font

328 views Asked by At

I am using PDFBox in my java application to generate PDF files and I am a newbie in this area. I have a requirement, where the output text content is in a variable. The output text should be a mixed of both BOLD and Normal fonts.

Code Snippet

PDDocument document = new PDDocument();
        PDPage page = new PDPage();
        document.addPage( page );

        PDFont font = PDType1Font.HELVETICA_BOLD;

        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        float xStartPos = 100;
        float yStartPos = 650;
        contentStream.beginText();
        contentStream.setFont( font, 12 );
        contentStream.moveTextPositionByAmount( xStartPos, yStartPos );
        String displayText = "Hello world";
        contentStream.drawString(displayText);
        contentStream.endText();

In the above code Hello should be in bold font and world should be in normal font. My requirement is using the single drawString call, this should be achieved. Any one can help?

Thanks in advance.

1

There are 1 answers

0
mkl On

A single drawString method call to generate both normal and bold font (as you mention in the question headline) is not possible because PDPageContentStream.drawString essentially creates one operation in the PDF drawing the whole parameter string using the current font. Thus, multiple drawString calls are required.

In your case e.g.:

contentStream.beginText();
contentStream.moveTextPositionByAmount( xStartPos, yStartPos );
contentStream.setFont( PDType1Font.HELVETICA_BOLD, 12 );
contentStream.drawString("Hello ");
contentStream.setFont( PDType1Font.HELVETICA, 12 );
contentStream.drawString("world");
contentStream.endText();