Share via


Print PDF file using Xamarin forms

Question

Wednesday, October 16, 2019 7:56 AM

Hello Developers

I am printing a Pdf file via print services. I implemented some code but not working through a exception java.lang.RuntimeException: Cannot print a malformed PDF file Please check my code and let me where i am wrong.

    public void Print(byte[] content)
    {
        //Android print code goes here
        Stream inputStream = new MemoryStream(content);
        string fileName = "form.pdf";
        if (inputStream.CanSeek)
        //Reset the position of PDF document stream to be printed
        inputStream.Position = 0;
        //Create a new file in the Personal folder with the given name
        string createdFilePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName);
        //Save the stream to the created file
        using (var dest = System.IO.File.OpenWrite(createdFilePath))
        inputStream.CopyTo(dest);
        string filePath = createdFilePath;
        PrintManager printManager = (PrintManager)Forms.Context.GetSystemService(Context.PrintService);
        PrintDocumentAdapter pda = new CustomPrintDocumentAdapter(filePath);
        //Print with null PrintAttributes
        printManager.Print(fileName, pda, null);
    }

This is my PrintDocumentAdapter

    internal class CustomPrintDocumentAdapter : PrintDocumentAdapter
    {
        private string filePath;
        public CustomPrintDocumentAdapter(string filePath)
        {
            this.filePath = filePath;
        }
        public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
        {
            if (cancellationSignal.IsCanceled)
            {
                callback.OnLayoutCancelled();
                return;
            }
            callback.OnLayoutFinished(new PrintDocumentInfo.Builder(filePath)
            .SetContentType(PrintContentType.Document)
            .Build(), true);
        }

        public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
        {
            try
            {
                using (InputStream input = new FileInputStream(filePath))
                {
                    using (OutputStream output = new FileOutputStream(destination.FileDescriptor))
                    {
                        var buf = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = input.Read(buf)) > 0)
                        {
                            output.Write(buf, 0, bytesRead);
                        }
                    }
                }
                callback.OnWriteFinished(new[] { PageRange.AllPages });
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                System.Diagnostics.Debug.WriteLine(fileNotFoundException);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception);
            }
        }
    }

i am calling Print method in this way

    private void GoToPrintPage_Clicked(object sender, EventArgs e)
    {
        using (var webClient = new WebClient())
        {
            var url = "https://vector.me/files/images/1/7/17513/tottenham_hotspur_fc.png";
            var imageBytes = webClient.DownloadData(new Uri(url));
            DependencyService.Get<Interface.IWifiPrinterConnectivity>().Print(imageBytes);
        }
    }

All replies (7)

Wednesday, October 16, 2019 3:43 PM ✅Answered

java.lang.RuntimeException: Cannot print a malformed PDF file Limitations on PDF Printing in Android, PDF’s must be version 1.6+ to be able to print in Android, anything below that Android PrintManager will say the PDF is malformed and can’t print.

Tutorial about Printing PDF on Xamarin.Forms. https://www.pujolsluis.com/printing-pdfs-and-images-xamarin-forms/


Monday, October 21, 2019 3:45 PM

I've just uploaded a first alpha of a printing NuGet for XF, supporting Android, iOS and UWP. I've built on top of code snippets from all sorts of sources, including https://www.pujolsluis.com/printing-pdfs-and-images-xamarin-forms/ . I did try using the contact form on that page to contact the author, but the anti-spam stuff wouldn't let my messages through.

@Jarvan - do you know how to programmatically check the version number of a PDF on Android, so that the malformed PDF exception can be avoided when PDFs are provided by a user?

Source for my NuGet is at https://github.com/johnshardman/Printing


Monday, October 21, 2019 6:06 PM

@Jarvan said:

java.lang.RuntimeException: Cannot print a malformed PDF file Limitations on PDF Printing in Android, PDF’s must be version 1.6+ to be able to print in Android, anything below that Android PrintManager will say the PDF is malformed and can’t print.

Tutorial about Printing PDF on Xamarin.Forms. https://www.pujolsluis.com/printing-pdfs-and-images-xamarin-forms/

@JohnHardman now i am able to print a image @Jarvan solution worked for me.

@JohnHardman I will try your solution as soon as possible.

@Jarvan and @JohnHardman thanks for help me :)


Tuesday, October 22, 2019 7:21 AM

how to programmatically check the version number of a PDF on Android @JohnHardman Sorry, I don't know how to get that.


Tuesday, October 22, 2019 7:23 PM

Hey @JohnHardman ! I'm glad to hear my article was useful to you guys, and that you have just released a new plugin for it, please do share so we can all use it! you can always contact me through my twitter @pujolsluis if my blog anti-spam blocks your comment, I'm always happy to hear feedback and what the Xamarin Community is doing :)


Tuesday, October 22, 2019 9:43 PM

@pujolsluis said: Hey @JohnHardman ! I'm glad to hear my article was useful to you guys, and that you have just released a new plugin for it, please do share so we can all use it!

The plugin is on NuGet. It's called Xam.Plugin.Printing . You'll need to select "Include prerelease" in Visual Studio to see it currently.

The repository, including documentation, is at https://github.com/johnshardman/Printing

@pujolsluis said: I'm always happy to hear feedback

I was curious to know if you'd identified a way of checking the PDF version against the v1.6+ constraint. I have to admit that I haven't researched it yet - it's on my list to do if you haven't found a way already. Far better to check the version number before trying to print the PDF, rather than attempt to handle the exception that can otherwise result.


Tuesday, October 22, 2019 10:15 PM

@JohnHardman said: The plugin is on NuGet. It's called Xam.Plugin.Printing . You'll need to select "Include prerelease" in Visual Studio to see it currently.

Thanks for the info, will give it a test!

@JohnHardman said: I was curious to know if you'd identified a way of checking the PDF version against the v1.6+ constraint. I have to admit that I haven't researched it yet - it's on my list to do if you haven't found a way already. Far better to check the version number before trying to print the PDF, rather than attempt to handle the exception that can otherwise result.

Mmm yes, I agree, it would be nice to be able to check against the version of the pdf, I haven't researched it either. if you find the way to do it would like to know more about it :P