You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android创建从右到左PDF:求推荐支持RTL的Java开源库

嘿,针对你需要在Android上用Java生成支持阿拉伯语、希伯来语等RTL(从右到左)语言PDF的需求,我整理了几个免费替代iText的方案,还有具体的实现步骤:

推荐的免费RTL支持PDF库
  • PdfBox-Android:Apache PDFBox的官方Android移植版,完全开源免费,对RTL文本的BIDI(双向文本)算法支持完善,能很好处理阿拉伯语、希伯来语的排版。
  • APW Library:轻量级的Android PDF生成库,API简洁,专门优化了移动端的PDF生成,对RTL语言的支持开箱即用。

一、使用PdfBox-Android实现RTL PDF生成

1. 添加依赖

首先在你的build.gradle(Module级别)中引入依赖:

implementation 'com.tom_roush:pdfbox-android:2.0.27.0'

2. 核心实现代码

// 1. 初始化PDF文档和页面
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);

// 2. 加载支持RTL语言的字体(比如Noto系列字体,需放在assets目录)
InputStream fontStream = getAssets().open("NotoNaskhArabic-Regular.ttf");
PDType0Font rtlFont = PDType0Font.load(document, fontStream);

// 3. 创建内容流并绘制RTL文本
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(rtlFont, 14);

// RTL文本从页面右侧开始绘制,这里设置起始坐标(右侧偏移50px,顶部偏移50px)
float startX = page.getMediaBox().getWidth() - 50;
float startY = page.getMediaBox().getHeight() - 50;
contentStream.newLineAtOffset(startX, startY);

// 直接传入阿拉伯语/希伯来语文本,PdfBox会自动处理RTL排版
String arabicText = "السلام عليكم، كيف حالك؟";
String hebrewText = "שלום עולם, איך אתה?";

contentStream.showText(arabicText);
// 换行到下一行右侧位置
contentStream.newLineAtOffset(0, -20);
contentStream.showText(hebrewText);

contentStream.endText();
contentStream.close();

// 4. 保存PDF到本地
File outputFile = new File(getExternalFilesDir(null), "rtl_pdf_box.pdf");
document.save(outputFile);
document.close();

注意事项

  • 必须使用支持目标RTL语言的字体,比如Google的Noto系列(NotoNaskhArabic、NotoHebrew),避免出现方块乱码。
  • RTL文本的起始坐标要从页面右侧计算,因为文本是从右往左排列的。

二、使用APW Library实现RTL PDF生成

APW的API更简洁,适合快速开发:

1. 添加依赖

在build.gradle中引入:

implementation 'com.github.ahmed-alamir:APW-Library:v1.0.3'

2. 核心实现代码

// 1. 初始化PDF生成器
PDFGenerator pdfGenerator = new PDFGenerator(this);
pdfGenerator.setPageSize(PDFGenerator.PageSize.A4);
pdfGenerator.setMargin(50); // 设置页面边距

// 2. 加载RTL字体
Typeface hebrewFont = Typeface.createFromAsset(getAssets(), "NotoHebrew-Regular.ttf");

// 3. 添加RTL文本,启用RTL支持并设置右对齐
pdfGenerator.addText(
    "שלום, זה דוגמה לטקסט עברי בפ"דף",
    hebrewFont,
    14,
    Color.BLACK,
    PDFGenerator.TextAlign.RIGHT,
    true // 启用RTL排版
);

// 添加阿拉伯语文本示例
Typeface arabicFont = Typeface.createFromAsset(getAssets(), "NotoNaskhArabic-Regular.ttf");
pdfGenerator.addText(
    "هذا مثال لنص عربي في ملف PDF",
    arabicFont,
    14,
    Color.DARK_GRAY,
    PDFGenerator.TextAlign.RIGHT,
    true
);

// 4. 生成并保存PDF
File outputFile = new File(getExternalFilesDir(null), "rtl_apw.pdf");
pdfGenerator.generatePDF(outputFile);

注意事项

  • 添加文本时务必将最后一个参数设为true,开启RTL排版支持。
  • 同样需要确保字体支持目标RTL语言。

内容的提问来源于stack exchange,提问作者Lior I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:21:39