Перейти к содержимому

Как создать pdf файл xamarin forms

  • автор:

Create or Generate PDF file in Xamarin

The Syncfusion Xamarin PDF library is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, forms, and secure PDF files.

To include the Syncfusion Xamarin PDF library into your Xamarin application, please refer to the NuGet Package Required or Assemblies Required documentation.

Steps to create PDF document in Xamarin

Xamarin project creation

Step 1: Create a new C# Xamarin.Forms application project.

Step 2: Select a project template and required platforms to deploy the application. In this application, the portable assemblies to be shared across multiple platforms, so the .NET Standard code sharing strategy has been selected. For more details about code sharing, refer here.

NOTE

If .NET Standard is not available in the code sharing strategy, the Portable Class Library (PCL) can be selected.

Xamarin project creation step2

Install Xamarin PDF NuGet package

Step 3: Install the Syncfusion.Xamarin.PDF NuGet package as a reference to your Xamarin.Forms applications from NuGet.org.

NOTE

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to add “Syncfusion.Licensing” assembly reference and include a license key in your projects. Please refer to this link to know about registering Syncfusion license key in your application to use our components.

Step 4: Add new Forms XAML page in portable project if there is no XAML page is defined in the App class. Otherwise, proceed to the next step.

a. To add the new XAML page, right-click the project and select Add > New Item and add a Forms XAML Page from the list. Name it as MainXamlPage.

b. In App class of portable project (App.cs), replace the existing constructor of App class with the following code example, which invokes the MainXamlPage.

 public App()  //The root page of your application. MainPage = new MainXamlPage(); >

Step 5: In the MainXamlPage.xaml, add new button as follows.

 ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="GettingStarted. MainXamlPage"> StackLayout VerticalOptions="Center"> Button Text="Generate Document" Clicked="OnButtonClicked" HorizontalOptions="Center"/> StackLayout> ContentPage>

Step 6: Include the following namespace in the MainXamlPage.xaml.cs file.

 using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid;

Step 7: Include the following code example in the click event of the button in MainXamlPage.xaml.cs, to create a PDF document and save it in a stream. In this code example, the PdfDocument object represents an entire PDF document that is being created and add a PdfPage to it. The text has been added in PDF by using the DrawString method of PdfGraphics class.

 //Create a new PDF document. PdfDocument document = new PdfDocument(); //Add a page to the document. PdfPage page = document.Pages.Add(); //Create PDF graphics for the page. PdfGraphics graphics = page.Graphics; //Set the standard font. PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); //Draw the text. graphics.DrawString("Hello World. ", font, PdfBrushes.Black, new PointF(0, 0)); //Save the document to the stream. MemoryStream stream = new MemoryStream(); document.Save(stream); //Close the document. document.Close(true); //Save the stream as a file in the device and invoke it for viewing. Xamarin.Forms.DependencyService.GetISave>().SaveAndView("Output.pdf", "application / pdf", stream);

Step 8: Download the helper files from this link and add them into the mentioned project. These helper files allow you to save the stream as a physical file and open the file for viewing.

Project File Name Summary
portable project ISave.cs Represent the base interface for save operation
iOS Project SaveIOS.cs Represent the base interface for save operation
PreviewControllerDS.cs Helper class for viewing the PDF file in iOS device
Android project SaveAndroid.cs Save implementation for Android device
WinPhone project SaveWinPhone.cs Save implementation for Windows Phone device
UWP project SaveWindows.cs Save implementation for UWP device.
Windows(8.1) project SaveWindows81.cs Save implementation for WinRT device.

NOTE

Introduced a new runtime permission model for the Android SDK version 23 and above. So, include the following code for enabling the Android file provider to save and view the generated PDF document.

Step 9(i): Create a new XML file with the name of provider_paths.xml under the Android project Resources folder and add the following code in it.
Eg: Resources/xml/provider_paths.xml

 xml version="1.0" encoding="UTF-8" ?> paths xmlns:android="http://schemas.android.com/apk/res/android"> external-path name="external_files" path="."/> paths>

