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].

2015-10-21

Convert and view PDF documents in Xamarin Forms applications

Introduction


Xamarin.Forms offers you a flexible cross-platform alternative to create data entry applications targeting multiple platforms at once. Sometimes you might need to create PDF file based on entered data, or show the existing PDF document to user. In this article we’ll demonstrate how to render existing PDF documents in a Xamarin.Forms app targeting iOS and Android using Apitron PDF Rasterizer component.


Form layout and code


We’ll use very simple layout – a button to trigger rendering and an image to display the result. 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="XamarinFormsSample.MyPage">
    <ContentPage.Content>    
         <StackLayout Orientation="Vertical" Spacing="10" 
          VerticalOptions="FillAndExpand"
          HorizontalOptions="FillAndExpand">
             <StackLayout Padding="0,10,0,10">
                <Button x:Name="btnRenderPDF" Clicked="OnRenderPdfClicked" 
                Text="Render"/>
            </StackLayout>
            <ScrollView Orientation="Horizontal">
            <ScrollView Orientation="Vertical">
                 <Image x:Name="myImage" Aspect="Fill" VerticalOptions="StartAndExpand" 
                 HorizontalOptions="StartAndExpand"/>                
            </ScrollView>
            </ScrollView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

public partial class MyPage : ContentPage
{
    public MyPage ()
    {
        InitializeComponent ();
    }

    void OnRenderPdfClicked(object sender, EventArgs args)
    {
        Assembly currentAssembly = typeof(MyPage).GetTypeInfo().Assembly;

        using (Stream resourceStream = 
currentAssembly.
               GetManifestResourceStream("XamarinFormsSample.Data.testfile.pdf")) 
 {                
            byte[] buffer = new byte[resourceStream.Length];
            resourceStream.Read (buffer, 0, buffer.Length);

            var renderer = DependencyService.Get<IRenderer>();
            myImage.Source = ImageSource.FromStream (()=>
                {                        
                    return renderer.RenderToStream(buffer,0);
                });
        }                
    }
}

We read the PDF document from resources and pass it to platform dependent renderer implementation requested using the dependency service. It returns an image stream used as image source. 


Android implementation


using System;
using Xamarin.Forms;
using XamarinFormsSample;
using Apitron.PDF.Rasterizer;
using Android.Graphics;
using System.IO;
using XamarinFormsSample.Droid;
using Java.Nio;

[assembly: Dependency(typeof(Renderer))]

namespace XamarinFormsSample.Droid
{
    /// <summary>
    /// Android specific implementation of <see cref="XamarinFormsSample.IRenderer"/>
    /// interface.
    /// </summary>
    public class Renderer:IRenderer
    {
        public Renderer ()
        {
        }

        #region IRenderer implementation
        public System.IO.Stream RenderToStream (byte[] documentData, int pageIndex)
        {
            using (MemoryStream ms = new MemoryStream (documentData))
            {
                // open document
                using (Document doc = new Document (ms)) 
                {
                    // prepare for rendering
                    int width = (int)doc.Pages [pageIndex].Width;
                    int height = (int)doc.Pages [pageIndex].Height;
                    // render as ints array
                    int[] renderedPage =doc.Pages[pageIndex].RenderAsInts(width,height,
                        new Apitron.PDF.Rasterizer.Configuration.RenderingSettings ());

                    // create bitmap and save it to stream
                    Bitmap bm = Bitmap.CreateBitmap (renderedPage, width, height,
                        Bitmap.Config.Argb8888);

                    MemoryStream outputStream = new MemoryStream ();
                    bm.Compress (Bitmap.CompressFormat.Png, 100, outputStream);
                    outputStream.Position = 0;

                    return outputStream;
                }
            }
        }
        #endregion
    }
}


iOS implementation


using …

[assembly: Dependency(typeof(Renderer))]

namespace XamarinFormsSample.iOS
{
    // iOS specific implementation of <see cref="XamarinFormsSample.IRenderer"/> 
    // interface.
    public class Renderer:IRenderer
    {
        public Renderer ()
        {
        }
        public System.IO.Stream RenderToStream (byte[] documentData, int pageIndex)
        {
            using (MemoryStream ms = new MemoryStream (documentData))
            {
                // open document
                using (Document doc = new Document (ms)) 
                {
                    // prepare for rendering
                    int width = (int)doc.Pages [pageIndex].Width;
                    int height = (int)doc.Pages [pageIndex].Height;

                    // render the page to a raw bitmap data represented by byte array
                    byte[] imageData=ConvertBGRAtoRGBA(
                    doc.Pages[pageIndex].RenderAsBytes(width, height,
                        new RenderingSettings(), null));

                    // create CGDataProvider which will serve CGImage creation
                    CGDataProvider dataProvider =new CGDataProvider(imageData,0,
                        imageData.Length);

                    // create core graphics image using data provider created above, 
                    // note that we use CGImageAlphaInfo.Last(ARGB) pixel format
                    CGImage cgImage = new CGImage(width,height,8,32,width*4,
                        CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.Last, 
                        dataProvider, null, false, CGColorRenderingIntent.Default);

                    // create UIImage and save it to gallery
                    UIImage finalImage = new UIImage (cgImage);                                
                    return finalImage.AsPNG ().AsStream();
                }
            }                        
        }

