如何在iTextSharp字符串中使用HTML标记

时间:2012-10-28 19:20:02

标签: c# html-parsing itextsharp

我有一个像这样的iTextSharp页脚模板方法:

public PdfTemplate footerTemplate(){
    PdfTemplate footer = cb.CreateTemplate(500, 50);
    footer.BeginText();
    BaseFont bf2 = BaseFont.CreateFont(BaseFont.TIMES_ITALIC, "windows-1254", BaseFont.NOT_EMBEDDED);
    footer.SetFontAndSize(bf2, 11);
    footer.SetColorStroke(BaseColor.DARK_GRAY);
    footer.SetColorFill(BaseColor.GRAY);
    int al = -200;
    int v = 45 - 15;
        float widthoftext = 500.0f - bf2.GetWidthPoint(footerOneLine[0], 11);
        footer.ShowTextAligned(al, footerOneLine[0], widthoftext, v, 0);
    footer.EndText();
    return footer;
}

footerTemplate()正在获取这样的字符串:

footerOneLine.Add("<b>All this line is bold, and <u>this is bold and underlined</u></b>");

我还有另一种方法可以将字符串转换为HTML。方法是:

private Paragraph CreateSimpleHtmlParagraph(String text) {
    //Our return object
    Paragraph p = new Paragraph();

    //ParseToList requires a StreamReader instead of just text
    using (StringReader sr = new StringReader(text)) {
        //Parse and get a collection of elements
        List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);
        foreach (IElement e in elements) {
            //Add those elements to the paragraph
            p.Add(e);
        }
    }
    //Return the paragraph
    return p;
}

问题:我没有设法在上面的代码中使用CreateSimpleHtmlParagraph方法。 footer.ShowTextAligned(al, footerOneLine[0], widthoftext, v, 0);方法的数据类型为footer.ShowTextAligned(int, string, float, float, float); 你能帮我解决一下如何在上面的代码中使用CreateSimpleHtmlParagraph方法吗? 亲切的问候。

1 个答案:

答案 0 :(得分:0)

我并不完全知道您如何使用PdfTemplate,但是您正在混合iTextSharp的文本抽象,例如Paragraph和{{1}使用Chunk之类的原始PDF命令。抽象最终使用原始命令,但可以方便地帮助您思考像您通常需要手动计算的换行符和当前坐标。

好消息是,有一个名为ShowText()的抽象直接与ColumnText对象一起工作,只要您愿意接受您有一个固定的矩形来绘制文本

PdfWriter.PdfContentByte