Step 9(ii): Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml.

 xml version="1.0" encoding="utf-8"?> manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname. GettingStarted "> uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" /> application android:label=" GettingStarted.Android" android:requestLegacyExternalStorage="true"> provider android:name="android.support.v4.content.FileProvider" android:authorities="$.provider" android:exported="false" android:grantUriPermissions="true"> meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" /> provider> application> manifest>

Please include the changes if you deploy the application in Android 11:

  • Enabled the androidLegacyExtranalStorage in the AndroidManifest.xml file.
 application android:label=" PDFXamarinSample.Android" android:requestLegacyExternalStorage="true">
  • User permission for read or write external storage.Add the following code to the AndroidManifest.xml file located under Properties/AndroidManifest.xml.
 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"> uses-permission> uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 10: Compile and execute the application. This will creates a simple PDF document.

You can download a complete working sample from GitHub.

Xamarin output PDF document

By executing the program, you will get the PDF document as follows.

Creating a PDF document with image

Load image stream from the local files on disk and draw the images through the DrawImage method of the PdfGraphics class. The following code example shows how to create a PDF document with an image.

 //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page to the document. PdfPage page = doc.Pages.Add(); //Create PDF graphics for the page. PdfGraphics graphics = page.Graphics; //Load the image as stream. Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("Adventure Cycles.png"); //Load the image from the disk. PdfBitmap image = new PdfBitmap(imageStream); //Draw the image. graphics.DrawImage(image, 0, 0); ////Save the document to the stream. MemoryStream stream = new MemoryStream(); //Save the document. 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.GetISave>().SaveAndView("Output.pdf", "application/pdf", stream);

You can download a complete working sample from GitHub.

Xamarin output PDF document

By executing the program, you will get the PDF document as follows.

Creating a PDF document with table

The PdfGrid allows you to create a table from a DataSource (data set, data table, arrays, or IEnumerable object) in a PDF document.The following code example shows how to create a PDF document with a simple 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. Listobject> data = new Listobject>(); 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. IEnumerableobject> dataTable = data; //Assign data source. pdfGrid.DataSource = dataTable; //Apply built-in table style pdfGrid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable4Accent1); //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.GetISave>().SaveAndView("Output.pdf", "application/pdf", stream);

You can download a complete working sample from GitHub.

Xamarin output PDF document

By executing the program, you will get the PDF document as follows.

Creating a simple PDF document with basic elements

The PdfDocument object represents an entire PDF document that is being created. The following code example shows how to create a PDF document and add a PdfPage to it along with the PdfPageSettings.

 //Creates a new PDF document. PdfDocument document = new PdfDocument(); //Adds page settings. document.PageSettings.Orientation = PdfPageOrientation.Landscape; document.PageSettings.Margins.All = 50; //Adds a page to the document. PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics;
  1. Essential PDF has APIs similar to the .NET GDI plus which helps to draw elements to the PDF page just like 2D drawing in .NET.
  2. Unlike System.Drawing APIs all the units are measured in point instead of pixel.
  3. In PDF, all the elements are placed in absolute positions and has the possibility for content overlapping if misplaced.
  4. Essential PDF provides the rendered bounds for each and every elements added through PdfLayoutResult objects. This can be used to add successive elements and prevent content overlap.

The following code example explains how to add an image from disk to a PDF document, by providing the rectangle coordinates.

 //Loads the image as stream. Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.AdventureCycle.jpg"); RectangleF bounds = new RectangleF(176, 0, 390, 130); PdfImage image = PdfImage.FromStream(imageStream); //Draws the image to the PDF page. page.Graphics.DrawImage(image, bounds);

The following methods can be used to add text to a PDF document.

  1. DrawString() method of the PdfGraphics
  2. PdfTextElement class.

The PdfTextElement provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. This is not available in the DrawString method.

