Как переопределить метод C # под ironPython - PullRequest
0 голосов
/ 01 февраля 2012

Я хочу реализовать iTextSharp FontProvider в ironPython, следуя этому сообщению iText + HTMLWorker - Как изменить шрифт по умолчанию? .

Мой код всегда выбрасывает: TypeError: GetFont () принимает ровно 8 аргументов (дано 7).

$ ipy itexthtml.py
[INFO] __init__ .. AngsanaUPC
Traceback (most recent call last):
  File "itexthtml.py", line 74, in <module>
  File "itexthtml.py", line 65, in main
TypeError: GetFont() takes exactly 8 arguments (7 given)

Не знаю, что не так, Можно ли помочь?

Мой код Python.

import clr

clr.AddReference("itextsharp")

from iTextSharp.text import Document, PageSize, FontFactoryImp
from iTextSharp.text.pdf import PdfWriter
from iTextSharp.text.html.simpleparser import HTMLWorker,StyleSheet
from System.Collections.Generic import List, Dictionary
from System.IO import FileStream, MemoryStream, FileMode, SeekOrigin, StreamReader
from System.Text import UTF8Encoding
from System import String, Object

class DefaultFontProvider (FontFactoryImp) :

    def __init__(self, string_def) :

        print "[INFO] __init__ ..", string_def
        self.default = string_def

    def GetFont(self, fontname,  encoding,  embedded,  size,  style,  color,  cached) :
        print "[INFO] getFont ..", fontname

        if (fontname == None) :
            fontname = self.default

        print "[INFO] return .."
        return super(DefaultFontProvider, self).GetFont(fontname, encoding, embedded, size, style, color, cached)


def main() :

    output_pdf_file = "test.pdf"
    f = open("test.html", "r")
    html_data = f.readlines()
    html_data = "".join(html_data)

    document =  Document(PageSize.A4);
    PdfWriter.GetInstance(document, FileStream(output_pdf_file, FileMode.Create))
    document.Open()

    providers = Dictionary[String,Object]()
    providers.Add(HTMLWorker.FONT_PROVIDER, DefaultFontProvider("AngsanaUPC"));

    h = HTMLWorker(document)

    h.SetInterfaceProps(providers)

    file_list = List[String]()

    styles = StyleSheet();
    #styles.LoadTagStyle("body", "font-family", "AngsanaUPC");
    #styles.LoadTagStyle("body", "font-face", "AngsanaUPC");

    for idx in range(1) :

        document.NewPage()

        mem = MemoryStream()
        b = UTF8Encoding.UTF8.GetBytes(html_data)
        mem.Write(b, 0, b.Length)
        mem.Seek(0, SeekOrigin.Begin)

        sr = StreamReader(mem, UTF8Encoding.UTF8, styles)
        h.Parse(sr)

        sr.Dispose()
        mem.Dispose()

    document.Close()


if __name__ == "__main__" :
    main()

И определение класса iTextSharp FontFactoryImp.

public class FontFactoryImp : IFontProvider
{
    // Fields
    private bool defaultEmbedding;
    private string defaultEncoding;
    private Dictionary<string, List<string>> fontFamilies;
    private static readonly ILogger LOGGER;
    private Dictionary<string, string> trueTypeFonts;
    private static string[] TTFamilyOrder;

    // Methods
    static FontFactoryImp();
    public FontFactoryImp();
    public virtual Font GetFont(string fontname);
    public virtual Font GetFont(string fontname, float size);
    public virtual Font GetFont(string fontname, string encoding);
    public virtual Font GetFont(string fontname, float size, BaseColor color);
    public virtual Font GetFont(string fontname, float size, int style);
    public virtual Font GetFont(string fontname, string encoding, bool embedded);
    public virtual Font GetFont(string fontname, string encoding, float size);
    public virtual Font GetFont(string fontname, float size, int style, BaseColor color);
    public virtual Font GetFont(string fontname, string encoding, bool embedded, float size);
    public virtual Font GetFont(string fontname, string encoding, float size, int style);
    public Font GetFont(string fontname, string encoding, bool embedded, float size, int style);
    public virtual Font GetFont(string fontname, string encoding, float size, int style, BaseColor color);
    public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color);
    public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached);
    public virtual bool IsRegistered(string fontname);
    public virtual void Register(string path);
    public virtual void Register(string path, string alias);
    public virtual int RegisterDirectories();
    public virtual int RegisterDirectory(string dir);
    public int RegisterDirectory(string dir, bool scanSubdirectories);
    public void RegisterFamily(string familyName, string fullName, string path);

    // Properties
    public virtual bool DefaultEmbedding { get; set; }
    public virtual string DefaultEncoding { get; set; }
    public virtual ICollection<string> RegisteredFamilies { get; }
    public virtual ICollection<string> RegisteredFonts { get; }
}

Ответы [ 2 ]

1 голос
/ 01 февраля 2012

Я не гуру IronPython (или даже Python), но я столкнулся с подобной проблемой пару лет назад, когда играл с IronPython как легким инструментом тестирования кода библиотеки C #.

Насколько я помню, проблема для меня заключалась в том, что я вызывал метод экземпляра статическим образом, поэтому «отсутствующий» аргумент был экземпляром класса.

Я написал об этом в блоге здесь, этого было достаточно, чтобы вызвать мою память, но я, видимо, не думал, что это было достаточно важно, чтобы показать фактическое исправление.

Не полное решение вашей проблемы, я знаю, но, возможно, это так 'дам вам указатель на правильное решение.Мне кажется, что вызов super () может вызываться статическим способом (т. Е. «Вызывать метод foo родительского класса этого экземпляра», когда у вас фактически нет экземпляра родительского класса для вызова GetFont () в).

0 голосов
/ 30 октября 2012

Вместо:

 return super(DefaultFontProvider, self).GetFont(fontname, encoding, embedded, size, style, color, cached)

использование:

return DefaultFontProvider.GetFont(self, fontname, encoding, embedded, size, style, color, cached)
...