Center and format text with OpenPDF

2.1k Views Asked by At

I created a PDF file in Java using OpenPDF and inserted a paragraph. The problem is that I want to place it in the middle, not on the left. How can this be done?

Second question: How can I place a word with specific formatting in the test?
For example: "Hello and welcome" (welcome should be bold)

This is my code:

Document document = new Document();
String PDFPath = "output.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
document.open();
document.add(p1);
document.close();
2

There are 2 best solutions below

0
On

Your first line had some weird declaration, but this should work:

Document document = new Document();
String PDFPath = "D:\\test.pdf";
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFPath));
Font font_bold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD, Color.BLACK);
Font font_normal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL, Color.BLACK);
Paragraph p1 = new Paragraph("Ordonnance", font_bold);
p1.setAlignment(Element.ALIGN_CENTER);
document.open();
document.add(p1);
document.close();

You just have to set the alignment of the paragraph

0
On

You need to define the alignment if you want to have the paragraph centred:
p1.setAlignment(Element.ALIGN_CENTER);

To apply formatting to some parts of the text, you can divide it into several chunks. A Chunk in OpenPDF is a string with a certain Font. Instead of adding a String (unformatted) to the paragraph, you add a Chunk-object like new Chunk("Hello and ", fontNormal) which defines the text and the font to be used.

Here is the code for what you want to do according to the question:

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();

Font fontNormal = new Font(Font.TIMES_ROMAN, 15, Font.NORMAL);
Font fontBold = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);

Paragraph p1 = new Paragraph();
p1.setAlignment(Element.ALIGN_CENTER);
p1.add(new Chunk("Hello and ", fontNormal));
p1.add(new Chunk("welcome", fontBold));
document.add(p1);

document.close();

The result looks like this:

result