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-05-26

Converting html to pdf using markup parser (C# sample)

Introduction


Sometimes, you have a pre-built HTML fragment and would like to convert it to PDF with minimal changes in its appearance. You could manually split it down to atomic elements like spans, DIVs et cetera, create corresponding pdf objects and get the job done. However, it may become a time consuming and boring task which could be easily automated using Apitron PDF Kit for .NET component. Strictly speaking, it’s not an HTML to PDF converter in its traditional meaning, but it provides you with an API to parse any custom markup (provided it’s XML-based) into pdf, and HTML is just the one of the possible markups.

Content wrapped by a tag will be converted to a flow layout content element with its Class property set to the tag’s name. You can define appropriate styles, and style these elements using class selectors. Images can be added using reserved <img> tag. Attributes link and bookmark are reserved to produce internal or external links and bookmarks. Id attribute can be used to assign an Id to the element. While it all may sound a bit complicated it’s actually pretty simple and convenient. Let’s see the code sample from the next section.

If you’d like to read more about custom markup parsing, we have a free book for you - Apitron PDF Kit in action.

Basic HTML to PDF conversion


Source HTML


Consider the following html fragment:

...
<img src='myimage.jpg' height='48px' width='48px' style='float: left;'/>
Apitron PDF Kit for .NET component can be used to convert html fragments to PDF.
<br/>
Here you can see <b>bold</b> or <i>italic</i> text elements. Next sentence contains a hyperlink.
<br/>
Read the complete description of library's capabilities on the <a href='www.apitron.com/product/pdf-kit'>product page</a>
...


It has bold and italic text, image element, and a link to other web page. All these elements will be converted to content elements defined in flow layout API subset and styled according to defined styles. You may also note the use of additional <br> element - it adds a line break.

In web browser it looks like this:

Pic. 1 HTML fragment sample pdf

Pic. 1 HTML fragment sample

Conversion implementation


The following code performs the actual conversion:

public void ConvertHtmlFragmentToPDF()
{
    // prepare resources
    ResourceManager resourceManager = new ResourceManager();   

    // create and fill document
    FlowDocument doc = new FlowDocument() { Margin = new Thickness(5, 5, 5, 5) };
   
    // register styles for different elements
    doc.StyleManager.RegisterStyle(".img", new Style(){Float = Float.Left});
    doc.StyleManager.RegisterStyle(".b",new Style()
    {Font=new Font(StandardFonts.HelveticaBold,12)});
    doc.StyleManager.RegisterStyle(".i",new Style()
    {Font=new Font(StandardFonts.HelveticaOblique,12)});
    doc.StyleManager.RegisterStyle(".a", new Style(){Color=RgbColors.Blue,
    TextDecoration = new TextDecoration(TextDecorationOptions.Underline)});   

    // parse html markup
    doc.AddItems(ContentElement.FromMarkup(
    "<img src='myimage.jpg' height='48px' width='48px'"+
    "style='float: left;'/> Apitron PDF Kit for .NET component can be used to convert html"+
    " fragments to PDF.<br/> Here you can see <b>bold</b> or <i>italic</i> text elements. "+
    "Next sentence contains a hyperlink.<br/>Read the complete description of library's"+
    " capabilities on the <a href='www.apitron.com/product/pdf-kit'>product page</a>."));

    // save document
    using (Stream stream = File.Create("ConvertHtmlFragmentToPDF.pdf"))
    {
        doc.Write(stream, resourceManager);
    }
}


Results of the conversion are as follows:

Pic. 2 Markup parsing results pdf
Pic. 2 Markup parsing results

Conclusion


This post demonstrates how to create basic html to pdf converter and how to work with markup parsing API provided by Apitron PDF Kit. Create apps using your favorite .NET programming language: C#, VB .NET or any other. This library is available for many modern platforms, and you’ll most likely find yours supported. Check out the samples included in download package and let us know if you have any questions or comments.

2015-05-25

How to add or open pdf attachments - managing embedded files

Introduction


Embedded files, so-called pdf attachments, are used to guarantee the validity of the document in case there are external references in main content referring to them. For example, you can include supplementary documentation or appendix as an embedded file and link to it from some page of the main document. They can also be used in the same way as email attachments, and pdf document will act as “envelope” containing additional data. Using embedded files, PDF documents can be turned to self-contained structured units.

Detailed description of this PDF feature is contained in section 7.11.4 Embedded File Streams of the PDF specification.  

Adding PDF attachments


Code sample below shows how to add attachments to PDF document:

public void AddPDFAttachments()
{
    // create document
    FixedDocument doc = new FixedDocument();

    // add attachments
    doc.Attachments.Add("Appendix-A",new EmbeddedFile("appendix_a.txt"));
    doc.Attachments.Add("Appendix-B",new EmbeddedFile("appendix_b.jpg"));

    // create text object
    Page page = new Page();
    TextObject textObject = new TextObject(StandardFonts.Helvetica,14);
    textObject.AppendText("Document with attachments, created using Apitron PDF Kit
    for .NET");
    page.Content.Translate(10,820);
    page.Content.AppendText(textObject);

    // add first page
    doc.Pages.Add(page);

    // save document
    using (Stream stream = File.Create("pdf_attachments.pdf"))
    {
        doc.Save(stream);
    }
}

Resulting image:

Pic. 1 Add pdf attachments

Pic. 1 Add pdf attachments

Note the panel on the left, with a paperclip, it allows you to view all attachments and open the desired file for viewing. You can also enumerate and read attachments programmatically, see the next sample.

Reading pdf attachments


See the code sample below that enumerates all attachments and prints their names and sizes:

public void ReadPDFAttachments()
{
    // open document
    using (Stream stream = File.Open("pdf_attachments.pdf",FileMode.Open))
    {
        FixedDocument doc = new FixedDocument(stream);

        // enumerate attachments, print their names and sizes
        foreach (var fileEntry in doc.Attachments)
        {
            using (Stream attachmentStream = fileEntry.Value.GetStream())
            {
                Console.WriteLine("Found attachment: {0}, Size: {1} bytes",
                    fileEntry.Key,attachmentStream.Length);  
            }           
        }       
    }

    Console.ReadLine();
}

This code produces the following results:

Pic. 2 Enumerating and reading pdf attachments

Pic. 2 Enumerating and reading pdf attachments

You could also remove any attachment using the single call:

doc.Attachments.RemoveAttachment([attachment key]);

Conclusion


Embedded files feature is very useful for including additional data into the main PDF document without changing its content. And as you could see from this article, managing attachments is quite easy with fixed layout API offered by Apitron PDF Kit for .NET component. This pdf manipulation library can be used to add, remove, enumerate, or read any files attached to pdf documents. Contact us if you have any questions and we’ll be happy to answer.

2015-05-22

Ordered and unordered lists in pdf (c# sample)

Introduction


Lists are well known feature of HTML and CSS, and can be defined to be either unordered, using <ul> html element or ordered using <ol> html element. List item can be defined using <li> element. In opposite to HTML, PDF doesn’t have a special command or object to produce lists. They can only be crafted manually using all available PDF’s drawing capabilities.

Our .NET pdf component, Apitron PDF Kit, offers a flow layout API which makes it possible to create lists just like in HTML, taking care of all PDF specifics. It also supports standard html list bullets and numerations, e.g. circle, diamond, square, triangle; latin, roman, decimal - with their lower and upper variations, and also, custom markers.

Lists in flow layout API


Lists in Flow layout API can be created using Section objects, which become containers for the list items. The following properties of the section affect the list’s appearance:
  • ListStyle – defines whether the list is ordered, unordered or it’s a list item in other list 
  • ListCounter – the starting value for item’s counter in ordered lists, default value is 1 
  • ListMarker – the type of marker to be used by list items 
  • ListMarkerPadding – sets the padding around item’s marker 
List items can be defined using ListStyle = ListItem, and they have the following properties:
  • ListMarker – the type of marker used by an item 
  • ListMarkerPadding – sets the padding around the item’s marker 
Therefore, a list can be created using a section with appropriate style set + one or several items with ListStyle= ListStyle.ListItem, which is an equivalent to <li> html element.

Multilevel numbered lists can be created by enclosing one ordered list into another, and this technique will be shown in one of the samples below.

Unordered lists


Unordered or bulleted lists are lists where each item is marked with a specific bullet without implying a particular order. The only order that exists is the order of items creation. Let’s check the code sample below that shows how to create unordered lists:

public void CreateUnorderedLists()
{
    // prepare resources
    ResourceManager resourceManager = new ResourceManager();
    resourceManager.RegisterResource(new Apitron.PDF.Kit.FixedLayout.Resources.XObjects.Image("smile",
    "smile.jpg"));

    // create and fill document
    FlowDocument doc = new FlowDocument() { Margin = new Thickness(5, 5, 5, 5) };

    // define unordered list style
    doc.StyleManager.RegisterStyle(".ul", new Style()
    {
       ListStyle = ListStyle.Unordered,
       Width = Length.FromPercentage(20),
       ListMarkerPadding = new Thickness(2),
       Display = Display.InlineBlock,
       Font = new Font(StandardFonts.Helvetica,24)
    });   

    // define style for items added to the unordered list
    doc.StyleManager.RegisterStyle(".ul > *",
        new Style(){ ListStyle = ListStyle.ListItem });

    // create an array of markers for our lists
    ListMarker[] markers = new ListMarker[] {ListMarker.Circle,ListMarker.Diamond,  
    ListMarker.Triangle, ListMarker.Square, ListMarker.FromResourceId("smile") };

    // create 5 lists with different markers
    foreach (ListMarker marker in markers)
    {
        doc.Add(new Section(new TextBlock("Item 1"), new TextBlock("Item 2"),
        new TextBlock("Item 3"),new TextBlock("Item 4"){ListStyle = ListStyle.None})
        {Class = "ul", ListMarker = marker});
    }

    // save document
    using (Stream stream = File.Create("unordered_lists.pdf"))
    {
        doc.Write(stream, resourceManager);
    }
}

This code creates five bulleted lists with different list markers. Lists are made of sections styled via the class selector “ul”. All their child items become list items because of another style matching children of an element with class “ul” set. Please also note that each list has the unmarked item which is not the list item at all, it’s just a child item in the section. We changed its appearance by setting an inline style property ListStyle to None.

Last list has the custom image list marker set; it’s possible to use any XObject as a list marker for unordered list elements.

See the resulting image below:

Pic. 1 Unordered lists sample pdf

Pic. 1 Unordered lists sample

Ordered lists


Ordered lists or numbered lists can be used to show the explicit order of the elements, and usually apply decimal, roman, or latin numeration to their items.

The code below creates ordered lists:

public void CreateOrderedList()
{
    // prepare resources
    ResourceManager resourceManager = new ResourceManager();

    // create and fill document
    FlowDocument doc = new FlowDocument() { Margin = new Thickness(5, 5, 5, 5) };

    // define ordered list style
    doc.StyleManager.RegisterStyle(".ol", new Style()
    {
       ListStyle = ListStyle.Ordered,
       Width = Length.FromPercentage(20),
       ListMarkerPadding = new Thickness(2),
       Display = Display.InlineBlock, Font = new Font(StandardFonts.Helvetica, 24)
    });
    // define style for items added to the ordered list
    doc.StyleManager.RegisterStyle(".ol > *",new Style(){ListStyle=ListStyle.ListItem});

    // create an array of markers for our lists
    ListMarker[] markers = new ListMarker []{ListMarker.Decimal,ListMarker.UpperLatin, 
    ListMarker.LowerLatin, ListMarker.UpperRoman, ListMarker.LowerRoman };

    // create 5 ordered lists with different markers
    foreach (ListMarker marker in markers)
    {
        doc.Add(new Section(new TextBlock("Item 1"),new TextBlock("Item 2"),
        new TextBlock("Item3"))
        {
            Class = "ol", ListMarker = marker,
            ListCounter=(marker==ListMarker.LowerLatin||marker==ListMarker.UpperLatin) ?
            new ListCounter(0) : null
        });
    }

    // save document
    using (Stream stream = File.Create("ordered_lists.pdf"))
    {
        doc.Write(stream, resourceManager);
    }
}


This code creates five numbered lists each having its own marker, for latin markers we set initial value of the list counter to zero because default value for it is 1.
Resulting image is provided below:

Pic. 2 Ordered lists sample pdf

Pic. 2 Ordered lists sample


Multi-level ordered lists


It’s possible to combine several ordered lists to create multi-level lists, see the code below:

public static void MultilevelOrderedList()
{
    // prepare resources
    ResourceManager resourceManager = new ResourceManager();

    // create and fill document
    FlowDocument doc = new FlowDocument() { Margin = new Thickness(5, 5, 5, 5) };

    // define ordered list style
    doc.StyleManager.RegisterStyle(".ol", new Style()
    {
        ListStyle = ListStyle.Ordered,
        ListMarkerPadding = new Thickness(2),
        Font = new Font(StandardFonts.Helvetica,20)
    });

    // define style for items added to the ordered list
    doc.StyleManager.RegisterStyle(".ol > textblock",
    new Style(){ListStyle = ListStyle.ListItem});

    // create top list
    Section topList=new Section(new TextBlock("Item 1"),new TextBlock("Item 2"),
    new TextBlock("Item3")){ Class = "ol", ListMarker = ListMarker.Decimal };

    // create inner list level 1
    Section firstLevelList = new Section(new TextBlock("Inner item 1"),
    new TextBlock("Inner item  2"), new TextBlock("Inner item  3"))
    { Class = "ol", ListMarker = ListMarker.Decimal };

    // create inner list level2
    Section secondLevelList = new Section(new TextBlock("Inner item 1"),
    new TextBlock("Inner item  2"), new TextBlock("Inner item  3"))
    { Class = "ol", ListMarker = ListMarker.Decimal };

    // combine lists
    firstLevelList.Add(secondLevelList);   
    topList.Add(firstLevelList);

    // add text block to the top list
    topList.Add(new TextBlock("item 4"));

    // insert to list in the document
    doc.Add(topList);

    // save document
    using (Stream stream = File.Create("multilevel_list.pdf"))
    {
        doc.Write(stream, resourceManager);
    }
}

This code creates a list having three levels, see the image representing produced document. Notice the dots separating the list levels.

Pic. 3 Multi-level list sample pdf

Pic. 3 Multi-level list sample

Conclusion


Working with ordered and unordered lists is easy and simple with Flow layout API offered by Apitron PDF Kit component. This pdf library offers unmatched flexibility and can be used to create applications for many modern mobile, desktop and cloud platforms. Develop for Windows Forms, WPF, Android, iOS, Windows Phone, ASP.NET, Azure, MONO, Windows Store, and use the same API producing professionally looking PDF documents.

Contact us if you need any help with pdf processing, and we’ll provide you with a free consultation and pdf expert’s advice.