I have a "Lato" font installed on my system and want to replace other fonts in already existing PDF document with it. However, there are some problems which I couldn't resolve by myself nor find any fix.
I do it by iterating already existing fonts from document. For each found PdfUsedFont I extract style and size, and then I use it to create the java.awt.Font, which is needed to create the PdfTrueTypeFont. Then I just replace the already used font with the new PdfTrueTypeFont.
- Code: Select all
for (PdfUsedFont usedFont : pdfDocument.getUsedFonts()) {
try {
EnumSet<PdfFontStyle> pdfFontStyles = usedFont.getStyle();
int stylesOrSum = pdfFontStyles.stream().reduce(0, (orSum, nextStyle) -> (orSum | nextStyle.getValue()), CommonUtils::bitwiseOr);
Font awtFontToReplace = new Font(
latoFontName, //latoFontName is equal to "Lato"
stylesOrSum,
(int) usedFont.getSize());
PdfTrueTypeFont pdfTrueTypeFontToReplace = new PdfTrueTypeFont(awtFontToReplace);
usedFont.replace(pdfTrueTypeFontToReplace);
} catch (Exception e) {
logger.error("Font replacement has been failed. The old ones will be used.");
CommonUtils.logStackTrace(e);
}
}
Unfortunately, as I researched the topic, embedded fonts cannot be replaced. This is the first problem I met with, but it's not critical and I can ignore this or find other solutions. However, even if font is of "Standard" type, I can't replace it - NullPointerException occurs:
java.lang.NullPointerException
at com.spire.pdf.graphics.PdfTrueTypeFont.<init>(Unknown Source)
at com.spire.pdf.graphics.PdfTrueTypeFont.spr (Unknown Source)
at com.spire.pdf.graphics.fonts.PdfUsedFont.replace(Unknown Source)
[...]
What can be the reason of this?
Lato font is installed properly, it can be found with such code:
- Code: Select all
String latoFontName = Arrays.stream(GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames())
.filter(s->s.equalsIgnoreCase("Lato"))
.findFirst()
.orElse(null);
I got it from here: https[://]fonts[.]google[.]com/specimen/Lato
My environment is:
- zulu8.40.0.25-ca-fx-jdk8.0.222-win_i686 JRE (but I checked Oracle Java 8 and Java 11 distributions and problem was the same)
- org.eclipse.swt.win32.win32.x86 SWT 4.3 version
- spire.pdf.free from e-iceblue repository, 4.4.1 version