无法在我的 phone 或 bluestacks Xamarin.Forms 上保存 pdf 文件

Cannot save pdf file on my phone or bluestacks Xamarin.Forms

我正在尝试使用 PdfSharpCore for Xamarin Forms 创建 pdf,但我 运行 遇到了一些问题。

 private void CreatePdf(object sender)
        {
            PdfDocument pdf = new PdfDocument();
            PdfPage pdfPage = pdf.AddPage();
            XGraphics graph = XGraphics.FromPdfPage(pdfPage);
            XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
            graph.DrawString("This is my first PDF document", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string localFilename = "test.pdf";
            string localPath = Path.Combine(documentsPath, localFilename);
            MemoryStream stream = new MemoryStream();
            pdf.Save(stream, false);
            byte[] bytes = stream.ToArray();
            File.WriteAllBytes(localPath, bytes);
        }

这是我生成 pdf 并保存它的函数,但是当我按下调用它的按钮时,没有任何反应。 我已经像这样在 AndroidManifest.xml 文件上添加了权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我试过使用一个名为 Xamarin.Forms.SaveOpenPDFPackage 的库。有了这个库,你可以 通过这样做保存并打开您全新的 pdf:

await CrossXamarinFormsSaveOpenPDFPackage.Current.SaveAndView("myFile1.pdf", "application/pdf", stream, PDFOpenContext.InApp);

它成功了一半:它打开了我的新 pdf,但没有保存它。

你有什么建议吗?

您可以尝试使用 Syncfusion.Xamarin.PDF

首先从 NuGet 包安装。

使用 table 创建 PDF 文档:

  //Create a new PDF document.
  PdfDocument doc = new PdfDocument();
  //Add a page.
  PdfPage page = doc.Pages.Add();
  //Create a PdfGrid.
  PdfGrid pdfGrid = new PdfGrid();
  //Add values to list
  List<object> data = new List<object>();
  Object row1 = new { ID = "E01", Name = "Clay" };
  Object row2 = new { ID = "E02", Name = "Thomas" };
  Object row3 = new { ID = "E03", Name = "Andrew" };
  Object row4 = new { ID = "E04", Name = "Paul" };
  Object row5 = new { ID = "E05", Name = "Gray" };
  data.Add(row1);
  data.Add(row2);
  data.Add(row3);
  data.Add(row4);
  data.Add(row5);
  //Add list to IEnumerable
  IEnumerable<object> dataTable = data;
  //Assign data source.
  pdfGrid.DataSource = dataTable;
  //Draw grid to the page of PDF document.
  pdfGrid.Draw(page, new PointF(10, 10));
  //Save the PDF document to stream.
  MemoryStream stream = new MemoryStream();
  doc.Save(stream);
  //Close the document.
  doc.Close(true);

  //Save the stream as a file in the device and invoke it for viewing
  Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("Output.pdf",             "application/pdf", stream);

有关ISave的更多详细信息,您可以从Syncfusion官方文档中获取完整代码。