以下是在安卓中使用 PdfFontFactory.createFont 方法调用 assets 目录下的 otf 字体文件的详细实现 Java 代码:

  1. 首先,在 assets 目录下放置字体文件,例如 font.otf。

  2. 在项目中创建一个名为 Utils 的 Java 类。

  3. 在 Utils 类中添加以下代码:

import android.content.Context;
import android.graphics.Typeface;

import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfAppearance;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfFont;
import com.itextpdf.text.pdf.PdfFontFactory;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;

import java.io.IOException;

public class Utils {

    public static final String FONT_PATH = "font.otf";

    public static PdfPTable createTable(Context context) throws IOException {
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);

        PdfPCell cell = new PdfPCell();
        cell.setPadding(10);
        cell.setBackgroundColor(com.itextpdf.text.BaseColor.LIGHT_GRAY);
        cell.setBorder(PdfPCell.NO_BORDER);

        PdfFont font = PdfFontFactory.createFont(getFontPath(context), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        cell.setPhrase(new com.itextpdf.text.Phrase("Hello World", new com.itextpdf.text.Font(font, 16)));

        table.addCell(cell);

        return table;
    }

    public static String getFontPath(Context context) {
        return String.format("file:///android_asset/%s", FONT_PATH);
    }
}
  1. 在需要创建 PDF 文件的地方调用 createTable 方法,例如:
PdfPTable table = Utils.createTable(getContext());
document.add(table);
  1. 运行应用程序并生成 PDF 文件,将会看到字体已经被应用
安卓里面 PdfFontFactorycreateFont 调用assets目录下的otf字体文件给出详细实现的Java代码

原文地址: https://www.cveoy.top/t/topic/gtKT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录