Open PDF Document in Hololens 2 from the file browser

Copper Contributor
I am trying to open a pdf document located in the persistent data path, in the file explorer, in the hololens 2 device but when trying to open it by c# code in Unity, nothing happens. I've tried with the code provided in the question locted in this link and it appear to happen an exception that sais this: "Exception of type 'System.Exception' was thrown". Does anyone know what is happening and how can I fix it?

This is the code I've used to do it:

using UnityEngine;
using UnityEngine.Networking;
using System;
using System.IO;
using System.Collections;
using System.Diagnostics;
using TMPro;
using System.Threading.Tasks;

#if !UNITY_EDITOR && UNITY_WSA
using System;
using System.Threading.Tasks;
using Windows.System;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Data.Pdf;
#endif

public class PdfDownloader : MonoBehaviour
{
    public string pdfUrl = "https://grados.ugr.es/primaria/pages/infoacademica/archivos/ejemplostfg/!";
    public string destinationPath = "my-file.pdf";
    int pg = 0; // Definir e inicializar la variable pg

    [SerializeField] private GameObject PDFPlane = null;

    [SerializeField] private TextMeshProUGUI text = null;

#if !UNITY_EDITOR && UNITY_WSA
    PdfDocument pdfDocument;
#endif

    public void download()
    {
        StartCoroutine(DownloadPdf());
    }

    IEnumerator DownloadPdf()
    {
        UnityWebRequest www = UnityWebRequest.Get(pdfUrl);
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            UnityEngine.Debug.LogError("Error al descargar el archivo PDF: " + www.error);
        }
        else
        {
            string filePath = Path.Combine(Application.persistentDataPath, destinationPath);
            SaveFile(filePath, www.downloadHandler.data);
            UnityEngine.Debug.Log("Archivo PDF descargado correctamente en: " + filePath);
            text.text += "Archivo PDF descargado correctamente en: " + filePath+ "\n";

            // Abrir el archivo PDF
            LoadAsync();
            text.text += "Abierto" + "\n";
        }
    }

    void SaveFile(string path, byte[] data)
    {
        try
        {
            // Crear el directorio si no existe
            string directory = Path.GetDirectoryName(path);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
                text.text += "Creado" + "\n";
            }

            // Escribir los datos del archivo en el archivo especificado
            File.WriteAllBytes(path, data);
            text.text += "Escrito" + "\n";
        }
        catch (Exception e)
        {
            UnityEngine.Debug.LogError("Error al guardar el archivo: " + e.Message);
            text.text += "Error al guardar el archivo: " + e.Message+ "\n";
        }
    }


    public async void LoadAsync()
    {
        string path = Application.persistentDataPath;

#if !UNITY_EDITOR && UNITY_WSA
text.text += "Empiezo "+ "\n";
        try 
    {           
        StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(path);
        /*StorageFolder storageFolder = KnownFolders.CameraRoll;*/
        text.text += "Empiezo 2 "+ "\n";
        StorageFile sampleFile = await storageFolder.GetFileAsync("my-file.pdf");
        text.text += "Empiezo 3 "+ "\n";
        //pdfDocument is an instanced object of type PdfDocument
        pdfDocument = await PdfDocument.LoadFromFileAsync(sampleFile);
        text.text += "Folder path 2: " + storageFolder + "\n";
    }
    catch (Exception e)
    {
        text.text += "1: " + e.Message;
        
    }
    text.text += "listo";
#endif

    }

    public async void ChangePageAsync()
    {
        text.text += "Voy" + "\n";
#if !UNITY_EDITOR && UNITY_WSA
        text.text += "Empiezo "+ "\n";
        //pg is the page to load
        using (PdfPage firstPage = pdfDocument.GetPage((uint)pg))
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            await firstPage.RenderToStreamAsync(stream);

            MemoryStream tempStream = new MemoryStream();
            await stream.AsStream().CopyToAsync(tempStream);

            byte[] imgBytes = new byte[16 * 1024];
            imgBytes = tempStream.ToArray();

            Texture2D imgTex = new Texture2D(2048, 2048, TextureFormat.BC7, false);
            imgTex.LoadImage(imgBytes);
            imgTex.filterMode = FilterMode.Bilinear;
            imgTex.wrapMode = TextureWrapMode.Clamp;

            MeshRenderer meshRenderer = PDFPlane.GetComponent<MeshRenderer>();
            Material mat = meshRenderer.material;
            mat.SetTexture("_MainTex", imgTex);
            mat.mainTextureScale = new Vector2(1, 1);

            text.text += "pg: " + pg + "\n";
        }
#endif

    }

}

In the code, I first download it and then try open it. The text.text are debugging lines I've added. The pdf URL is an example pdf obtained from google.

I want to show using an Unity app a pdf that has been downloaded before a pdf, avoiding the limitations tah hololens 2 has when opening a local file.

0 Replies