简体   繁体   中英

IText7 and missing GetPageN method in C#

I've this C# code working with iTextSharp 5 and I need to port it to IText7 .

public static PdfReader Fix(PdfReader pdfReader, int pagina)
{
    var dic = pdfReader.GetPageN(pagina);
    var resources = dic.GetAsDict(PdfName.Resources);

    var fonts = resources?.GetAsDict(PdfName.Font);
    if (fonts == null) return pdfReader;

    foreach (var key in fonts.Keys)
    {
        var font = fonts.GetAsDict(key);

        var firstChar = font.Get(PdfName.FirstChar);
        if (firstChar == null)
            font.Put(PdfName.FirstChar, new PdfNumber(32));

        var lastChar = font.Get(PdfName.LastChar);
        if (lastChar == null)
            font.Put(PdfName.LastChar, new PdfNumber(255));

        var widths = font.GetAsArray(PdfName.Widths);

        if (widths != null) continue;
        var array = Enumerable.Repeat(600, 256).ToArray();
        font.Put(PdfName.Widths, new PdfArray(array));
    }

    return pdfReader;
}

The problem I have is that the method GetPageN in this line:

var dic = pdfReader.GetPageN(pagina);

has been removed.

Have someone faced the same problem?

Indeed, now the GetPage() method is inside of the PdfDocument class.

There are also some little changes as to how you get the Dictionary entries from the document, which I took the liberty to adjust your code to.

public static PdfReader Fix(PdfReader pdfReader, int pagina)
{
    var dic = new PdfDocument(pdfReader).GetPage(pagina);
    var resources = dic.GetPdfObject().GetAsDictionary(PdfName.Resources);

    var fonts = resources?.GetAsDictionary(PdfName.Font);
    if (fonts == null) return pdfReader;

    foreach (var key in fonts.KeySet())
    {
        var font = fonts.GetAsDictionary(key);

        var firstChar = font.Get(PdfName.FirstChar);
        if (firstChar == null)
            font.Put(PdfName.FirstChar, new PdfNumber(32));

        var lastChar = font.Get(PdfName.LastChar);
        if (lastChar == null)
            font.Put(PdfName.LastChar, new PdfNumber(255));

        var widths = font.GetAsArray(PdfName.Widths);

        if (widths != null) continue;
        var array = Enumerable.Repeat(600, 256).ToArray();
        font.Put(PdfName.Widths, new PdfArray(array));
    }

    return pdfReader;
}

(I haven't checked your code, just made sure that at least what you posted now compiles)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM