0
votes

I create a PDF document using itextsharp and I need to connect the fonts from the Assets folder. At the moment everything works when I throw fonts in the memory of the smartphone.

System.String ttf = Android.OS.Environment.ExternalStorageDirectory + 
"/arial.ttf";
var baseFont = BaseFont.CreateFont(tttt, BaseFont.IDENTITY_H, 
BaseFont.NOT_EMBEDDED);
var font = new Font(baseFont, Font.DEFAULTSIZE, Font.NORMAL);

doc.Add(new Paragraph(inf1, font));

But probably no one has these fonts in the memory of the smartphone :)

I tried to get the path to the Assets folder using the following code:

public static AssetManager Assets { get; private set; }

string ttf;
using (var asset = Assets.Open("arial.ttf"))
{
    var fontStream = new MemoryStream();
    asset.CopyTo(fontStream);
}

or another option:

string content;
using (StreamReader sr = new StreamReader(Assets.Open("arial.ttf")))
{
    content = sr.ReadToEnd();
}

but in these cases there is a problem: object reference not set to an instance of an object... on line

using (var asset = Assets.Open("arial.ttf")) 

and

using (StreamReader sr = new StreamReader(Assets.Open("arial.ttf")))

Maybe there is some analog of the folder path, similar to the path to the Font in Windows ?

Environment.GetFolderPath(Environment.SpecialFolder.Fonts);

or maybe I can somehow use the resulting TypeFace

Android.Graphics.Typeface tf = Android.Graphics.Typeface.CreateFromAsset(Application.Context.Assets, "arial.ttf"); 

Tell me, please, how do I set the necessary fonts in a PDF document or how to find the path to the fonts ttf, that would be inserted into the line BaseFont :)

2
Try whether "file:///android_asset/fileName" is the right pathLeo Zhu - MSFT
@LeoZhu Doesn't find such a path :( And similar tooИгорь Ибрагимов

2 Answers

0
votes

The problem with your above code in my understanding when you say it gives you object reference not set to an instance of an object. error, which means that you are not assigning a value to it and its null what you need to do to overcome that is simple;

After declaring the property

 public AssetManager AppAssets { get; private set; }

In your class constructor assign it a value:

AppAssets= this.ApplicationContext.Assets; // In an activity
AppAssets= this.Activity.ApplicationContext.Assets; // In a fragment

Once you do this the object reference error should go away,

Goodluck revert in case of queries.

0
votes

I guess the problem is that BaseFont.CreateFont() Wants to get path to the font file not a stream.

I am also facing this issue. It works for sdcard but how to make it read from assets folder i do not know. As a workaround i copy it to the documents folder.