PDFsharp & MigraDoc Foundation
http://forum.pdfsharp.de/

PdfSharpCore generates huge PDF files despite resizing first
http://forum.pdfsharp.de/viewtopic.php?f=2&t=4596
Page 1 of 1

Author:  Marvino [ Thu May 23, 2024 10:07 pm ]
Post subject:  PdfSharpCore generates huge PDF files despite resizing first

I am trying to convert images to PDF (scaling to full page), while keeping the file size moderate. I understand that PdfSharpCore embeds the full image, so it has to be resized first. Consider the following code (can be run directly from LinqPad):

Code:
const string ImagePath = @"C:\pexels-eberhardgross-443446.jpg";
const string PdfPath = @"C:\foo.pdf";

using (var imageStream = File.OpenRead(ImagePath))
{
    var image = new MagickImage(imageStream);
    image.Resize(new Percentage(20));
    image.Quality = 50;

    using (var resizedImageStream = new MemoryStream())
    {
        image.Write(resizedImageStream);
        resizedImageStream.Position = 0;

        using (var document = new PdfDocument())
        {
            PdfPage page = document.AddPage();
            page.Size = PdfSharpCore.PageSize.A4;
            using (XImage img = XImage.FromStream(() => resizedImageStream))
            {
                XGraphics gfx = XGraphics.FromPdfPage(page);
                var pageWidth = gfx.PageSize.Width * 0.95;
                var pageHeight = gfx.PageSize.Height * 0.95;

                // compute image width / height maintaining image aspect ratio
                var width = pageWidth;
                var height = (((double)width / (double)img.PixelWidth) * img.PixelHeight);
                if (height > pageHeight)
                {
                    height = pageHeight;
                    width = (((double)height / (double)img.PixelHeight) * img.PixelWidth);
                }

                gfx.DrawImage(img, (gfx.PageSize.Width - width) / 2, (gfx.PageSize.Height - height) / 2, width, height);
            }
            using (var pdfStream = File.OpenWrite(PdfPath))
            {
                document.Save(pdfStream);
            }
        }
    }
}


You can find the sample image I am using here.

Even when I resize to 1%, the file size of the resulting PDF file stays the same (about 3MB), although it only contains an image that has such low resolution that you can't see anything but pixels anymore.

What am I doing wrong?

Author:  TH-Soft [ Fri May 24, 2024 8:21 am ]
Post subject:  Re: PdfSharpCore generates huge PDF files despite resizing f

Marvino wrote:
What am I doing wrong?
You are using the wrong forum.
PDFsharp handles images differently from PdfSharpCore.

See also:
https://docs.pdfsharp.net/General/Issue-Reporting.html

Author:  TH-Soft [ Fri May 24, 2024 11:46 am ]
Post subject:  Re: PdfSharpCore generates huge PDF files despite resizing f

According to a deleted post on SO, this is no longer reproducible.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/