简体   繁体   中英

Itext Paragraph alignment issue in Android

I am creating PDF outfile file using itext library in android but Paragraph is not centered align while similar code is Java desktop application creates output with center align.

I have also checked by using Element.ALIGN_CENTER and Paragraph.ALIGN_CENTER but no success in android.

Android Code

Here is my code in android for creating centered align Paragraph.

 Paragraph prefaceX = new Paragraph();
 prefaceX.setAlignment(Element.ALIGN_CENTER);
 addEmptyLine(preface, 1);
 prefaceX.add(new Paragraph(getString(R.string.report_title), catFont));
 prefaceX.add(new Paragraph(getString(R.string.disclaimer), smallBoldMM));
 document.add(prefaceX);

where addEmptyLine is as follow

private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
        paragraph.add(new Paragraph(" "));
    }
}

Output PDF in android 在此处输入图片说明

Java Desktop application code

Paragraph prefaceX = new Paragraph();
prefaceX.setAlignment(Paragraph.ALIGN_CENTER);
prefaceX.add(new Paragraph("Dummy Text", catFont));
prefaceX.add(new Paragraph("* Dummy Details ", smallBoldMM));
document.add(prefaceX);

Output PDF in Java Desktop

在此处输入图片说明

Font (catFont and smallBoldMM) are custom font and both are same as follow

private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font smallBoldMM = new Font(Font.FontFamily.TIMES_ROMAN, 7,
        Font.ITALIC)

Please don't suggest to use tables.

I guess that the difference between your Android application and your Desktop application is the version of iText that is used.

You can get the same behavior by using Paragraph the way one would expect when talking about a paragraph.

Paragraph prefaceX = new Paragraph();
prefaceX.setAlignment(Element.ALIGN_CENTER);
document.add(prefaceX);
document.add(Chunk.NEWLINE);
document.add(new Paragraph(getString(R.string.report_title), catFont));
document.add(new Paragraph(getString(R.string.disclaimer), smallBoldMM));

There is no reason why you'd want to put all the different Paragraph objects into one big Paragraph .

If you take a look at iText 7 (but you're using iText 5 or earlier), you'll notice that we make a distinction between the Paragraph object (single paragraphs) and the Div object (that can contain several Paragraph and other objects).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM