Products
TallPDF.NET 5.0
Created
9/4/2018
Tags
Generate PDF

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.