I am working on embedding fonts those are not embedded to PDF. For this, I am using PDFBox library to identify missing fonts using PDFont
class. Using this I am able to identify list of missing fonts. But when I am trying to embed them using my local machine font's(grabbed TTF files from my local machine fonts folder), I am not able to do it, getting following result.
I am using following code to get list of (not embedded) fonts,
private static List<FontsDetails> checkAllFontsEmbeddedOrNot(PDDocument pdDocument) throws Exception {
List<FontsDetails> notEmbFonts = null;
try {
if(null != pdDocument){
PDPageTree pageTree = pdDocument.getDocumentCatalog().getPages();
notEmbFonts = new ArrayList<>();
for (PDPage pdPage : pageTree) {
PDResources resources = pdPage.getResources();
Iterable<COSName> cosNameIte = resources.getFontNames();
Iterator<COSName> names = cosNameIte.iterator();
while (names.hasNext()) {
COSName name = names.next();
PDFont font = resources.getFont(name);
boolean isEmbedded = font.isEmbedded();
if(!isEmbedded){
FontsDetails fontsDetails = new FontsDetails();
fontsDetails.setFontName(font.getName().toString());
fontsDetails.setFontSubType(font.getSubType());
notEmbFonts.add(fontsDetails);
}
}
}
}
} catch (Exception exception) {
logger.error("Exception occurred while validating fonts : ", exception);
throw new PDFUtilsException("Exception occurred while validating fonts : ",exception);
}
return notEmbFonts;
}
Following is the code which I am using to embed fonts which I am getting from above list,
public List<FontsDetails> embedFontToPdf(File pdf, FontsDetails fontToEmbed) {
ArrayList<FontsDetails> notSupportedFonts = new ArrayList<>();
try (PDDocument pdDocument = PDDocument.load(pdf)) {
LOGGER.info("Embedding font : " + fontToEmbed.getFontName());
InputStream ttfFileStream = PDFBoxOperationsUtility.class.getClassLoader()
.getResourceAsStream(fontToEmbed.getFontName() + ".ttf");//loading ttf file
if (null != ttfFileStream) {
PDFont font = PDType0Font.load(pdDocument, ttfFileStream);
PDPage pdfPage = new PDPage();
PDResources pdfResources = new PDResources();
pdfPage.setResources(pdfResources);
PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdfPage);
if (fontToEmbed.getFontSize() == 0) {
fontToEmbed.setFontSize(DEFAULT_FONT_SIZE);
}
font.encode("ANSI");
contentStream.setFont(font, fontToEmbed.getFontSize());
contentStream.close();
pdDocument.addPage(pdfPage);
pdDocument.save(pdf);
} else {
LOGGER.info("Font : " + fontToEmbed.getFontName() + " not supported");
notSupportedFonts.add(fontToEmbed);
}
} catch (Exception exception) {
notSupportedFonts.add(fontToEmbed);
LOGGER.error("Error ocurred while embedding font to pdf : " + pdf.getName(), exception);
}
return notSupportedFonts;
}
Could someone pleas help me to identify what mistake I am doing or any other approach I will need to take.