We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: November 16, 2018).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert JPEG image from PNG image and draw those JPEG image into PDF document

Platform: Xamarin.Forms |
Control: PDF |
Published Date: August 3, 2017 |
Last Revised Date: April 25, 2019
Tags: pdf, graphics, png, drawing

At present, we do not have native support for drawing PNG image on PDF in Xamarin forms platform. So, we can convert the PNG image to JPEG and drawing the JPEG image into PDF document in Xamarin platform.  We have achieved the PNG image to JPEG conversion by using the Dependency service. We have implemented the PNG to JPEG conversion in Xamarin.Android, Xamarin.IOS and Xamarin.UWP. Please find the sample and code snippet below,

Convert PNG to JPEG using Xamarin.Android:

Convert the PNG image to JPEG in Xamarin.Android by using below code snippet.

C#

public Stream ConvertPngToJpeg(Stream stream)
{
        //Convert image stream into byte array
        byte[] image = new byte[stream.Length];
        stream.Read(image, 0, image.Length);
 
        //Load the bitmap
        Bitmap resultBitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);
 
        //Create memory stream
        MemoryStream outStream = new MemoryStream();
 
        //Save the image as Jpeg
        resultBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream);
 
        //Return the Jpeg image as stream
        return outStream;
 }

 

Convert PNG to JPEG using Xamarin.IOS:

Convert the PNG image to JPEG in Xamarin.IOS by using below code snippet.

C#

Stream ISave.ConvertPngToJpeg(Stream stream)
{
       //Convert image stream into byte array
       byte[] image = new byte[stream.Length];
       stream.Read(image, 0, image.Length);
 
       //Load the image
       UIKit.UIImage images = new UIImage(Foundation.NSData.FromArray(image));
 
        //Save the image as Jpeg
        byte[] bytes = images.AsJPEG(100).ToArray();
 
        //Store the byte array into memory stream
        Stream imgStream = new MemoryStream(bytes);
 
        //Return the Jpeg image as stream
        return imgStream;
}

 

Convert PNG to JPEG using Xamarin.UWP:

Convert the PNG image to JPEG in Xamarin.UWP by using below code snippet.

C#

public async Task<Stream> ConvertPngToJpeg2(Stream s)
{
         byte[] resultArray = null;
            
         //Convert stream into byte array
         byte[] image = new byte[s.Length];
         s.Read(image, 0, image.Length);
           
         //Create An Instance of WriteableBitmap object  
         WriteableBitmap resultBitmap = new WriteableBitmap(1, 1);
 
         using (IRandomAccessStream ms = new InMemoryRandomAccessStream())
          {
              await ms.WriteAsync(image.AsBuffer());
              ms.Seek(0);
                
               //Set the source for WriteableBitmap  
               resultBitmap.SetSource(ms);
          }
 
        //Get the image data
        using (IRandomAccessStream ms = new InMemoryRandomAccessStream())
         {
             try
              {
                  byte[] bytes;
 
                  // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
                  using (Stream stream = resultBitmap.PixelBuffer.AsStream())
                  {
                      bytes = new byte[(uint)stream.Length];
                      await stream.ReadAsync(bytes, 0, bytes.Length);
                  }
 
                 // Create an encoder with the Jpeg format
                 BitmapEncoder encoder = await   BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);
                   
                 // WriteableBitmap uses BGRA format 
                 encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)resultBitmap.PixelWidth, (uint)resultBitmap.PixelHeight, 96, 96, bytes);
 
                 //Terminate the encoder bytes
                 await encoder.FlushAsync();
                    
                 resultArray = new byte[ms.AsStream().Length];
                 await ms.AsStream().ReadAsync(resultArray, 0, resultArray.Length);
             }
             catch (Exception e)
             {
                  System.Diagnostics.Debug.WriteLine(e.Message);
             }
         }
 
         //Store the image into memory stream
         Stream imgStream = new MemoryStream(resultArray);
 
        //Return the Jpeg image as stream
        return imgStream;
 }

 

Draw the JPEG image into PDF document:

Draw the JPEG image into PDF document can be shown in the below code snippet.

C#

//Load the file as stream
Stream docStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("ImageDrawing.Assets.Sample.pdf");
 
//Load a PDF document.
PdfLoadedDocument doc = new PdfLoadedDocument(docStream);
 
//Get first page from document
PdfLoadedPage page = doc.Pages[0] as PdfLoadedPage;
 
//Create PDF graphics for the page
PdfGraphics graphics = page.Graphics;
 
//Load the image
Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("ImageDrawing.Assets.logo.png");
 
Stream stream = DependencyService.Get<ISave>().ConvertPngToJpeg(imageStream);
 
//Load the image from the stream
PdfBitmap image = new PdfBitmap(stream);
 
//Draw the image
graphics.DrawImage(image, 0, 0);
 
MemoryStream memoryStream = new MemoryStream();
 
//Save the document into memory stream
doc.Save(memoryStream);
 
//close the documents
doc.Close(true);
 
//Save the stream into pdf file
DependencyService.Get<ISave>().SaveAsync("sample.pdf", "application/pdf", memoryStream);

 

Sample link:

http://www.syncfusion.com/downloads/support/directtrac/general/ze/ImageDrawing-1680216731

2X faster development

The ultimate Xamarin UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
Shrikant Thorve
Mar 19, 2019

in Draw the JPEG image into PDF document; imageStream is getting null.

Where we need to store the jpeg file in Xamarin project solutin

Reply
KarthikeyanC [Syncfusion]
Mar 19, 2019

Hi Shrikant, Greetings from Syncfusion. We have checked with the provided sample. The image stream object setting as null because while loading the image as a stream, image file in Assets should be set as Embedded Resources.

Right click on the image file in assets > Properties > Set Embedded resource for Build Action

Please find the below screenshot for more details,

We have modified the sample to resolve the mentioned issue. Please find the sample for the same from below link,

Sample link: http://www.syncfusion.com/downloads/support/directtrac/231037/ze/CreatePDFSample754699366

Kindly try the above sample in your end and let us know if it solves the issue.

Regards, Karthikeyan

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon