使用Aspose.PDF在段落中附加文本

时间:2013-03-08 16:40:52

标签: .net-3.5 aspose

我想做一些非常简单的事情,但我不知道如何做。这变得非常烦人,这是我的问题。

我想在aspose.pdf部分中添加以下文本

 "<h1>What a nice <i>italic</i> freaking title</h1>"

由于apsose的PDF生成不能正确支持css样式,因此我的团队决定采用不同的方法,即:支持基本的html元素,并使用具有预定义样式的aspose对象库直接添加它们代码。现在,我使用以下函数添加标题:

    public static void AddTitle(XElement xElement, Section section, TitleType type)
    {
        Text title;
        title = xElement.HasElements ? new Text(section, GetFullValue(xElement)) : new Text(section, xElement.Value);
        var info = new TextInfo();
        switch(type)
        {
            case TitleType.H1:
                info.FontSize = 22;
                break;
            case TitleType.H2:
                info.FontSize = 20;
                break;
            case TitleType.H3:
                info.FontSize = 18;
                break;
            case TitleType.H4:
                info.FontSize = 16;
                break;
            case TitleType.H5:
                info.FontSize = 14;
                break;
        }

        info.IsTrueTypeFontBold = true;
        title.IsKeptTogether = true;
        //title.IsHtmlTagSupported = true;
        title.TextInfo = info;
        section.Paragraphs.Add(title);
    }

BTW:在这个例子中传递给文本对象的内容是“这是一个很好的斜体怪异的标题”

目前,斜体不起作用。如果我取消注释.IsHtmlTagSupported,斜体将起作用,但我正在丢失我的TextInfo(粗体,字体大小等)。有没有办法让这项工作?或者,有没有办法在具有不同样式的单个段落中附加文本。 (我可以将另一个Text对象添加到包含斜体文本的段落中)

1 个答案:

答案 0 :(得分:4)

在Aspose.Pdf for .NET 7.7.0中使用以下简单代码时,我可以看到斜体文本和H1中的所有字符串。使用IsHtmlTagSupported时,建议使用HTML标签指定文本格式(Bold,FontSize等)。

Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();
Text title = new Text("<h1>What a nice <i>italic</i> freaking title</h1>");
var info = new TextInfo();
info.FontSize = 12;
//info.IsTrueTypeFontBold = true;
title.TextInfo = info;

title.IsHtmlTagSupported = true;

sec1.Paragraphs.Add(title);
pdf1.Save("c:/pdftest/PDF_From_HTML.pdf");

此外,Text段落可以包含一个或多个Segment对象,您可以为每个段指定不同的格式。为了满足您的要求,您可以尝试使用以下代码段

Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();
Text title = new Text("What a nice");

var info = new TextInfo();
info.FontSize = 12;
info.IsTrueTypeFontBold = true;
title.TextInfo = info;

Segment segment2 = new Segment(" italic ");
// set the formatting of segment2 as Italic
segment2.TextInfo.IsTrueTypeFontItalic = true;
// add segment2 to segments collection of text object
title.Segments.Add(segment2);

Segment segment3 = new Segment(" freaking title ");
// add segment3 to segments collection of text object
segment3.TextInfo.IsTrueTypeFontBold = true;
title.Segments.Add(segment3);

sec1.Paragraphs.Add(title);
// save the output document
pdf1.Save("c:/pdftest/PDF_with_Three_Segments.pdf");