使用Xamarin表单打印PDF文件

时间:2019-10-16 08:00:56

标签: pdf xamarin xamarin.forms xamarin.android printdocument

我正在通过打印服务打印Pdf文件。 我实现了一些代码,但是它不起作用-它引发了异常:

  

java.lang.RuntimeException:无法打印格式错误的PDF文件

请检查我的代码,然后让我出问题所在。

internal class CustomPrintDocumentAdapter : PrintDocumentAdapter
{
   private string filePath;
   public CustomPrintDocumentAdapter(string filePath)
   {
      this.filePath = filePath;
   }
   public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
        {
    if (cancellationSignal.IsCanceled)
    {
        callback.OnLayoutCancelled();
        return;
    }
    callback.OnLayoutFinished(new PrintDocumentInfo.Builder(filePath)
    .SetContentType(PrintContentType.Document)
    .Build(), true);
    }

    public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
    {
        try
        {
        using (InputStream input = new FileInputStream(filePath))
        {
            using (OutputStream output = new FileOutputStream(destination.FileDescriptor))
            {
                var buf = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.Read(buf)) > 0)
                {
                    output.Write(buf, 0, bytesRead);
                }
            }
        }
        callback.OnWriteFinished(new[] { PageRange.AllPages });
    }
    catch (FileNotFoundException fileNotFoundException)
    {
                System.Diagnostics.Debug.WriteLine(fileNotFoundException);
    }
    catch (Exception exception)
    {
        System.Diagnostics.Debug.WriteLine(exception);
    }
   }
  }

0 个答案:

没有答案
相关问题