如何在Xamarin.Forms中打印图像?

问题描述 投票:0回答:1

我需要在Xamarin.Forms应用程序中打印一张图片。我知道每个平台的情况不同,所以我这样做了。

if (Device.RuntimePlatform == Device.iOS)
    {
                    //code for iOS (works)
                    var printInfo = UIPrintInfo.PrintInfo;
                    printInfo.JobName = "myJobName";
                    printInfo.OutputType = UIPrintInfoOutputType.General;

                    var printer = UIPrintInteractionController.SharedPrintController;
                    printer.PrintInfo = printInfo;
                    printer.PrintingItem = NSData.FromFile("imagePath");
                    printer.ShowsPageRange = true;

                    printer.Present(true, (handler, completed, error) =>
                    {
                        if (!completed && error != null)
                        {
                            Console.WriteLine(error.LocalizedDescription)
                        }
                    });

                    printInfo.Dispose();
    }
else   
    {
            //code for Android (does not work)
            DependencyService.Get<IPrint>().Print(myimageArray);
    }

它在iOS平台上工作得很好 但在Android平台上却出现了以下错误: System.NullReferenceException

这是我的打印接口。

using System;
namespace myApp.Interfaces
{
    public interface IPrint
    {
        void Print(byte[] content);
    }
}

这里是Android的Print类。

using System;
using System.IO;
using Android.Content;
using Android.Print;
using myApp.Interfaces;
using Xamarin.Forms;

namespace myApp.Droid
{
    public class Print : IPrint
    {
        [Obsolete]
        void IPrint.Print(byte[] content)
        {
            //Android print code goes here
            Stream inputStream = new MemoryStream(content);
            string fileName = "form.pdf";
            if (inputStream.CanSeek)
                //Reset the position of PDF document stream to be printed
                inputStream.Position = 0;
            //Create a new file in the Personal folder with the given name
            string createdFilePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName);
            //Save the stream to the created file
            using (var dest = System.IO.File.OpenWrite(createdFilePath))
                inputStream.CopyTo(dest);
            string filePath = createdFilePath;
            PrintManager printManager = (PrintManager)Forms.Context.GetSystemService(Context.PrintService);
            PrintDocumentAdapter pda = new CustomPrintDocumentAdapter(filePath);
            //Print with null PrintAttributes
            printManager.Print(fileName, pda, null);
        }
    }
}

这里是CustomPrintDocumentAdapter:

using System;
using Android.OS;
using Android.Print;
using Java.IO;

namespace myApp.Droid
{
    public class CustomPrintDocumentAdapter : PrintDocumentAdapter
    {
        internal string FileToPrint { get; set; }

        internal CustomPrintDocumentAdapter(string fileDesc)
        {
            FileToPrint = fileDesc;
        }
        public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
        {
            if (cancellationSignal.IsCanceled)
            {
                callback.OnLayoutCancelled();
                return;
            }


            PrintDocumentInfo pdi = new PrintDocumentInfo.Builder(FileToPrint).SetContentType(PrintContentType.Document).Build();

            callback.OnLayoutFinished(pdi, true);
        }

        public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
        {
            InputStream input = null;
            OutputStream output = null;

            try
            {
                //Create FileInputStream object from the given file
                input = new FileInputStream(FileToPrint);
                //Create FileOutputStream object from the destination FileDescriptor instance
                output = new FileOutputStream(destination.FileDescriptor);

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = input.Read(buf)) > 0)
                {
                    //Write the contents of the given file to the print destination
                    output.Write(buf, 0, bytesRead);
                }

                callback.OnWriteFinished(new PageRange[] { PageRange.AllPages });

            }
            catch (FileNotFoundException ex)
            {
                //Catch exception
                System.Diagnostics.Debug.WriteLine(ex);
            }
            catch (Exception e)
            {
                //Catch exception
                System.Diagnostics.Debug.WriteLine(e);
            }
            finally
            {
                try
                {
                    input.Close();
                    output.Close();
                }
                catch (IOException e)
                {
                    e.PrintStackTrace();
                    System.Diagnostics.Debug.WriteLine(e);
                }
            }
        }
    }
}

谁能帮帮我?先谢谢你。

xamarin.forms xamarin.android
1个回答
1
投票

你应该把这个添加到你的Android项目的Print类中去

[assembly: Dependency(typeof(myApp.Droid. Print))]

像这样

using Xamarin.Forms;

//Add this line
[assembly: Dependency(typeof(myApp.Droid. Print))]
namespace myApp.Droid
{
    public class Print : IPrint
    {
        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.