ilay zeidman
ilay zeidman

Reputation: 2814

Two images to one pdf file one image per page

I have two images and I want to convert it to one pdf file with one image in a page... what is the easiest way of doing it in C#?

Edit: I tried the following code (added the PdfSharp reference):

 string source1 = @"MySource1.JPG";
 string source2 = @"MySource2.JPG";
 string destinaton = @"MyDest.pdf";

 PdfDocument doc = new PdfDocument();
 doc.Pages.Add(new PdfPage());
 doc.Pages.Add(new PdfPage());

 XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
 XImage img = XImage.FromFile(source1);

 XGraphics xgr2 = XGraphics.FromPdfPage(doc.Pages[1]);
 XImage img2 = XImage.FromFile(source2);

 xgr.DrawImage(img, 0, 0);
 xgr2.DrawImage(img2, 0, 0);
 doc.Save(destinaton);
 doc.Close();

Now it is create a pdf with my two pages but the problem now is that the images are cut and not in their original size! the size of the pictures is 3264x2448. How can I fix the image size to the pdf document size?

Upvotes: 0

Views: 1423

Answers (2)

There are several overloads of DrawImage. Use an overload that allows you to specify the destination size of the image.

Three lines of code allow to calculate the image size to use the complete page (with a margin if wanted) while keeping the aspect ratio.

Upvotes: 1

Yegor Korotetskiy
Yegor Korotetskiy

Reputation: 401

If you know the pdf document size, you can resize your image as:

Bitmap objBitmap = new Bitmap(objImage, new Size(size1, size2));

where objImage is your original image.

or like:

public static Image resizeImage(Image imgToResize, Size size)
    {
       return (Image)(new Bitmap(imgToResize, size));
    }

    objBitmap = resizeImage(objBitmap, new Size(size1,size2));

Upvotes: 1

Related Questions