您现在的位置是:首页 >  云笔记 >  开发笔记 >  文章详情

Apache PDFBox 3.0字体使用介绍

豆豆   2023-09-15 16:51:23   3639人已围观

一、使用Apache PDFBox默认字体

    public void createPDF(String filePath, String conttext) {
        try {
            PDDocument document =new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.beginText();
              //设置pdfbox默认字体(此字体不支持中文)
              PDType1Font font2 =new PDType1Font(Standard14Fonts.FontName.COURIER);
                contentStream.setFont(font2, 12);
                contentStream.newLineAtOffset(100, 700);
                contentStream.showText(conttext);
                contentStream.endText();
                contentStream.close();
                document.save(filePath);
                document.close();
                System.out.println("PDF created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

二、使用字体文件加载字体

       我这里是以pdfbox.jar文件中自带的一个字体ttf文件作为开发的例子,如果你喜欢其他的字体也可以下载字体文件后用类似的方法加载使用

    public void createPDF(String filePath, String conttext) {
        try {
            PDDocument document =new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.beginText();
              //设置pdfbox自带字体文件(此字体不支持中文)
              PDFont font = PDType0Font.load(document, this.getClass().getResourceAsStream(
                      "/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"));
                contentStream.setFont(font, 12);
                contentStream.newLineAtOffset(100, 700);
                contentStream.showText(conttext);
                contentStream.endText();
                contentStream.close();
                document.save(filePath);
                document.close();
                System.out.println("PDF created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

三、常见字体文件下载

分享到:

编辑发布时间:2023-09-15 16:51:23