0
votes

I'm working with iText in java to write PDF files. I'm trying to write a paragraph like heading and then text start very after the heading in the same line like

Heading: this a para now ...

Heading is bold and para is in normal text but I'm unable to do this using iText. I tried to use:

fonts[2] = new Font(Font.HELVETICA, 8, Font.BOLD);
Paragraph paranumber = new Paragraph(
    fonts[2].getCalculatedLeading(1),
    headingText.trim()
                + " ", fonts[0]);

Paragraph para = new Paragraph(
    fonts[0].getCalculatedLeading(1), contentText.trim(), fonts[0]);
        para.setAlignment(Element.ALIGN_JUSTIFIED);
        para.setSpacingAfter(3f);

//Now adding the para to paraNumber that is having the heading and expecting
//that it will be added very after the heading, but this does not show correct 
//result, formatting issue.

paranumber.add(para);
mct.addElement(paranumber);

I also tried to create a new paragraph and added both paras(heading para and normal text para) to that new one, but that is also not showing proper result. please see below chunk for that.

Paragraph newPara = new Paragraph();
newPara.add(paranumber);
newPara.add(para);

but this also not show proper formatting.

Or if anyone can advise me to use some other way to create PDF from HTML that will be good too, so that i may rewrite the module to create required PDF. Please advise.

1
Maybe you need Chunk of different font in the same paragraph?Jan

1 Answers

1
votes

Paragraphs typically use concepts like indentation and increased leading to set them apart visually. They are block level elements, not inline. It doesn't make sense to add a paragraph inside another paragraph. The added paragraph would typically start on a new line, essentially making it a separate paragraph anyway.

To get a paragraph with different fonts, like your example, you can use Chunks in iText. A Chunk is basically a piece of text with an associated font.

Font fontbold = new Font(BaseFont.createFont(BaseFont.HELVETICA_BOLD,
    BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);
Font fontregular = new Font(BaseFont.createFont(BaseFont.HELVETICA,
    BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);
Chunk header = new Chunk("Heading: ", fontbold);
Chunk content = new Chunk("this is a para now ...", fontregular);
Paragraph paragraph = new Paragraph();
paragraph.add(header);
paragraph.add(content);
document.add(paragraph);

The result looks like this:

Paragraph

It's not clear from your question and code sample how HTML is involved. I assume you are somehow parsing HTML input and converting the parsed content to PDF using iText Elements. This is a valid approach. Alternatively, you can look into iText XML Worker, which does XHTML (+CSS) to PDF conversion.