Search code examples
c#iosxamarin.iosarrayscgpdfdocument

Create a CGPDFDocument from a byte array


In MonoTouch I am looking to create a CGPDFDocument from a byte array transferred back text encoded from a web service. However MonoTouch does not seem to support creation from anything other than a local file or downloaded from a URL.

Anybody know how to do this?


Solution

  • One option would be to p/invoke into CGPDFDocumentCreateWithProvider to create your own instance of a CGPDFDocument. It should not be too complex since CGDataProvider already available in MonoTouch.

    OTOH receiving an array (from a web service) can consume a lot of memory (unless you're 100% sure about their small size). E.g. string to byte conversion, it must all fit in memory...

    TO be safe you might want to serialize the array (or better stream it directly if possible) to a local (temporary/cache) file first (to avoid another in-memory copy for the GCPDFDocument instance) and then call the existing CGPDFDocument.FromFile API.

    UPDATE: MonoTouch 5.3.3+ will provide new constructor for GCPDFDocument that accept a CGDataProvider. In the mean time you can use the following code.

    [DllImport (Constants.CoreGraphicsLibrary)]
    extern static IntPtr CGPDFDocumentCreateWithProvider (IntPtr provider);
    
    static GCPDFDocument FromArray (byte[] array)
    {
        using (var dp = new CGDataProvider (array, 0, array.Length) {
            return new CGPDFDocument (CGPDFDocumentCreateWithProvider (dp.Handle));
        }
    }