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?