pdf links

PDF Rendering
Convert PDF to Image (.NET)
Convert PDF to image on Android (Xamarin)
Convert PDF to image on iOS (Xamarin)
Convert PDF to image in Windows Store apps (.NET)
Convert PDF to image in Windows Phone apps (.NET)
PDF to image in Universal Windows Store apps (.NET)
Free PDF Viewer control for Windows Forms (.NET)
How to integrate PDF Viewer control in WPF app (.NET)
Creating WPF PDF Viewer supporting bookmarks (.NET)
Cross-platform PDF Viewer using GTK# (MONO)
Silverlight PDF viewer control (Silverlight 5)
Multithreaded PDF rendering (.NET)
Convert pdf to image in Silverlight app (C# sample)
How to set fallback fonts for PDF rendering (C#)
Avoiding the out-of-memory exception on rendering (C#)
PDF viewer single page application (WebAPI, AngularJS)
PDF viewer control for Windows 10 universal applications
Use custom ICC profile for CMYK to RGB conversion
PDF layers - separate images, text, annotations, graphics

PDF Forms Creation PDF Security
Conversion to PDF/A
Other topics
PDF Document Manipulation PDF Content Generation
Fixed and Flow layout document API (.NET)
Creation of grids and tables in PDF (C# sample)
How to create interactive documents using Actions (C# sample)
Text flow effects in PDF (C# sample)
How to generate ordered and bulleted lists in PDF (C# sample)
Convert HTML to PDF using flow layout API (C# sample)
How to use custom fonts for PDF generation (.NET)
Create document with differently sized pages (C#)
Create PDF documents using MONO (C#/MONO/Windows/OSX)
How to use background images for content elements (C#/PDF Kit/FlowLayout)
Add transparent images to PDF document (C#)
Draw round rect borders in PDF documents(C#)
ICC color profiles and and ICC based colors in PDF (C#)
How to use bidirectional and right to left text in PDF (C#)
Create PDF documents from XML templates (C# sample)
How to resize PDF pages and use custom stamps (C#)
Add header and footer to PDF page (.NET sample)
How to use clipping mask for drawing on PDF page
Fill graphics path with gradient brushes in PDF (Shadings)
Apitron PDF Kit and Rasterizer engine settings
Add layers to PDF page (optional content, C# sample)
How to create free text annotation with custom appearance
PDF Content Extraction PDF Navigation
PDF to TIFF conversion
Contact us if you have a PDF related question and we'll cover it in our blog.

2015-10-26

How to create PDF forms in Xamarin.Forms applications

Introduction


Xamarin.Forms might be the best fit technology for cross-platform forms data processing applications as its name suggests. Nowadays we have lots of forms to fill, and many apps emerge to help us with that. In many cases, we also need these forms to be exported in some way or read afterwards and the PDF became the de-facto standard.

Luckily, the PDF standard offers such things like fields – document properties that can be added, saved, read and modified during the document’s lifetime.  Furthermore, they can be interactively edited using PDF viewers, being linked to corresponding widget annotation (see the section 12.7 Interactive Forms of the PDF specification for the details).

In this article, we’ll show you how to create a simple PDF form using Xamarin.Forms and Apitron PDF Kit .NET component.

Form layout and code


We’ll use very simple layout – a button to trigger the saving action and a few text boxes for entering the data of an imaginable employee. See the XAML and code behind below:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="PDFFormCreationSample.MyPage">
        <StackLayout Orientation="Vertical" Padding="10,20,10,10">
            <Entry x:Name="firstName" Text="{Binding FirstName, Mode=TwoWay}" 
                Placeholder="Enter employee's first name here"/>
            <Entry x:Name="lastName" Text="{Binding LastName, Mode=TwoWay}" 
                Placeholder="Enter employee's last name here"/>
            <Entry x:Name="position" Text="{Binding CurrentPosition, Mode=TwoWay}" 
                Placeholder="Enter employee's position here"/>
            <Button Text="Save to PDF" Clicked="OnSaveClicked" />    
        </StackLayout>
</ContentPage>


public partial class MyPage : ContentPage
{
    Employee currentEmployee;

    public MyPage ()
    {
        InitializeComponent ();
        BindingContext = currentEmployee = new Employee ();
    }

    public void OnSaveClicked(object sender, EventArgs args)
    {
        // create flow document and register necessary styles
        FlowDocument doc = new FlowDocument(){ Margin = new Thickness (10,10,10,10)};
        // the style for all document's textblocks and textboxes
        doc.StyleManager.RegisterStyle("TextBlock, TextBox"new Style()        
            {                
                Font = new Font("Helvetica",20),
                Color = RgbColors.BlackDisplay = Display.Block                        
            });

        // the style for the section that contains employee data
        doc.StyleManager.RegisterStyle ("#border"new Style (){
                Padding = new Thickness(10,10,10,10),
                BorderColor = RgbColors.DarkRed,Border = new Border(5), BorderRadius=5
            }
        );

        // add PDF form fields for later processing
        doc.Fields.Add (new TextField ("firstName", currentEmployee.FirstName));
        doc.Fields.Add (new TextField ("lastName", currentEmployee.LastName));
        doc.Fields.Add (new TextField ("position", currentEmployee.CurrentPosition));
        // create section and add text block inside
        Section section = new Section (){Id="border"};

        // ios PDF preview doesn't display text fields correctly, 
        // uncomment this code to use simple text blocks instead of text boxes                   // section.Add(new TextBlock(string.Format("First name:{0}",
        // currentEmployee.FirstName)));
        // section.Add(new TextBlock(string.Format("Last name: {0}", 
        // currentEmployee.LastName)));
        // section.Add(new TextBlock(string.Format("Position: {0}",
        // currentEmployee.CurrentPosition )));

        section.Add(new TextBlock("First name: "));
        section.Add(new TextBox("firstName"));
        section.Add(new TextBlock("Last name: "));
        section.Add(new TextBox("lastName"));
        section.Add(new TextBlock("Position: "));
        section.Add(new TextBox("position"));
        doc.Add (section);

        // get io service and generate output file path
        var fileManager = DependencyService.Get<IFileIO>();
        string filePath = Path.Combine (fileManager.GetMyDocumentsPath (), "form.pdf");

        // generate document
        using(Stream outputStream = fileManager.CreateFile(filePath))
        {
            doc.Write (outputStream, new ResourceManager());
        }
        // request preview
        DependencyService.Get<IPDFPreviewProvider>().TriggerPreview (filePath);
    }
}


We used flow layout API to create the PDF form, and, unfortunately, as built-in iOS PDF preview doesn’t display the PDF forms correctly, we’ve used simple text blocks instead of text fields (see the commented lines) for demoing on iOS. We also used DependencyService to request the platform specific IO and preview functionality.

Results


PDF forms generated by the iOS and Android versions are shown on the images below:

Pic. 1 Create PDF form using Xamarin.Forms  (iOS UI)

Pic. 1 Create PDF form using 
Xamarin.Forms  (iOS UI)

Pic. 2 Created PDF form (iOS preview)


Android:

Pic. 3 Create PDF form using Xamarin.Forms (Android UI)

Pic. 3 Create PDF form using 
Xamarin.Forms (Android UI)
Pic. 4 PDF form generated by the Xamarin.Forms app (Android)

Pic. 4 PDF form generated by
 the Xamarin.Forms app (Android)


If there is no default viewer found on your Android device, you may navigate to the indicated folder, copy the generated PDF form to the PC and view it using installed PDF viewer.

On the right image you can see that form fields are represented by editable text boxes and can be changed after the form creation. It’s possible to change this behavior by making the fields read-only.

Conclusion


Apitron PDF Kit is fully compatible with Xamarin.Forms and can be used for creation of data-entry and data processing apps that require PDF export of import functionality. It’s also available for other platforms offering the same API for .NET applications running on desktops, windows phones, tablets and even web servers. You can download it by the following link. The complete example can be found in our GitHub repo.

Downloadable version of this article can be found by the following link [PDF].

No comments:

Post a Comment