How to open PDF in xamarin.forms?

How to open PDF in xamarin.forms?

«1

Answers

  • StephaneDelcroixStephaneDelcroix USInsider, Beta ✭✭✭✭

    A proper solution would require a custom control and custom renderers. But if you don't want to go that far, just open them in a WebView

  • B.6242B.6242 INMember

    @StephaneDelcroix‌
    how to open pdf from local path in Webview?

  • walbiwalbi SEUniversity ✭✭

    Hi

    I'm also trying to do open a pdf from local path, but haven't been able to get it working. Any suggestions? Tried the example at http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/webview/. Even tried with local html file, but just a blank page.

  • walbiwalbi SEUniversity ✭✭

    Hi again

    I found a solution for my issue now, in the BaseUrlWebViewRenderer I added this
    public override void LoadRequest(NSUrlRequest r) { base.LoadRequest(new NSUrlRequest(NSUrl.FromFilename(r.Url.ToString()))); }

    and in the page

    _browser = new BaseUrlWebView(); _browser.VerticalOptions = LayoutOptions.FillAndExpand; _browser.HorizontalOptions = LayoutOptions.FillAndExpand; _browser.Source = new UrlWebViewSource() {Url = "report.pdf"};

    Not sure if its the optimal way to do it, but it works now.

  • AndrewRobertsAndrewRoberts USMember ✭✭

    If you're willing to spend some money, it looks like Syncfusion has a solution for viewing and editing PDF files.
    http://www.syncfusion.com/products/xamarin

  • B.6242B.6242 INMember

    @AndrewRoberts
    In Xamarin.Froms, I already created pdf file but how to open pdf which i saved.

  • stevencallanstevencallan USMember, Beta

    I'm having trouble with this too. I have a resource file - pdf, and I can't figure out how to display it in a xamarin.forms webview. Thanks for any help.

    Steve

  • B.6242B.6242 INMember
    edited December 2014

    @stevencallan‌
    I got Solution how to create pdf and excel file and also open it in xamarin.forms.
    First, I would like to know about Dll which i have used in project. 1) Flexcel.dll used for Excelsheet 2) Xfinium.Pdf.PCL used for Pdf. Both dll is trail of 30 days. means that is paid.
    If you want to open pdf directly in pdf reader then See following Code.
    Add new XAML Form Page. I created XAML FORM PAGE which i gave name "PDFPage".

    using FlexCel;
    using FlexCel.Core;
    using FlexCel.Report;
    using FlexCel.XlsAdapter;
    using Xamarin.Forms;
    using Xfinium.Pdf;
    using Xfinium.Pdf.Graphics;
    using Xfinium.Pdf.Standards;
    
    namespace UsingPDFAndExcel
    {
    public partial class PDFPage
        {
            public PDFPage()
            {
                InitializeComponent();
                btnPDF.Clicked += btnPDF_Clicked;
                btnExcel.Clicked += btnExcel_Clicked;
            }
            private void btnExcel_Clicked(object sender, EventArgs e)
            {
                XlsFile xls = new XlsFile(1, true);
                xls.SetCellValue(1, 1, "Hello from FlexCel!");
                xls.SetCellValue(2, 1, 7);
                xls.SetCellValue(3, 1, 11);
                xls.SetCellValue(4, 1, new TFormula("=Sum(A2:A3)"));
    
                MemoryStream stream = new MemoryStream();
                xls.Save(stream,);
    
                Xamarin.Forms.DependencyService.Get<ISaveAndLoad>().Save("Formulas.xlsx", "application/msexcel", stream);
            }
    
            private async void btnPDF_Clicked(object sender, EventArgs e)
            {
                PdfFixedDocument document = new PdfFixedDocument();
                PdfPage page = document.Pages.Add();
                PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);
                PdfBrush brush = new PdfBrush();
                page.Graphics.DrawString("World is a common name for the whole of human civilization, specifically human experience, history, or the human condition in general, worldwide, i.e. anywhere on Earth or pertaining to anywhere on earth.", helvetica, brush, 100, 100);
    
                MemoryStream stream = new MemoryStream();
                document.Save(stream);
    
                Xamarin.Forms.DependencyService.Get<ISaveAndLoad>().Save("HelloWorld.pdf", "application/pdf", stream);
            }
        }
    

    }

    And also created inteface Which name is "ISaveAndLoad" in PCL.

    public interface ISaveAndLoad
        {
            Task Save(string filename, string contentType, MemoryStream stream);
        }
    

    in last, I also created class file in Android project which name is SaveAndLoad_Android. its inherited ISaveAndLoad.

    public class SaveAndLoad_Android : ISaveAndLoad
        {
            public async Task Save(string fileName, String contentType, MemoryStream stream)
            {
                string root = null;
                if (Android.OS.Environment.IsExternalStorageEmulated)
                {
                    root = Android.OS.Environment.ExternalStorageDirectory.ToString();
                }
                else
                    root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
    
                Java.IO.File myDir = new Java.IO.File(root + "/Documents");
                myDir.Mkdir();
    
                Java.IO.File file = new Java.IO.File(myDir, fileName);
    
                if (file.Exists()) file.Delete();
    
                try
                {
                    FileOutputStream outs = new FileOutputStream(file);
                    outs.Write(stream.ToArray());
    
                    outs.Flush();
                    outs.Close();
                }
                catch (Exception e)
                {
                }
                if (file.Exists())
                {
                    Android.Net.Uri path = Android.Net.Uri.FromFile(file);
                    string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                    string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                    Intent intent = new Intent(Intent.ActionView);
                    intent.SetDataAndType(path, mimeType);
                    Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                }
            }
    
        }
    

    Thanks,
    Bhavika Chaudhari

  • stevencallanstevencallan USMember, Beta

    Thank you Bhavika, I did consider this product (and it does look like a very good choice) but I'm not ready to make an investment just yet. I hope to just get something running without extra cost.

    Thank you,

    Steve

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    I haven't understand if it is possible to view a PDF file (from a url) in a xamarin.forms.webview.
    I've tried with this simple code

        WebView wv = new WebView ();
        wv.Source = "http://developer.xamarin.com/guides/cross-platform/getting_started/introduction_to_mobile_development/offline.pdf";
        Content = wv;
    

    but only a white form appears

    (if I have wv.source = "http://xamarin.com" the site appears correctly)

  • eHealtheHealth USUniversity ✭✭

    Ok guys, here's my PDFViewer implementation. It uses custom renderer for each platform. In iOS i use WebView and it works without problems. In Android i use https://github.com/gearit/RadaeePDF-Xamarin and it works but after opening some PDFs it gets out of memory and i don't know "yet" how to solve it. I hope it helps and maybe someone can help me to solve the issue. Cheers!

  • eHealtheHealth USUniversity ✭✭

    @AlessandroCaliaro @B.6242 @StephaneDelcroix @walbi @iambeanie @stevencallan hi guys, i fixed my solution and it's not only useful for Xamarin.Forms, it's Xamarin in general. I will publish to github soon and post the link here. Thanks.

  • RobertDebaultRobertDebault USUniversity ✭✭✭

    @alexrainman.5013 Alex can't wait to see what you have.

  • JacobPoulsen_JacobPoulsen_ DKMember ✭✭✭

    Any news on your PDFViewer Alex?

  • keannan5390keannan5390 USMember

    Looks to me as though that PDF library is built upon a paid pdf SDK for android (RadaeePDF appears to be pay-for-license only). If I'm incorrect on that, then it's awesome.

  • NMackayNMackay GBInsider, University mod

    Seems to cost between $460 and $870. USD.

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    wow, it creates PDF with the power of the mind

  • alexrainmanalexrainman USMember ✭✭

    @Jacob_B_Poulsen @RobertDebault Sorry for not answering sooner guys. And yes, it's based on radaee but it works really nice. Anyways, i implemented android-pdfview as a custom renderer too but it has a limitation. I couldnt change the orientation. I will upload everything to github this weekend. Cheers!

  • alexrainmanalexrainman USMember ✭✭

    @Jacob_B_Poulsen @RobertDebault https://github.com/alexrainman/Xamarin.Forms.PDFViewer. I need to test and upload the custom renderer for android-pdfview. Tomorrow!

  • RobertDebaultRobertDebault USUniversity ✭✭✭

    @alexrainman1975 thanks for this Alex....

  • alexrainmanalexrainman USMember ✭✭

    @Jacob_B_Poulsen @RobertDebault guys i has been busy starting in a new Job. Has you been able to use this?

  • RobertDebaultRobertDebault USUniversity ✭✭✭

    Not yet @alexrainman1975 I had to find another way of doing this prior to your post. I will be back on that project in a couple of weeks though.

  • @Bhavika Chaudhari

    Please provide me the zip file of project in which you have used Xfinium.Pdf.PCL

    It will be very helpful, thanks in advance.

  • hvaughanhvaughan USMember ✭✭✭

    @walbi
    I realize that you commented a while ago but I also wanted to mention this for anyone having this problem. For me the WebView would not show up unless I gave it a HeightRequest and WidthRequest.

    If I made a brand new page and put in a WebView, it would work fine without the sizes. But, for some reason, after I started adding in more functionality to the code-behind and ViewModel, it would stop showing up until I gave it a size.

    Took me forever to figure this out!

  • hvaughanhvaughan USMember ✭✭✭

    @AlessandroCaliaro
    Just realized you had run into this issue also on this thread. See my post above if you are still interested.

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @hvaughan, sorry, I've not understand your post... My english is not perfect.
    If you would like to know about my experience in opening pdf in web view, I have tried in XF with Android with no success.
    So I've used dependency service to open docs in Android and iOS

  • How would this be done in a Windows Store app? Having a hard time finding documentation on this.

  • JesseMJesseM USMember ✭✭

    I would also like to know how its done for Windows apps?

  • Abhi_XamarinAbhi_Xamarin USMember

    @JesseM
    @ChrisBohatkaAztek

    You need to use in build launcher in windows store app.

    Which will automatically select the appropriate program for opening file, or will show option to user.

    var success = await Windows.System.Launcher.LaunchFileAsync(file);

  • JesseMJesseM USMember ✭✭

    @Abhi_Xamarin

    Thanks for the info. So is this something that could be done in a custom renderer?

    In my case, the pdf is being downloaded as a base64 encoded string. Can you provide more info on how this could be loaded and viewed?

  • Abhi_XamarinAbhi_Xamarin USMember

    @JesseM

    I apologise, I mistook the question for Windows store app.

    In case of Xamarin form, their is no out of box PDF viewer is available.

    1. You either need to use Xamarin Dependency Service & implement PDF viewer in targeted platforms, like android, ios
    2. You can also use Device.OpenURI, which takes the local URI of the file, which will give same effect of the Launcher in windows.
      It might prompt you with register app for opening that kind of URI (like open office in android, ios) or it will open file in browser which is capable of opening pdf file.

    http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/platform-specifics/

  • JesseMJesseM USMember ✭✭

    @Abhi_Xamarin

    Yeah, my requirement is to display a downloaded pdf. In iOS, I simply created a custom renderer in the iOS project and it works great.

    For Windows, I have been unable to find a solution. This is the only thing holding us up from using Xamarin for this project. We have everything else figured out...

  • RobertDebaultRobertDebault USUniversity ✭✭✭

    I created a custom render that opened the URI on the Android and Windows platforms. It works great as long as you do not have to control the screen once the PDF is opened. I am still looking for a controllable cross platform PDF Viewer and have heard their is one out there but it's not cheap.

  • VictorHGarciaVictorHGarcia USUniversity ✭✭

    @RobertDebault Which is the one you heard about it?

  • RobertDebaultRobertDebault USUniversity ✭✭✭

    @VictorHGarcia
    Here are the three I have been told might work. Xifinium is 300.00 and from what I have been told can be integrated into a Xamarin cross platform application. I have not tried it but my source is reliable.

    PDFTRON is another one I ran across and it will work on IOS and Android but I do not know about the Windows platform.

    Here is another one that might work as well Apitron "pdf-rasterizer".

  • JesseMJesseM USMember ✭✭

    @RobertDebault, so you are saying that you are able to open a PDF in xamarin forms in a Windows app? What are you doing, converting it to an image first?

    But yeah, on iOS and Android, this is pretty simple to figure out.

  • VictorHGarciaVictorHGarcia USUniversity ✭✭

    @RobertDebault I tried Xifinium and it does not provide a PDF Viewer, they provide all set of tools to edit PDFs, but not a viewer. I tried it already.

    about the PDFTRON it looked nice, but at the end the implementation was hard.

    I ended using an Android specific PDF Viewer: plugpdf.com it worked nice... but sadly there is no free version.

  • RobertDebaultRobertDebault USUniversity ✭✭✭

    I was told XFINIUM could be integrated into the apps. I have not tried it and it isn't cheap. https://components.xamarin.com/view/xfinium.pdf
    Here is another library that will work on IOS and Android but I do not know about windows... http://blog.pdftron.com/2014/01/24/getting-started-with-xamarin-android/
    There is also an independent developer working on one..
    http://blog.apitron.com/2013/06/creating-cross-platform-pdf-viewer.html

Sign In or Register to comment.