在保存为PDF时仅更改特定Unicode字符的字体
一些Unicode字符无法使用用户指定的字体显示。其中一个这样的Unicode字符是非间断连字(U+2011),其Unicode编号为8209。这个字符不能用Times New Roman显示,但可以用其他字体如Arial Unicode MS显示。
当这样一个字符出现在某个特定字体(如Times New Roman)的单词或句子中时,Aspose.Cells会将整个单词或句子的字体更改为可显示此字符的字体,如Arial Unicode MS。
然而,这对一些用户来说是不希望的行为,他们只希望特定字符的字体更改,而不是更改整个单词或句子的字体。
为了解决这个问题,Aspose.Cells提供了PdfSaveOptions.setFontSubstitutionCharGranularity()属性,应设置为true,以便仅更改无法显示的特定字符的字体,而保持单词或句子的其余部分的字体不变。
示例
以下屏幕截图比较了以下样本代码生成的两个输出PDF。一个是在未设置PdfSaveOptions.setFontSubstitutionCharGranularity()属性的情况下生成的,另一个是在将PdfSaveOptions.setFontSubstitutionCharGranularity()属性设置为true后生成的。如您在第一个PDF中可以看到,由于非间断连字,整个句子的字体已从Times New Roman更改为Arial Unicode MS。而在第二个PDF中,仅非间断连字的字体已更改。
// 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); | |