XamDev
XamDev

Reputation: 45

Convert Byte Array to pdf for UWP

I am working on Xamarin.Forms-UWP. I want to convert byte array stored in the database to pdf for Windows phone. I know how to convert var base64Binarystr = "ABCDS" byte[] bytes = Convert.FromBase64String(base64Binarystr );

Can anyone help as how to display pdf? Just a pointer- I have multiple pdf files so I cannot add all the files to the application or store on the disk.

Appreciate for any pointers on this. Thanks!

Upvotes: 0

Views: 715

Answers (1)

Yuri S
Yuri S

Reputation: 5370

Every received file can be stored with the same name (I used "my.pdf") then there is no risk for too many files stored. If you need to cache files then you can give different names. The pdf viewer didn't want to show files from Local, Temp or Downloads folder for me though I tried ms-appdata, so I had to move the file from Local folder to Assets to display the way viewer "wants" it via ms-appx-web. Downloads folder also has a problem with CreationCollisionOption.ReplaceExisting, it says invalid parameter if file already exists instead of replacing it but Local and Temporary folder behave correctly.

        /////////////// store pdf file from internet, move it to Assets folder and display ////////////////////
        //bytes received from Internet. Simulated that by reading existing file from Assets folder
        var pdfBytes = File.ReadAllBytes(@"Assets\Content\samplepdf.pdf");
        try
        {
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder; //or  ApplicationData.Current.TemporaryFolder
            StorageFile pdfFile = await storageFolder.CreateFileAsync("my.pdf", CreationCollisionOption.ReplaceExisting);
            //write data to created file
            await FileIO.WriteBytesAsync(pdfFile, pdfBytes);
            //get asets folder
            StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Assets");
            //move file from local folder to assets
            await pdfFile.MoveAsync(assetsFolder, "my.pdf", NameCollisionOption.ReplaceExisting);
        }
        catch (Exception ex)
        {
        }
        Control.Source = new Uri(string.Format("ms-appx-web:///Assets/pdfjs/web/viewer.html?file={0}", "ms-appx-web:///Assets/my.pdf")); //local pdf

Upvotes: 2

Related Questions