【问题标题】:How to convert Windows Font to iText.Kernel.Font.PdfFont如何将 Windows 字体转换为 iText.Kernel.Font.PdfFont
【发布时间】:2018-01-26 14:56:03
【问题描述】:

我在 .Net 中使用 iText.Kernel 库,我需要从 Windows 字体(从 TextBlock 获取)的段落中设置字体。

有人知道如何将 Windows 字体转换为 iText.Kernel.Font.PdfFont 吗?

谢谢。

【问题讨论】:

  • 解释“从 TextBlock 获得”。你有.ttf.otf.ttc 文件的路径吗? (因为 Windows 上的字体以此类文件的形式存储在 Windows 字体目录中,例如在 C:\Windows\fonts 中)
  • @Bruno Lowagie:当我说“来自 Textblock”时:TextBlock 具有 FontSize、FontStyle、FontFamily、FontStretch 和 FontWeight 属性。我认为字体是由这些属性定义的,我搜索以在 PdfFont 中转换此属性。我没有字体路径,但如果我可以转换这些属性以找到路径,它可以是一个解决方案。

标签: .net pdf itext


【解决方案1】:

在 Bruno Lowagie 的帮助下找到的解决方案

  • 在创建 PDF 之前,注册所有字体:

        PdfFontFactory.RegisterSystemDirectories()
    
  • 我将以下文本块属性存储在自定义类中(在我的例子中是 ptb 命名变量):FontWeight、FontStyle、FontSize、FontFamily

  • 我创建了一个将 System.Windows.FontWeight 转换为 Integer 的方法(值代表 PDF FontStyle):

    Public Function ConvertWeightToPdfStyleInteger(p_originalWeight As System.Windows.FontWeight, Optional p_isItalic As Boolean = False) As Integer
    Select Case p_originalWeight
        Case Windows.FontWeights.Normal
            If p_isItalic Then
                Return 2 'ITALIC
            Else
                Return 0 'NORMAL
            End If
        Case Windows.FontWeights.Bold
            If p_isItalic Then
                Return 3 'BOLDITALIC
            Else
                Return 1 'BOLD
            End If
        Case Else
            If p_isItalic Then
                Return 2 'ITALIC
            Else
                Return -1 'UNDEFINED
            End If
    End Select
    End Function
    

我找到了等效的整数值here

  • 我调用了 CreateRegisteredFont() 方法从 Windows 字体创建 PDF 字体:

    Dim font As PdfFont = PdfFontFactory.CreateRegisteredFont(ptb.FontFamily.ToString(), PdfEncodings.IDENTITY_H, True, FontHelper.ConvertWeightToPdfStyleInteger(ptb.FontWeight, (ptb.FontStyle = Windows.FontStyles.Italic)))
    
  • 我将 PDF 字体应用于我的段落:

    Dim para As Paragraph = New Paragraph(ptb.Text).SetFont(font)
    

而且它的工作发现。我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    请查看FontProgramFactory

    您确实需要一个字体程序(存储在.ttf.otf.ttc、...文件中),但如果您不想通过将路径传递给此类来创建PdfFont一个文件,您可以将字体文件和字体目录注册到FontProgramFactory(例如使用registerFontDirectory()registerFont()registerFontFamily()方法)。

    注册字体文件后,您可以使用createRegisteredFont(String fontName, int style)等方法创建您需要的PdfFont实例PdfFont

    显然,字体大小不是字体的属性。那会很愚蠢,因为这意味着您需要为每种不同的字体大小使用不同的字体。

    在评论中,您还谈到了 CSS 属性,例如 font-weight。您可能会受益于阅读 HTML 到 PDF 教程,例如 chapter about fonts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2019-08-19
      相关资源
      最近更新 更多