Xamarin Android无法保存文件PDFdocument

时间:2018-02-16 08:52:21

标签: android xamarin pdf-generation

我是Xamarin的新手。 我正在尝试将我的PDF文档保存到手机,但PDF文档不会保存在手机中。

我已经在android清单中授予了READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE权限。

这是我的源代码

public void CreatePdf(Survey survey)
{
    // create a new document
    PdfDocument pdf = new PdfDocument();

    // crate a page description
    PageInfo pageInfo = new PageInfo.Builder(100, 100, 1).Create();

    // start a page
    PdfDocument.Page page = pdf.StartPage(pageInfo);

    Canvas canvas = page.Canvas;

    Paint paint = new Paint();

    canvas.DrawCircle(50, 50, 30, paint);

     // finish the page
    pdf.FinishPage(page);
    string path = "";

    try
    {  // write the document content
        path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MediKine.pdf");

        //FileStream fs = new FileStream(path, FileMode.Create);
        //pdf.WriteTo(fs);
        //fs.Flush();

        //pdf.Close();

        using (FileStream fileStream = new FileStream(path, FileMode.Create))
        {
            pdf.WriteTo(fileStream);
            fileStream.Flush();

            pdf.Close();
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.StackTrace);
    }

    // close the document
    pdf.Close();
}

编辑的代码正在运行,但我使用过时的函数Forms.Context来获取活动。我会尽力找到好的解决方案。

    try
    {  // Get directory download
        Java.IO.File file = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);

        CheckPermission();

        using (FileStream fileStream = new FileStream(file.AbsolutePath + "MediKine.pdf", FileMode.Create))
        {
            pdf.WriteTo(fileStream);
            fileStream.Flush();
            fileStream.Close();
            pdf.Close();
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.StackTrace);
    }

    // close the document
    pdf.Close();
}

private void CheckPermission()
{
    if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
    {
        const string permission = Manifest.Permission.WriteExternalStorage;

        if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, permission) != Android.Content.PM.Permission.Granted)
        {
            ActivityCompat.RequestPermissions((Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
        }
    }
}

请帮我解决这个问题。

0 个答案:

没有答案