我正在嘗試使用 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,但沒有保存它。
你有什么秘訣嗎?
uj5u.com熱心網友回復:
你可以嘗試使用Syncfusion.Xamarin.PDF.
首先從 NuGet 包安裝。
創建帶有表格的 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 官方檔案中獲取完整代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432722.html
標籤:xamarin xamarin.forms xamarin.android xamarin.ios xamarin 工作室
