Home > other >  How can set Image and PDF size in UWP C#
How can set Image and PDF size in UWP C#

Time:03-12

I am trying to generate a pdf in my project where I converted Image into Pdf and Image generated from Layout. Generated image size is very large and also There are not received good quality. Please Help me to solve this.

I am using this code in program.

 RenderTargetBitmap renderTargetBitmapimg = new RenderTargetBitmap();

            var mainlayoutHeight = pageStackPanel.ActualHeight;
            var mainlayoutWidth = pageStackPanel.ActualWidth;
            int mlHeight = Convert.ToInt32(mainlayoutHeight);
            int mlWidth = Convert.ToInt32(mainlayoutWidth);


            
            await renderTargetBitmapimg.RenderAsync(pageStackPanel, mlWidth, mlHeight);
            
            ///SAVE IMAGE IN FOLDER 
            var pixelBufferimg = await renderTargetBitmapimg.GetPixelsAsync();
            var pixels = pixelBufferimg.ToArray();
            var displayInformation = DisplayInformation.GetForCurrentView();
            var storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            StorageFolder projectFolder = await storageFolder.CreateFolderAsync("TestImage", CreationCollisionOption.OpenIfExists);
            var file = await projectFolder.CreateFileAsync(jpgFilename, CreationCollisionOption.GenerateUniqueName);

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Premultiplied,
                                    (uint)renderTargetBitmapimg.PixelWidth,
                                    (uint)renderTargetBitmapimg.PixelHeight,
                                    200, 200,
                                    pixels);

                await encoder.FlushAsync();
                StorageFile prescriptionJpgFile = await projectFolder.GetFileAsync(jpgFilename);
                await stream.FlushAsync();
                stream.Seek(0);
                stream.Dispose();
                renderTargetBitmapimg = null;

CodePudding user response:

The answer is no, you can't set the size of the generated image file. But you could try to resize it to reduce its physical size by giving a specific width and height. You could use BitmapEncoder class to encode the original image, change the BitmapInterpolationMode of the image. The code looks like this:

    //open file as stream
        using (IRandomAccessStream fileStream = await imagefile.OpenAsync(FileAccessMode.ReadWrite))
        {
            var decoder = await BitmapDecoder.CreateAsync(fileStream);

            var resizedStream = new InMemoryRandomAccessStream();

            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
            double widthRatio = (double)reqWidth / decoder.PixelWidth;
            double heightRatio = (double)reqHeight / decoder.PixelHeight;

            double scaleRatio = Math.Min(widthRatio, heightRatio);

            if (reqWidth == 0)
                scaleRatio = heightRatio;

            if (reqHeight == 0)
                scaleRatio = widthRatio;

            uint aspectHeight = (uint)Math.Floor(decoder.PixelHeight * scaleRatio);
            uint aspectWidth = (uint)Math.Floor(decoder.PixelWidth * scaleRatio);

            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;

            encoder.BitmapTransform.ScaledHeight = aspectHeight;
            encoder.BitmapTransform.ScaledWidth = aspectWidth;

            await encoder.FlushAsync();
            resizedStream.Seek(0);
            var outBuffer = new byte[resizedStream.Size];
            await resizedStream.ReadAsync(outBuffer.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None);


            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            Debug.WriteLine(storageFolder.Path);
            StorageFile sampleFile = await storageFolder.CreateFileAsync("testfile.pdf", CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteBytesAsync(sampleFile, outBuffer);

        }

For more information, you could check this document:How to Compress image and change its Size.

Another suggestion is that you could just use the UWP print API to generate the PDF file. You could take a look at the Print Helper of Windows Community Toolkit. You could choose not to print but save it as a PDF file.

  • Related