The following code example adds the necessary text such as address, invoice number and date to create a basic invoice application.

 PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); bounds = new RectangleF(0, bounds.Bottom + 90, graphics.ClientSize.Width, 30); //Draws a rectangle to place the heading in that region. graphics.DrawRectangle(solidBrush, bounds); //Creates a font for adding the heading in the page. PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14); //Creates a text element to add the invoice number. PdfTextElement element = new PdfTextElement("INVOICE " + id.ToString(), subHeadingFont); element.Brush = PdfBrushes.White; //Draws the heading on the page. PdfLayoutResult result = element.Draw(page, new PointF(10, bounds.Top + 8)); string currentDate = "DATE " + DateTime.Now.ToString("MM/dd/yyyy"); //Measures the width of the text to place it in the correct location. SizeF textSize = subHeadingFont.MeasureString(currentDate); PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y); //Draws the date by using DrawString method. graphics.DrawString(currentDate, subHeadingFont, element.Brush, textPosition); PdfFont timesRoman = new PdfStandardFont(PdfFontFamily.TimesRoman, 10); //Creates text elements to add the address and draw it to the page. element = new PdfTextElement("BILL TO ", timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(126, 155, 203)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); PdfPen linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); PointF startPoint = new PointF(0, result.Bounds.Bottom + 3); PointF endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address. graphics.DrawLine(linePen, startPoint, endPoint);

Essential PDF provides two types of table models. The difference between both the table models can be referred from the link
Difference between PdfLightTable and PdfGrid

Since the invoice document requires only simple cell customizations, the given code example explains how to create a simple invoice table by using PdfGrid.

 //Creates the datasource for the table. DataTable invoiceDetails = GetProductDetailsAsDataTable(); //Creates a PDF grid. PdfGrid grid = new PdfGrid(); //Adds the data source. grid.DataSource = invoiceDetails; //Creates the grid cell styles. PdfGridCellStyle cellStyle = new PdfGridCellStyle(); cellStyle.Borders.All = PdfPens.White; PdfGridRow header = grid.Headers[0]; //Creates the header style. PdfGridCellStyle headerStyle = new PdfGridCellStyle(); headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173)); headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); headerStyle.TextBrush = PdfBrushes.White; headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular); //Adds cell customizations. for (int i = 0; i  header.Cells.Count; i++)  if (i == 0 || i == 1) header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); else header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); > //Applies the header style. header.ApplyStyle(headerStyle); cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f); cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f); cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136)); //Creates the layout format for grid. PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat(); //Creates layout format settings to allow the table pagination. layoutFormat.Layout = PdfLayoutType.Paginate; //Draws the grid to the PDF page. PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 100)), layoutFormat);

The following code example shows how to save the invoice document to disk and dispose the PdfDocument object.

 //Save the PDF document to stream. MemoryStream stream = new MemoryStream(); document.Save(stream); //Close the document. document.Close(true); //Save the stream as a file in the device and invoke it for viewing Xamarin.Forms.DependencyService.GetISave>().SaveAndView("Output.pdf", "application/pdf", stream);

You can download a complete working sample from GitHub.

Invoice PDF document

The following screenshot shows the invoice PDF document created by using Essential PDF.

Filling forms

An interactive form sometimes referred to as an AcroForm, is a collection of fields for gathering information interactively from the user. A PDF document or existing PDF document contain any number of fields appearing in any combination of pages, all that make a single, globally interactive form spanning the entire document.

Essential PDF allows you to create and manipulate existing form in a PDF document using the PdfForm class. The PdfLoadedFormFieldCollection class represents the entire field collection of the loaded form. To work with existing form documents, the following namespaces are required.

  1. Syncfusion.Pdf
  2. Syncfusion.Pdf.Parsing

Sample PDF form

The following guide shows how to fill out a sample PDF form.

Essential PDF allows you to fill the form fields by using PdfLoadedField class. You can get the form field either by using its field name or field index.

 //Loads the PDF form. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(@"JobApplication.pdf"); //Loads the form. PdfLoadedForm form = loadedDocument.Form; //Fills the textbox field by using index. (form.Fields[0] as PdfLoadedTextBoxField).Text = "John"; //Fills the textbox fields by using field name. (form.Fields["LastName"] as PdfLoadedTextBoxField).Text = "Doe"; (form.Fields["Address"] as PdfLoadedTextBoxField).Text = " John Doe \n 123 Main St \n Anytown, USA"; //Loads the radio button group. PdfLoadedRadioButtonItemCollection radioButtonCollection = (form.Fields["Gender"] as PdfLoadedRadioButtonListField).Items; //Checks the 'Male' option. radioButtonCollection[0].Checked = true; //Checks the 'business' checkbox field. (form.Fields["Business"] as PdfLoadedCheckBoxField).Checked = true; //Checks the 'retiree' checkbox field. (form.Fields["Retiree"] as PdfLoadedCheckBoxField).Checked = true; //Save the PDF document to stream. MemoryStream stream = new MemoryStream(); loadedDocument.Save(stream); //Close the document. loadedDocument.Close(true); //Save the stream as a file in the device and invoke it for viewing Xamarin.Forms.DependencyService.GetISave>().SaveAndView("Output.pdf", "application/pdf", stream);

You can download a complete working sample from GitHub.

Filled PDF form

The filled form is shown in adobe reader application as follows.

Merge PDF Documents

Essential PDF supports merging multiple PDF documents from stream using the Merge method of the PdfDocumentBase class.

You can merge the PDF document streams by using the following code example.

 //Creates a PDF document. PdfDocument finalDoc = new PdfDocument(); //Loads the Pdf as a stream. Stream stream1 = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.file1.pdf"); Stream stream2 = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.file2.pdf"); // Creates a PDF stream for merging. Stream[] streams =  stream1, stream2 >; // Merges PDFDocument. PdfDocumentBase.Merge(finalDoc, streams); //Save the PDF document to stream. MemoryStream stream = new MemoryStream(); finalDoc.Save(stream); //If the position is not set to '0' then the PDF will be empty. stream.Position = 0; //Close the document. finalDoc.Close(true); //Save the stream as a file in the device and invoke it for viewing Xamarin.Forms.DependencyService.GetISave>().SaveAndView("Output.pdf", "application/pdf", stream);

You can download a complete working sample from GitHub.

Click here to explore the rich set of Syncfusion PDF library features.

An online sample link to create PDF document in ASP.NET Core.

Help us improve this page
Correct inaccurate or outdated content
Please provide additional information
Improve illustrations or images
Please provide additional information
Fix typos or broken links
Please provide additional information
Add more information
Please provide additional information
Correct inaccurate or outdated code samples
Please provide additional information
Please provide additional information

I agree to the creation of a Syncfusion account in my name and to be contacted regarding this message. No further action will be taken. Please see our Privacy Policy.

Write a Text File (or PDF File) from Json in Xamarin.forms

I am Trying to Write My listView (with multiple Binding Objects in it and user Entrys as input) to a Text file. I came up with the Idea of Serialize it to Json and then write it to text with button clicked (I am new here :)). But I get stocked in Json Loops errors. The name of my listView is LL:

private void Save_Clicked(object sender, EventArgs e)

The error is:

Newtonsoft.Json.JsonSerializationException: ‘Self referencing loop detected for property ‘ParentView’ with type ‘Xamarin.Forms.Grid’. Path ‘TemplatedItems[0].View.Children[0]’.’

My Xamlpage

    " FontSize="18" TextColor="Black" Grid.Column="0" Grid.Row="0" />           

Out put

with a model I can now print this:

Отправка файлов в приложение Xamarin.Forms. Часть 1

Пересылка файлов между приложениями является довольно специфической функцией для ОС. И это то, что лучше не пытаться сделать в Xamarin.Forms, не так ли? На самом деле сделать это довольно просто, и этот пост продемонстрирует как заполучить эту функцию и запустить в iOS (в следующем посте будет рассмотрен случай с Android и, при необходимости, с UWP).

Это распространенная практика использования мобильных приложений: открытие файла в одном приложении и необходимость использования другого для дальнейшей обработки этого файла. Например, вы открыли PDF файл, и появилась необходимость внести некоторые изменения в этом файле в другом приложении. При тапе на этом PDF файле на экране появится меню «Открыть в», позволяя импортировать данный файл в предпочитаемое приложение.

Стоит отметить, что в этом посте речь пойдет не о создании расширения приложения к iOS фрагменту Forms решения, чтобы появлялось приложение, когда пользователь тапает кнопку «Поделиться» (маленький прямоугольник с выходящей из него стрелкой). В данном случае будет рассмотрена передача файла в Forms приложение, а не обмен контентом между приложениями.

Сценарий

Приведенный в этом посте пример — это Xamarin.Forms приложение, зарегистрированное для возможности открытия PDF файлов и последующего отображения их в WebView. Здесь будут рассмотрены основы регистрации для iOS, а значит и для Xamarin.Forms (Это также применимо и для Android).

iOS регистрация

Когда я говорю, что Forms приложение будет зарегистрировано, то имеется в виду, что оно будет работать как этих скриншотах. В Safari открыта страница с PDF файлом.

Приложение называется «OpenForms», и на первом скриншоте iOS предоставляет возможность напрямую открыть файл с помощью быстрой команды «Open In OpenForms».

На втором скриншоте при тапе на меню «More» внизу появится окно со списком действий. Здесь виден ярлык нужного приложения.

Info.plist

Чтобы iOS поняла, что данное приложение может обрабатывать PDF файлы, необходимо скорректировать файл Info.plist. Нужно добавить новый ключ верхнего уровня. Можно сделать это с помощью встроенного в Xamarin Studio редактора или отредактировать напрямую.

Чтобы использовать Xamarin Studio, нужно дважды кликнуть на Info.Plist, и тогда откроется встроенный редактор. Выберите вкладку «Advanced» внизу экрана. В разделе «Document Types» в самом вверху кликните кнопку «Add Document Type». Это добавит раздел как на скриншоте ниже.

Вот так нужно его заполнить.

Name: Любое имя. Оно понадобится для ссылки позднее.
Types: Это превратиться в массив определенных строк. Подробнее об этом ниже.
Icons: Расположение ярлыков, которые будут отображаться в меню «More», вместо главного ярлыка приложения. Опять же это может превратиться в массив строк, если будет больше одного ярлыка.

Заполнение таким образом изменит Info.plist и позволит зарегистрировать приложение для открытия файлов других типов. Но здесь стоит разобраться подробнее, чтобы понять, что меняется в Info.plist. Оказывается, что в этот файл можно добавить дополнительные ключи, что не всегда получается сделать в IDE.

Вот весь словарь, который был использован для регистрации открытия файлов нужного типа.

CFBundleDocumentTypes  CFBundleTypeName PDF CFBundleTypeRole Viewer LSHandlerRank Alternate LSItemContentTypes com.adobe.pdf    

CFBundleDocumentTypes — ключ словаря верхнего уровня, который в свою очередь содержит массив других объектов словаря:

  • CFBundleTypeName . Этот ключ содержит имя типа документа для ссылки на тип.
  • CFBundleTypeRole . Этот ключ позволяет ОС определить приложение, которое будет обрабатывать файл данного типа. В конкретном случае — это Viewer.
  • LSHandlerRank . Определяет уровень значимости приложения для типов файлов. Microsoft Word назначен по умолчанию для Word файлов. Для нашего приложения установлено значение Alternate.
  • LSItemContentTypes . Массив строк. Здесь определяются файлы типы файлов, которые приложение сможет открывать.

Теперь нужно понять, как iOS дает знать приложению, что есть файл, ожидающий открытия.

Ответ на открытые iOS события

Когда кто-нибудь выбирает данное приложение, чтобы открыть PDF файл, вызывается следующая функция:

public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) 

iOS копирует файл, который нужно открыть этим приложением, в хранилище, к которому у приложения есть доступ и которое указано с помощью параметра NSUrl url . Далее необходимо обработать этот файл в Xamarin.Forms.

Тогда AppDelegate будет выглядеть так:

App mainForms; public override bool FinishedLaunching(UIApplication app, NSDictionary options) < global::Xamarin.Forms.Forms.Init(); mainForms = new App(); LoadApplication(mainForms); return base.FinishedLaunching(app, options); >public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)

Здесь есть пара необычных моментов. Во-первых, сохранена локальная переменная Xamarin.Forms mainForms класса App в AppDelegate. Она понадобится позднее как точка входа для отображения PDF.

