RTL not working in pdf generation with itext 5.5 for Arabic text

前端 未结 3 766
北恋
北恋 2020-12-04 03:14

I have java code that writes arabic characters with the help of itext 5.5 and xmlworker jars, but its writing left to right even after writer.setRunDirection(PdfWrit

3条回答
  •  误落风尘
    2020-12-04 03:33

    For developers that need an straightforward solution

    I used this trick and output is very clean and nice!

    1. create a PDFPTable with 1 column
    2. for every paragraph of your content, create a Paragraph object and set its alignment to Paragraph.ALIGN_JUSTIFIED (I don't know why but it causes to paragraph align to right of page!!!)
    3. create a PDFPCell and remove its borders using setBorder(Rectangle.NO_BORDER) and add the paragraph to cell
    4. add the cell to the table

    here is a code sample to your convenience.

    public void main(){
        /*
        * create and initiate document
        * */
        // repeat this for all your paragraphs
        PdfPTable pTable = new PdfPTable(1);
        Paragraph paragraph = getCellParagraph();
        paragraph.add("your RTL content");
        PdfPCell cell = getPdfPCellNoBorder(paragraph);
        pTable.addCell(cell);
    
        // after add all your content
        document.add(pTable);
    }
    
    private Paragraph getCellParagraph() {
        Paragraph paragraph = new Paragraph();
        paragraph.setAlignment(Paragraph.ALIGN_JUSTIFIED);
        // set other styles you need like custom font
        return paragraph;
    }
    
    private PdfPCell getPdfPCellNoBorder(Paragraph paragraph) {
        PdfPCell cell = new PdfPCell();
        cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        cell.setPaddingBottom(8);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.addElement(paragraph);
        return cell;
    }
    

提交回复
热议问题