Generate pdf from user input to PDF Xamarin

Viewed 143

I am currently working on an application that generates orders in Xamarin forms for both Android and IOS. The customer can place an order, you can see the method of ordering below in the code block. I would like to create a function that displays the customer's order in PDF format. Is there a way from this function to create a new function called "CreatePdfFile" that generates a pdf with the orders that the customer has ordered?

    public async Task<string> PlaceOrderAsync()
    {
        var cn = DependencyService.Get<ISQLite>().GetConnection();
        var data = cn.Table<CartItem>().ToList();

        var orderId = Guid.NewGuid().ToString();
        var uname = Preferences.Get("Username", "Guest");

        foreach(var item in data)
        {
            OrderDetails od = new OrderDetails()
            {
                OrderId = orderId,
                OrderDetailId = Guid.NewGuid().ToString(),
                ProductId = item.ProductId,
                ProductName = item.ProductName
            };
            await client.Child("OrderDetails").PostAsync(od);
        }
        await client.Child("Orders").PostAsync(
            new Order()
            {
                OrderId = orderId,
                Username = uname
            });
        return orderId;
    }
1 Answers

You could try to use Syncfusion.Xamarin.PDF.

Install from NuGet package first.

Creating a PDF document with table:

  //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);

For more details about the ISave, you could get the whole code from Syncfusion official document.

Related