Change the Font on just the specific Unicode characters while saving to PDF
Some Unicode characters are not displayable by the user-specified font. One such Unicode character is Non-breaking Hyphen (U+2011) and its Unicode number is 8209. This character cannot be displayed with Times New Roman, but it can be displayed with other fonts like Arial Unicode MS.
When such a character occurs inside some word or sentence which is in some specific font like Times New Roman, then Aspose.Cells changes the font of the entire word or sentence to font which could display this character like Arial Unicode to MS.
However, this is undesirable behavior for some users and they want only that the specific character’s font must be changed instead of changing the font of the entire word or sentence.
To deal with this problem, Aspose.Cells provides PdfSaveOptions.setFontSubstitutionCharGranularity() property which should be set true so that only the font of the specific character which is not displayable is changed and the font for the rest of the word or sentence remains the same.
Example
The following screenshot compares the two output PDFs generated by the sample code below. One was generated without setting PdfSaveOptions.setFontSubstitutionCharGranularity() property and the other was generated after setting the PdfSaveOptions.setFontSubstitutionCharGranularity() property to true. As you can see in the first PDF, the font of the entire sentence has changed from Times New Roman to Arial Unicode MS because of Non-Breaking Hyphen. While in the second PDF, only the font of Non-Breaking Hyphen has changed.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(ChangeFontonspecificUnicodecharacters.class); | |
// Create workbook object | |
Workbook workbook = new Workbook(); | |
// Access the first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Access cells | |
Cell cell1 = worksheet.getCells().get("A1"); | |
Cell cell2 = worksheet.getCells().get("B1"); | |
// Set the styles of both cells to Times New Roman | |
Style style = cell1.getStyle(); | |
style.getFont().setName("Times New Roman"); | |
cell1.setStyle(style); | |
cell2.setStyle(style); | |
// Put the values inside the cell | |
cell1.putValue("Hello without Non-Breaking Hyphen"); | |
cell2.putValue("Hello" + (char) (8209) + " with Non-Breaking Hyphen"); | |
// Autofit the columns | |
worksheet.autoFitColumns(); | |
// Save to Pdf without setting PdfSaveOptions.IsFontSubstitutionCharGranularity | |
workbook.save(dataDir + "output.pdf"); | |
// Save to Pdf after setting PdfSaveOptions.IsFontSubstitutionCharGranularity to true | |
PdfSaveOptions opts = new PdfSaveOptions(); | |
opts.setFontSubstitutionCharGranularity(true); | |
workbook.save(dataDir + "output2.pdf", opts); |