繁体   English   中英

使用 itext 在 pdf 中添加复选标记

[英]Put check mark in pdf using itext

我正在使用 iText(java 库)生成 PDF 文件。 在这里我有一段我必须在其中打勾

PdfPCell cell95 = new PdfPCell(new Paragraph((new Chunk('\u2713', FontFactory.getFont(FontFactory.HELVETICA, 11, Font.BOLD, new BaseColor(0,0,0))))));

我正在使用它,但它不起作用。

您不能将 unicode 直接用于 PDFPCell。

相反,创建复选标记的图像并将其插入 PDFPCell。

这个stackoverflow帖子itext-questions中的这个项目表明您需要使用unicode字符集而不是默认的Windows CP1252字符集来创建字体 - 尝试使用带有编码说明符的getFont重载:

FontFactory.getFont(FontFactory.HELVETICA, BaseFont.IDENTITY_H, 11, Font.BOLD, new BaseColor(0,0,0))

使用此代码:

    String FONT = "C:/dev/dejavu-fonts-ttf-2.33/ttf/DejaVuSans.ttf";
    FontSelector selector = new FontSelector();
    BaseFont base = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    selector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 12));
    selector.addFont(new Font(base, 12));
    Phrase ph = selector.process(text);
    document.add(new Paragraph(ph));

这里,重点是 1)set BaseFont.IDENTITY_H; 2)只有一些字体提供“复选标记”

试试这个解决了。 https://www.fontsquirrel.com/fonts/dejavu-sans下载 dejavu-sans。 并将其保存在本地。

使用以下代码将刻度符号写入 PDF 文档。

    private static void writeUsingIText() {


    Document document = new Document();

    try {

        PdfWriter.getInstance(document, new FileOutputStream(new File(FILE_NAME)));

        //open
        document.open();

        Paragraph p = new Paragraph();
        p.add("This is my paragraph 1");
        p.setAlignment(Element.ALIGN_CENTER);

        document.add(p);

        Paragraph p2 = new Paragraph();
        p2.add("This is my paragraph 2"); //no alignment

        document.add(p2);

        Font f = new Font();
        f.setStyle(Font.BOLD);
        f.setSize(8);

        document.add(new Paragraph("This is my paragraph 3", f));

        document.add(new Paragraph("This is my tick mark ", f));


        String FONT = "C:\\Users\\<username>\\Documents\\DejaVuSans.ttf";
        FontSelector selector = new FontSelector();
        BaseFont base = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        selector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 12));
        selector.addFont(new Font(base, 12));
        char tickSymbol=10003;
        String text = String.valueOf(tickSymbol);
        Phrase ph = selector.process(text);
        document.add(new Paragraph(ph));




        //close
        document.close();

        System.out.println("Done");

    } catch (FileNotFoundException | DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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