Search code examples
c#pdfunity-game-enginetexture2d

PDF to Texture2D array?


        //add icon
        byte[] fileBytes;
        Texture2D tex = null;

        if (File.Exists(*path to file*))
        {
            fileData = File.ReadAllBytes(*path to file*);
            tex = new Texture2D(2, 2);
            tex.LoadImage(fileBytes); 
        }

        //Read Texture into RawImage component
        GameObject.GetComponent<RawImage>().material.mainTexture = tex;

The above code can dynamically create and display images (jpeg, jpg, png) in Unity. I'm seeking to do the same for a PDF.

As far as I've seen through my research, there are PDF renderers available on the asset store however, they are expensive. Unfortunately there aren't any low grade or free options that load PDFs.

When I try to run my code on PDFs, it returns what looks like a factory image of a red question mark icon on a blank white background.

My code isn't reading the PDF into an array, creating an image/texture for each page. Before I dive head first and do this, I'm reaching out to you. Is this plausible? Are there better options? Am I SOL and my time would be better spent buying a pre-made asset?


Solution

  • Instead of working with the PDF directly it may be easier to convert to an image file, and use your code to convert the new image to the Texture2D array. I have not personally done this but this SO question seems to outline it pretty well:

    Save pdf to jpeg using c#