【问题标题】:How to make Cyrillic characters display correctly when converting to PDF with itextpdf?使用 itextpdf 转换为 PDF 时如何使西里尔字符正确显示?
【发布时间】:2017-05-10 22:50:49
【问题描述】:

有没有人知道如何让 itextpdf 使用西里尔符号?

I have code: 

 Font normal = FontFactory.getFont(String.valueOf(Font.FontFamily.HELVETICA), "CP1251", false, 13);
 Document doc = new Document(PageSize.A4, 36, 36, 36, 65);
 Paragraph paragraph = new Paragraph("ЗАПИСЬ!!!", normal);
 doc.add(paragraph);

我看到 CP1251 工作良好,但对于单个字符 - 而对于文本 - (在我的示例中为“ЗАПИСЬ”)。它会显示所有相互重叠的字符。

我的代码有什么问题? 谢谢!

【问题讨论】:

  • 使用支持这些字符的字体,例如 arial.ttf,采用 Unicode 编码。
  • @PauloSoares 评论顶部的额外说明:如果您使用 arial 以外的其他东西以确保它在任何地方都能正常工作,您可能还想嵌入您选择的 ttf 前端。 BaseFont bf_russian = BaseFont.createFont("location/of/your/font.ttf", "CP1251", BaseFont.EMBEDDED); Font normal = new Font(bf_russian, 12);

标签: java pdf itext cp1251


【解决方案1】:

您可以从网络(http://fonts4web.ru/Helvetica.html#test)下载字体源。

将字体保存在资源目录中。

如下例所示:

public class HelloWorld {

    /** Path to the resulting PDF file. */
    public static final String RESULT = "results/hello.pdf";
    public static final String FONT = "fonts/HelveticaRegular.ttf";

    /**
     * Creates a PDF file: hello.pdf
     * @param    args    no arguments needed
     */
    public static void main(String[] args)
            throws DocumentException, IOException {
        new HelloWorld().createPdf(RESULT);
    }

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException
     * @throws    IOException
     */
    public void createPdf(String filename)
            throws DocumentException, IOException {
        Font font = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, true);

        Document document = new Document();

        PdfWriter.getInstance(document, new FileOutputStream(filename));

        document.open();

        document.add(new Paragraph("Hello World! Ты можешь использовать кирилицу.", font));

        document.close();
    }
}

【讨论】:

  • 太棒了!作品!谢谢你。
猜你喜欢
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
相关资源
最近更新 更多