我在路径src / main / resources /
中只有一个自定义字体(consolab.ttf)在我的第一个代码块中,我正在使用我的自定义字体,而在第二个代码块中,我正在从pdfbox中加载times字体。
两者在Eclipse中都能正常编译,并且我的目标pdf看起来不错。
当我导出可运行的作品时,我的第二个代码块很好,但是我的第一个代码块给了我错误
Exception in thread "main" java.lang.NullPointerException
at org.apache.fontbox.ttf.MemoryTTFDataStream.<init>(MemoryTTFDataStream.java:56)
at org.apache.fontbox.ttf.TTFParser.parse(TTFParser.java:106)
at org.apache.pdfbox.pdmodel.font.PDType0Font.load(PDType0Font.java:97)
at Pocketogram.main(Pocketogram.java:38)
不使用自定义字体
public static void main (String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/myPath/doc.pdf");
//File file = new File(source);
PDDocument document = PDDocument.load(file);
//Retrieving the pages of the document
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true
);
//Setting the font to the Content stream
InputStream consolaFontStream = Pocketogram.class.getResourceAsStream("/consolab.ttf");
PDType0Font font = PDType0Font.load(document, consolaFontStream, true);
//Begin the Content stream
contentStream.beginText();
contentStream.setFont(font, 12);
使用时代字体
public static void main (String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/myPath/doc.pdf");
//File file = new File(source);
PDDocument document = PDDocument.load(file);
//Retrieving the pages of the document
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true
);
//Begin the Content stream
contentStream.beginText();
contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
编辑,如果我更改了路径,则可以使用
InputStream consolaFontStream = Pocketogram.class.getResourceAsStream("/consolab.ttf");
收件人
InputStream consolaFontStream = Pocketogram.class.getResourceAsStream("/src/main/resources/consolab.ttf");