Generate PDF with local images from XML with Xamarin.iOS

This code sample generates a PDF from XML with an image that is included as resource. Here is the XML:

<document>
    <section>
        <paragraph type="textparagraph">
            <fragment>Hello world</fragment>
        </paragraph>
        <paragraph type="TallComponents.ResourceImage" path="foopdf.jpg"/>
    </section>
</document>

Note that the type of the image paragraph is TallComponents.ResourceImage. This is a specialization of TallComponents.PDF.Layout.Paragraphs.Image. This derived class overrides Compose to change the Image.Path property so that it points to the embedded resource image:

using System;
using System.IO;
using Foundation;
using TallComponents.PDF.Layout;
using TallComponents.PDF.Layout.Paragraphs;

namespace TallComponents
{
    public class ResourceImage : Image
    {
        protected override void Compose(Document doc)
        {
            base.Path = System.IO.Path.Combine(NSBundle.MainBundle.BundlePath, base.Path);
        }
    }
}

The following code reads the XML and generates the PDF document:

string bundlePath = NSBundle.MainBundle.BundlePath;
string xmlPath = Path.Combine(bundlePath, WebUtility.UrlEncode(customWebView.Uri));

Document document = new Document();
document.Read(xmlPath);

// convert to PDF and save
string pdfPath = Path.Combine(bundlePath, "out.pdf");
using (FileStream fs = new FileStream(pdfPath, FileMode.Create))
{
    document.Write(fs);
}

The full code sample displays the generated PDF using UIWebView. It is available on github.

Download TallPDF.NET 5.0
We will send you a download link
Why do we ask your email address?
We send tips that speed up your evaluation
We let you know about bug fixes
You can always unsubscribe with one click
We never share your address with a 3rd party
Thank you for your download

We have sent an email with a download link.