is there an example of how to print data, or display data as a report that can be printed on .NET MAUI android
Loading
is there an example of how to print data, or display data as a report that can be printed on .NET MAUI android
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Tuhin PaulRank #7 · 71.9K reputationPosted Jun 18, 2023, 10:59 AM EDT
In the XAML file (MainPage.xaml), add a ListView control to display the data
In code-behind file (MainPage.xaml.cs), set the data context and populate the ReportData collection with the data
using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Xaml; namespace YourNamespace { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); // Set the data context BindingContext = new MainViewModel(); } } }Create a view model (MainViewModel.cs) to provide the data to the view
using System.Collections.ObjectModel; using Microsoft.Maui.Controls; namespace YourNamespace { public class MainViewModel : BindableObject { public ObservableCollection ReportData { get; set; } public MainViewModel() { // Populate the ReportData collection with your data ReportData = new ObservableCollection { new ReportItem { Name = "Item 1", Description = "Description 1" }, new ReportItem { Name = "Item 2", Description = "Description 2" }, new ReportItem { Name = "Item 3", Description = "Description 3" } }; } } public class ReportItem { public string Name { get; set; } public string Description { get; set; } } }A SalimRank #9,295 · 208 reputationPosted Jun 26, 2023, 10:58 PM EDT
Thanks to Tuhin Paul for the answer, but what I need is a way/code to be able to print the displayed data to a thermal printer, which is usually connected via bluetooth, the example described by Mohamed Azarudeen is close, but can't be implemented, maybe there are steps that not enough.
This my code
using DMS.Constant; using DMS.Model; using DMS.Repo; using GemBox.Document; using GemBox.Document.Tables; using Microsoft.Maui.Controls.PlatformConfiguration; using System.Collections.ObjectModel; using System.Diagnostics; namespace DMS.View; public partial class ListOfInvoicePage : ContentPage { List _customerARList; int _pageSize = 20; public ObservableCollection ListOfCustomerAR { get; set; } = new(); CustomerRepository oCustomerRepository = new(); public ListOfInvoicePage() { InitializeComponent(); //cek permisiion bluetooth Task.Run(() => CheckBluetoothAccess()); GetListCustomerARAsync(); } private async Task CheckBluetoothAccess() { try { var requestStatus = PermissionStatus.Unknown; requestStatus = await Permissions.CheckStatusAsync(); if (requestStatus == PermissionStatus.Granted) return; if (Permissions.ShouldShowRationale()) { await Shell.Current.DisplayAlert("List Of Invoice", "dibutuhkan izin akses bluetooth", "OK"); } requestStatus = await Permissions.RequestAsync(); } catch (Exception ex) { await Shell.Current.DisplayAlert("List of invoice", ex.Message, "OK"); } } private void GetListCustomerARAsync() { try { ListOfCustomerAR = new(); decimal decCount = 0; decimal decAmount = 0; decimal decPayment = 0; decimal decRemain = 0; decimal decRemainInv = 0; //IsBusy = true; Task.Run(() => { _customerARList = oCustomerRepository.GetListCustARAll(); App.Current.Dispatcher.Dispatch(() => { ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc0_abcsakfskgskgskghieshi", dtmDue = "05/25/2023", decAmount = 1000200000000, decRemain = 1000000000000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc1_abcsakfskgskgskghieshi", dtmDue = "05/27/2023", decAmount = 1000000, decRemain = 1000000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc2_abcsakfskgskgskghieshi", dtmDue = "05/28/2023", decAmount = 500000, decRemain = 500000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc3_abcsakfskgskgskghieshi", dtmDue = "05/30/2023", decAmount = 7500000, decRemain = 7500000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc4_abcsakfskgskgskghieshi", dtmDue = "05/25/2023", decAmount = 1000000, decRemain = 6600000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc5_abcsakfskgskgskghieshi", dtmDue = "05/26/2023", decAmount = 1300000, decRemain = 1300000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc6_abcsakfskgskgskghieshi", dtmDue = "05/28/2023", decAmount = 4200000, decRemain = 4200000 }); ListOfCustomerAR.Add(new SFA_CustomerAR { szDocId = "Doc7_abcsakfskgskgskghieshi", dtmDue = "05/25/2023", decAmount = 100000, decRemain = 100000 }); decCount = (from x in ListOfCustomerAR select x.szDocId).Count(); decAmount = (from x in ListOfCustomerAR select x.decAmount).Sum(); decPayment = 0; decRemain = (from x in ListOfCustomerAR select x.decRemain).Sum(); decRemainInv = decAmount - decPayment; }); return Task.CompletedTask; }); this.lbllembarInv.Text = decCount.ToString(); this.lblnnilaiinv.Text = decAmount.ToString(); this.lblpaymentinv.Text = decPayment.ToString(); this.lblremaininv.Text = decRemainInv.ToString(); this.cvCustAR.ItemsSource = ListOfCustomerAR; } catch (Exception ex) { Debug.WriteLine($"Unable to get data customer: {ex.Message}"); Shell.Current.DisplayAlert("List callplan", ex.Message, "OK"); throw; } } private async void btnGeneratePdf_Clicked(object sender, EventArgs e) { try { var ReportFolder = Android.App.Application.Context.GetExternalFilesDir(GeneralConstant.FolderReportApps); var filePath = System.IO.Path.Combine(ReportFolder.AbsolutePath, "Invoice.docx"); //GeneratePDF_Gembox(); GenerateDocument_Gembox(); ///===============This is for print...??????? } catch (Exception ex) { await Shell.Current.DisplayAlert("List AR", ex.Message, "OK"); throw; } } private async void GenerateDocument_Gembox() { try { var document = new GemBox.Document.DocumentModel(); var table = new Table(document); table.TableFormat.AutomaticallyResizeToFitContents = false; // By default Table has assigned "Table Grid" style, the same as when creating it in Microsoft Word. // This base style defines borders which can be removed with the following. table.TableFormat.Style.TableFormat.Borders.ClearBorders(); // Add columns with specified width. table.Columns.Add(new TableColumn(60)); table.Columns.Add(new TableColumn(120)); table.Columns.Add(new TableColumn(180)); // Add rows with specified height. table.Rows.Add(new GemBox.Document.Tables.TableRow(document) { RowFormat = { Height = new TableRowHeight(30, TableRowHeightRule.AtLeast) } }); table.Rows.Add(new GemBox.Document.Tables.TableRow(document) { RowFormat = { Height = new TableRowHeight(60, TableRowHeightRule.AtLeast) } }); table.Rows.Add(new GemBox.Document.Tables.TableRow(document) { RowFormat = { Height = new TableRowHeight(90, TableRowHeightRule.AtLeast) } }); for (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) { // Add cell. var cell = new TableCell(document); table.Rows[r].Cells.Add(cell); // Set cell's vertical alignment. switch (r) { case 0: cell.CellFormat.VerticalAlignment = GemBox.Document.VerticalAlignment.Top; break; case 1: cell.CellFormat.VerticalAlignment = GemBox.Document.VerticalAlignment.Center; break; case 2: cell.CellFormat.VerticalAlignment = GemBox.Document.VerticalAlignment.Bottom; break; } // Add cell content. var paragraph = new Paragraph(document, $"Cell ({r + 1},{c + 1})"); cell.Blocks.Add(paragraph); // Set cell content's horizontal alignment. switch (c) { case 0: paragraph.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Left; break; case 1: paragraph.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Center; break; case 2: paragraph.ParagraphFormat.Alignment = GemBox.Document.HorizontalAlignment.Right; break; } if ((r + c) % 2 == 0) { // Set cell's background and borders. cell.CellFormat.BackgroundColor = new GemBox.Document.Color(255, 242, 204); cell.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Double, GemBox.Document.Color.Red, 1); } } document.Sections.Add(new GemBox.Document.Section(document, table)); var ReportFolder = Android.App.Application.Context.GetExternalFilesDir(GeneralConstant.FolderReportApps); var filePath = System.IO.Path.Combine(ReportFolder.AbsolutePath, "Invoice.docx"); document.Save(filePath); } catch (Exception ex) { await Shell.Current.DisplayAlert("List AR", ex.Message, "OK"); throw; } } }Mohamed Azarudeen ZRank #297 · 8.5K reputationPosted May 25, 2023, 9:13 AM EDT
Hi salim try this
To display data as a report that can be printed in a .NET MAUI Android application, you can use the printing capabilities provided by the underlying Android platform. Here's an outline of the steps involved:
1. Install the required NuGet packages:
- Xamarin.Essentials: Provides cross-platform APIs, including printing functionality.
- Xamarin.AndroidX.Print: AndroidX library that enables printing support on Android.
2. Request the necessary permissions in your AndroidManifest.xml file:
- Add the following permissions to enable printing:
3. Implement the printing functionality in your .NET MAUI application:
- Define a method to handle the print functionality, which will generate and display the report.
- Within the print method, you can use libraries or frameworks (e.g., PDFSharp, Syncfusion, etc.) to generate a printable document from your data.
- Once you have the document, you can use the Xamarin.Essentials API to initiate the printing process.
Here's an example of a basic implementation for printing a PDF document:
using Xamarin.Essentials; ... // Method to handle the printing functionality private async void PrintReport() { // Generate the report document using a PDF library or other frameworks // Save the generated report to a temporary file string tempFilePath = Path.Combine(FileSystem.CacheDirectory, "report.pdf"); using (FileStream fileStream = new FileStream(tempFilePath, FileMode.Create)) { // Write the generated document to the file stream // Example: document.Save(fileStream); } // Print the document using the Xamarin.Essentials API await Print.PickAsync(new PrintSpecifications { JobName = "Report", PrinterOptions = new PrinterOptions { MediaType = PrintMediaType.Unknown, Copies = 1 }, FilePath = tempFilePath }); }Make sure to adapt the code based on your specific requirements, including generating the report document using a suitable PDF library or other frameworks.
Remember to handle any necessary error checking, permissions, and exception handling to ensure a smooth printing experience.
With this implementation, you should be able to generate a report document and print it from your .NET MAUI Android application.
A SalimRank #9,295 · 208 reputationPosted Jun 18, 2023, 7:53 AM EDT
Thanks to Mohamed Azarudeen for the answer, but the method you presented cannot be implemented on .net maui, I have tried to create a pdf document to print according to your instructions using Gembox, and added the packages Xamarin.Essentials and Xamarin.AndroidX.Print, as well as adding permissions to the AndroidManifest.xml file, but the print method of the example you provided is unknown, but it is directed to use the Microsoft.Graph package, so I can't continue, or is there a possibility that I missed a step
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Jun 27, 2023, 4:12 AM EDT
example of how you can display data as a report in a .NET MAUI application for Android:
Create a .NET MAUI Application: Start by creating a new .NET MAUI application targeting Android.
Design the Report Page: Add a new page to your application to display the report. You can use XAML or code-behind to define the UI. Here's an example using XAML:
private string GenerateReportData() { // Retrieve data and format as HTML // Example: var reportData = "Report TitleReport content goes here "; return reportData; }Handle Print Button Click: Implement the
OnPrintClickedevent handler for the print button. In this method, generate the report data and load it into the WebView control. Here's an example:private void OnPrintClicked(object sender, EventArgs e) { var reportData = GenerateReportData(); ReportWebView.Source = new HtmlWebViewSource { Html = reportData }; // Call the Print function Print(); }Print Function: Implement the
Printfunction to print the report using the Android printing system. Here's an example:private async void Print() { var printManager = (PrintManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.PrintService); var printAdapter = ReportWebView.CreatePrintDocumentAdapter("Report"); var printJobName = "Report_Print"; printManager.Print(printJobName, printAdapter, null); }Run the Application: Build and run your .NET MAUI application on an Android device or emulator. When you click the "Print Report" button, the report data will be loaded into the WebView, and the print dialog will be displayed for the user to print the report.
Deepak RawatRank #646 · 3.7K reputationPosted May 26, 2023, 1:48 AM EDT
.NET MAUI, you can use the
PrintManagerclass to handle printing tasks, including generating and displaying printable reports. Here's an example of how you can print data and display it as a report in a .NET MAUI Android application:First, make sure you have the
PrintandPrintPreviewpermissions added to your Android project'sAndroidManifest.xmlfile