使用Python.NET在保存为PDF时对特定Unicode字符更改字体

** 示例对比**

下方截图展示了不同设置的输出。第一个PDF显示全文字体替换,第二个PDF仅更改特定字符的字体。

全文替换 字符级替换
全文字体更改 选择性字体更改

** 实现步骤**

要启用字符级字体替换:

  1. 创建一个 Workbook 对象
  2. 使用 Worksheet.cells 属性访问工作表单元格
  3. 设置包含特殊Unicode字符的单元格值
  4. 配置 PdfSaveOptions
    • is_font_substitution_char_granularity = True
  5. 将工作簿保存为PDF格式
import os
from aspose.cells import Workbook, PdfSaveOptions

# For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
current_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(current_dir, "data")

if not os.path.exists(data_dir):
    os.makedirs(data_dir)

# Create workbook object
workbook = Workbook()

# Access the first worksheet
worksheet = workbook.worksheets[0]

# Access cells
cell1 = worksheet.cells.get("A1")
cell2 = worksheet.cells.get("B1")

# Set the styles of both cells to Times New Roman
style = cell1.get_style()
style.font.name = "Times New Roman"
cell1.set_style(style)
cell2.set_style(style)

# Put the values inside the cell
cell1.put_value("Hello without Non-Breaking Hyphen")
cell2.put_value("Hello" + chr(8209) + " with Non-Breaking Hyphen")

# Autofit the columns
worksheet.auto_fit_columns()

# Save to Pdf without setting PdfSaveOptions.is_font_substitution_char_granularity
workbook.save(os.path.join(data_dir, "SampleOutput_out.pdf"))

# Save to Pdf after setting PdfSaveOptions.is_font_substitution_char_granularity to true
opts = PdfSaveOptions()
opts.is_font_substitution_char_granularity = True
workbook.save(os.path.join(data_dir, "SampleOutput2_out.pdf"), opts)

** 关键配置**

使用以下必要的API组件:

  • 用于PDF渲染设置的 PdfSaveOptions
  • is_font_substitution_char_granularity 属性用于字符级字体替换
  • Workbook.save 方法用于输出生成