0

I am trying to implement the HTML to PDF and storing functionality in Xamarin.Forms. I have tried different 3rd party libraries such PDFSharpcore, Syncfusion.Xamarin.PDF,ITextSharp,Xamarin.PDF none of them worked for me. ITextSharp is the deprecated library so I don't want to use that. I have tried this https://www.c-sharpcorner.com/blogs/xamarinforms-pdf this is working well with converting from HTML to PDF functionality but storing part it is failing. It is giving SharePath voilation exception. I have tried the ways to find out why the exception is occuring, i have to tried to find the permissions for the folder in which Iam trying to save apparently I have the permissions to write in that folder. I have also checked if the File is being used by any other application or the processor that is also not showing any results. Any Ideas how I can achieve the functionality? I have used android native webview and webview client to render the HTML and converting that to byte stream.

Below is the code that I have used for android

  [Register("android/print/PdfLayoutResultCallback")]  
    public class PdfLayoutResultCallback : PrintDocumentAdapter.LayoutResultCallback  
    {  
        public PrintDocumentAdapter Adapter { get; set; }  
  
        public PDFToHtml PDFToHtml { get; set; }  
  
        public PdfLayoutResultCallback(IntPtr javaReference, JniHandleOwnership transfer)  
            : base(javaReference, transfer) { }  
  
        public PdfLayoutResultCallback() : base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer)  
        {  
            if (!(Handle != IntPtr.Zero))  
            {  
                unsafe  
                {  
                    JniObjectReference val = JniPeerMembers.InstanceMethods.StartCreateInstance("()V", GetType(), null);  
                    SetHandle(val.Handle, JniHandleOwnership.TransferLocalRef);  
                    JniPeerMembers.InstanceMethods.FinishCreateInstance("()V", this, null);  
                }  
            }  
  
        }  
  
        public override void OnLayoutFinished(PrintDocumentInfo info, bool changed)  
        {  
            try  
            {  
                var file = new Java.IO.File(PDFToHtml.FilePath);  
                var fileDescriptor = ParcelFileDescriptor.Open(file, ParcelFileMode.ReadWrite);  
                var writeResultCallback = new PdfWriteResultCallback(PDFToHtml);  
                Adapter.OnWrite(new PageRange[] { PageRange.AllPages }, fileDescriptor, new CancellationSignal(), writeResultCallback);  
            }  
            catch  
            {  
                PDFToHtml.Status = PDFEnum.Failed;  
            }  
  
            base.OnLayoutFinished(info, changed);  
        }  
          
        public override void OnLayoutCancelled()  
        {  
            base.OnLayoutCancelled();  
            PDFToHtml.Status = PDFEnum.Failed;  
        }  
  
        public override void OnLayoutFailed(ICharSequence error)  
        {  
            base.OnLayoutFailed(error);  
            PDFToHtml.Status = PDFEnum.Failed;  
        }  
    }  
  
    [Register("android/print/PdfWriteResult")]  
    public class PdfWriteResultCallback : PrintDocumentAdapter.WriteResultCallback  
    {  
        readonly PDFToHtml pDFToHtml;  
  
        public PdfWriteResultCallback(PDFToHtml _pDFToHtml, IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)  
        {  
            pDFToHtml = _pDFToHtml;  
        }  
  
        public PdfWriteResultCallback(PDFToHtml _pDFToHtml) : base(IntPtr.Zero, JniHandleOwnership.DoNotTransfer)  
        {  
            if (!(Handle != IntPtr.Zero))  
            {  
                unsafe  
                {  
                    JniObjectReference val = JniPeerMembers.InstanceMethods.StartCreateInstance("()V", GetType(), null);  
                    SetHandle(val.Handle, JniHandleOwnership.TransferLocalRef);  
                    JniPeerMembers.InstanceMethods.FinishCreateInstance("()V", this, null);  
                }  
            }  
  
            pDFToHtml = _pDFToHtml;  
        }  
  
  
        public override void OnWriteFinished(PageRange[] pages)  
        {  
            base.OnWriteFinished(pages);  
            pDFToHtml.Status = PDFEnum.Completed;  
        }  
  
        public override void OnWriteCancelled()  
        {  
            base.OnWriteCancelled();  
            pDFToHtml.Status = PDFEnum.Failed;  
        }  
  
        public override void OnWriteFailed(ICharSequence error)  
        {  
            base.OnWriteFailed(error);  
            pDFToHtml.Status = PDFEnum.Failed;  
        }  
    } 
  

{System.IO.IOException: Sharing violation on path /storage/emulated/0/Android/data/com.bt.WasteTracker.intune/files/temp/Example_1677226869970.pdf at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.…}

That is the exception when I tried to store the bytestream in the filepath

`using (var stream = new FileStream(this.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))

In the above code the exeption is occuring in the using line.

1 Answers1

0

First of all, you can try to use the FileShare.ReadWrite just as Jason said, such as:

using (var stream = new FileStream(this.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)

Or you can try to use the following code to write the file:

var filepath = Path.Combine("the folder","the file name");
using FileStream outputStream = System.IO.File.OpenWrite(filepath);
using StreamWriter streamWriter = new StreamWriter(outputStream);
streamWriter.Write(content);

The StreamWriter.Write(Parameter) method can accept a string or a char array. I have tried use this code to write a file successfuly.

And you can refer to the similar case about System.IO.IOException: Sharing violation on path. It seems a common error. There are many solutions about it.

Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14
  • No, I havent tried that but what solved my problem is that I have removed await FileStream.WriteAsync(PDFStreamArray, 0, PDFStreamArray.Length); this line from my code seems like file is being written twice cause I have checked the bytes written is double than the bytes. and sharing voilation exception is becuase of the file is being used/ or open to write already that is the reason why we are getting double bytestream – karanam kalyani Mar 06 '23 at 11:15