        /// <summary>
        /// Converts the BGRA data to RGBA.
        /// </summary>
        /// <returns>Same byte array but with RGBA color dara.</returns>
        /// <param name="bgraData">Raw bitmap data in BGRA8888 format .</param>
        byte[] ConvertBGRAtoRGBA(byte[] bgraData)
        {
            // implemented simple conversion, swap 2 bytes.
            byte tmp;
            for(int i=0,k=2;i<bgraData.Length;i+=4,k+=4)
            {
                tmp = bgraData [i]; 
                bgraData [i] = bgraData [k];
                bgraData [k] = tmp;
            }
            return bgraData;
        }
    }
}


Results


The source PDF file rendered on both platforms is shown on the images below:

Pic. 1 Render PDF in Xamarin.Forms App ( Android

Pic.
1 Render PDF in Xamarin.Forms App ( Android) 


Pic. 2 Render PDF in Xamarin.Forms app ( iOS )

Pic. 2 Render PDF in Xamarin.Forms app ( iOS )

Conclusion


In this article we’ve shown how to convert to image and view PDF documents in Xamarin Forms applications. We used Apitron PDF Rasterizer .NET component for that, but if you need to create PDF documents or manipulate them you can use Apitron PDF Kit and do whatever you want with PDF files. Text extraction, context generation, adding signatures and many other features are wrapped by the easy to use API for your convenience. Contact us if you need any help and we’ll be happy to assist you. 

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

2015-10-10

ICC color profiles and ICC-based colors in PDF

Introduction


In color management, an ICC profile is a specific set of data that defines the color representation of the color reproduction device. Common term for this characteristic is “colorspace”.  Therefore each color reproduction device works with its own colorspace, and the rules used to manipulate colors within each colorspace, or to convert them between colorspaces are described in standards created by the International Color Consortium, hence the name ICC. Examples of well-known colorspaces are: RGB, CMYK, GRAY, LAB and XYZ.

A manufacturer of a color reproduction device may include a color profile along with the device for better color management. You may use these profiles and create PDF files which will include all data needed for reproduction on a selected device. Drawing primitives using colors defined by the ICC profile is possible with Apitron PDF Kit, and we’ll show you how to do it in our code section.

Code sample


Consider the code below. It adds two rectangles to PDF page using same colors from CMYK colorspace. The difference is in the way of defining these colorspaces, in first case we’re using ICC color profile downloaded from Adobe website, and in the second case we rely on default behavior provided by the PDF viewer – by means of the colorspace called DeviceCMYK in PDF specification.

static void Main(string[] args)
{
    using (Stream outputStream = File.Create("icccolors.pdf"))
    {
        using (FixedDocument doc = new FixedDocument())
        {
            // register CMYK profile "US Web Uncoated v2",
            // you can get it from Adobe website
            string profileName = "US Web Uncoated v2";
            doc.ResourceManager.RegisterResource(new ICCBasedColorSpace(profileName,
 File.ReadAllBytes("../../data/USWebUncoated.icc")));

            // create and add new page
            Page page = new Page();
            doc.Pages.Add(page);

            // create rectangular shape
            Path rectangle = new Path();
            rectangle.AppendRectangle(10,700,200,100);
                   
            // RECT 1
            // select CMYK colorspace for drawing using loaded color profile
            page.Content.SetNonStrokingColorSpace(profileName);
            page.Content.SetStrokingColorSpace(profileName);

            // select fill and stroke colors
            page.Content.SetNonStrokingColor(new double[]{0,1,0,0});
            page.Content.SetStrokingColor(new double[]{0,0,0,1});

            // fill and stroke the path
            page.Content.FillAndStrokePath(rectangle);
                   
            //RECT 2
            // select colors using device CMYK colorspace, the viewer will
            // use default CMYK profile for representing these colors
            page.Content.SetDeviceNonStrokingColor(new double[] { 0, 1, 0, 0 });
            page.Content.SetDeviceStrokingColor(new double[] { 0, 0, 0, 1 });

            // fill and stroke the path again
            page.Content.Translate(0,-120);
            page.Content.FillAndStrokePath(rectangle);
                   
            //save document
            doc.Save(outputStream);
        }
    }
}


Resulting document is shown on the image below (callouts are not the part of the generated document, they were added later for clarification).


Pic. 1 Paths drawn using colors from ICC colorspace and DeviceCMYK colorspace

You may clearly see the difference between the two. In first case we used the profile named “US Web Uncoated V2”, according to information about this profile that can be found on the internet, it is “designed to produce quality separations using U.S. inks under the following printing conditions: 260% total area of ink coverage, negative plate, uncoated white offset stock”.

The second one uses default CMYK color profile that is called DeviceCMYK in PDF specification, it seems that Adobe substitutes the profile named “US Web Coated (SWOP) v2” in this case, but we’re not 100% sure.

Using the correct color profile supplied with color reproduction devices, you may prepare your PDF documents for professional printing and avoid color misrepresentations related to color profile difference.

Conclusion


Using ICC colorprofiles, you may create PDF documents ready for professional printing and reproduction. Apitron PDF Kit for .NET component provides all necessary APIs for achieving this goal. You can download it on our website (link) and try for yourself. Create cross platform applications using our .NET PDF components and enjoy the quality of our software and support services. 

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