can I use PdfSharpCore with .net maui

1.4k Views Asked by At

I am trying to use PdfSharpCore and MigraDocCore to create a pdf file in .net maui with vs pre 2022

this is my code

using System;
using System.Diagnostics;
using System.Windows.Input;
using MigraDocCore.DocumentObjectModel;
using MigraDocCore.Rendering;
using PdfKit;
using PdfSharpCore;
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;

private void CreatePdf()
        {           System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            PdfSharpCore.Pdf.PdfDocument document = new PdfSharpCore.Pdf.PdfDocument();

            PdfSharpCore.Pdf.PdfPage page = document.AddPage();

            PdfSharpCore.Drawing.XGraphics gfx = XGraphics.FromPdfPage(page);
            gfx.MUH = PdfFontEncoding.Unicode;

            var ren = new PdfDocumentRenderer(true);

            XFont font = new XFont("OpenSans-Semibold", 20, XFontStyle.Bold);

            gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height));
            }

but I have an error with XFont

static void Main(string[] args)
    {
        // if you want to use a different Application Delegate class      from "AppDelegate"
        // you can specify it here.
        UIApplication.Main(args, null, typeof(AppDelegate));
    }
1

There are 1 best solutions below

1
On BEST ANSWER

you need create the file FileFontResolver.

public class FileFontResolver: IFontResolver
{
    public FileFontResolver()
    {
    }

    public string DefaultFontName => throw new NotImplementedException();

    public byte[] GetFont(string faceName)
    {
        var assembly = this.GetType().GetTypeInfo().Assembly;
        var directory = $"MyApp.Resources.Fonts.{faceName}.ttf";
        var stream = assembly.GetManifestResourceStream(directory);

        using (var reader = new StreamReader(stream))
        {
            var bytes = default(byte[]);

            using (var ms = new MemoryStream())
            {
                reader.BaseStream.CopyTo(ms);
                bytes = ms.ToArray();
            }

            return bytes;
        }
    }

    public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
    {
        return new FontResolverInfo(familyName);
    }
}.

And Then, i call this file in app.xaml.cs

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        GlobalFontSettings.FontResolver = new FileFontResolver();
        MainPage = new AppShell();
    }
}