Также в функции OpenUrl была вызвана функция DisplayPDF() переменной mainForms . Это обеспечит отображение PDF в Xamarin.Forms. В идеале нужно было бы скопировать PDF и удалить исходник, указанный параметром url, чтобы очистить место. Но не в этом случае.

Xamarin.Forms!

Я потратил много времени, рассказывая о настройке со стороны iOS. Однако, когда начинается работа в реальном проекте, то часть iOS — это не более чем формальность. Настоящая работа начинается со стороны Xamarin.Forms: как обработать входящий файл. Для этого я оставил комментарий по отображению PDF к статье, которую нашел на сайте Xamarin. Здесь рассказано о настройке рендерера.

Далее хотелось бы сосредоточиться на точке входа в Forms решение.

В файле App.xaml.cs или классе App (класс к которому AppDelegate имеет доступ) есть функция, определяющая взаимодействие между iOS и Forms проектами:

public void DisplayThePDF(string url)

Эта функция создает новую страницу Xamarin.Forms, передает ей место расположения файла и отображает эту страницу модально (В конструкторе класса App все вложено в NavigationPage и сохранено в переменной _navigationRoot ).

Отображаясь модально, она появится поверх всего остального, происходящего в приложении, и никак не отразится на стеке навигации (кроме того, что появится поверх). Конечно ориентация будет на просмотр PDF файла. В реальном приложении необходимо проверить состояние самого приложения – что отображается в настоящий момент (чтобы не было стека модальных окон). Рабочий процесс приложения может потребовать закрыть весь стек и начать сначала или, если используются вкладки, переключиться на новую.

OpenFilesPage имеет подкласс WebView с кастомным рендерером для каждой платформы. В этом классе есть свойство место расположения файла, который нужно отобразить. Затем кастомный рендерер отображает его.
Отображение файла кастомным рендерером поможет избежать перехода в специфическое месторасположение файла в iOS. Но опять-таки, это только в этом специфичном исполнении сценария. Важный момент – это потребность класса App в точке входа для доступа iOS проекта.

Итог

В целом, открыть файл из какого-то приложения в Xamarin.Forms приложении не так сложно. Есть некоторые формальности, одна из которых – скорректировать файл Info.plist, чтобы зарегистрировать приложение как способное обрабатывать файлы определенного типа. И необходимость переписать OpenUrl функцию для iOS приложения.

После этого все зависит от Xamarin.Forms. Необходимо создать точку входа в классе App , чтобы AppDelegate в iOS мог обратиться к «общей» части кода. Здесь нужно действовать в зависимости от того, что необходимо сделать с файлом. Может понадобиться написание кастомного рендерера для отображения. Или можно все сделать в общем проекте, если не понадобится дополнительный функционал платформы.

Благодарим за перевод

Александр Алексеев — Xamarin-разработчик, фрилансер. Работает с .NET-платформой с 2012 года. Участвовал в разработке системы автоматизации закупок в компании Digamma. C 2015 года ушел во фриланс и перешел на мобильную разработку с использованием Xamarin. В текущее время работает в компании StecPoint над iOS приложением.

Ведет ресурс XamDev.ru и сообщества «Xamarin Developers» в социальных сетях: VK, Facebook, Telegram.

  • Microsoft
  • xamarin
  • xamarin.forms
  • xamarincolumn
  • мобильная разработка
  • разработка под android
  • разработка под ios
  • Блог компании Microsoft
  • Разработка под iOS
  • Разработка мобильных приложений
  • C#
  • Xamarin

Как открыть pdf файл?

Выдает ошибку:
Java.Lang.RuntimeException: ‘Unable to get provider android.support.v4.content.FileProvider: java.lang.ClassNotFoundException: Didn’t find class «android.support.v4.content.FileProvider» on path: DexPathList[[zip file «/data/app/com.companyname.lexemes_android-4Y5mjVem9TgeT6umzAvz7A==/base.apk»],nativeLibraryDirectories=[/data/app/com.companyname.lexemes_android-4Y5mjVem9TgeT6umzAvz7A==/lib/x86, /data/app/com.companyname.lexemes_android-4Y5mjVem9TgeT6umzAvz7A==/base.apk!/lib/x86, /system/lib]]’

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *