-1

I'm trying to save a PNG as a PDF but I can't seem to cut down on the file size. Even when I split up the file into 3 different PDF documents they are still the same size as the original. Is there any way to decrease the final file size either as one or split up as 3? I can't figure out why the file size is the same even when I've decreased each PDF doc from 935 x 2000 it comes out to be about 226 kb. The picture comes from a screenshot of a website using C#'s selenium. ss is the screenshot I took earlier. Any suggestions would be appreciated.

        string pic = @"";
        ss.SaveAsFile(pic, ScreenshotImageFormat.Png);

        PdfDocument doc = new PdfDocument();
        PdfDocument doc2 = new PdfDocument();
        PdfDocument doc3 = new PdfDocument();
        XImage image = XImage.FromFile(pic);

        PdfPage page1 = doc.AddPage();
        page1.Width = 935;
        page1.Height = 600;

        XGraphics gfx = XGraphics.FromPdfPage(page1);
        gfx.DrawImage(image, 0, 0, 468, 1000);

        PdfPage page2 = doc2.AddPage();
        page2.Width = 935;
        page2.Height = 600;

        gfx = XGraphics.FromPdfPage(page2);
        gfx.DrawImage(image, 0, -600);

        PdfPage page3 = doc3.AddPage();
        page3.Width = 935;
        page3.Height = 600;

        gfx = XGraphics.FromPdfPage(page3);
        gfx.DrawImage(image, 0, -1200);

        Regex pngRGX = new Regex(@".png");
        string strPDFSave = pngRGX.Replace(pic, "1.pdf");

        doc.Save(strPDFSave);
        strPDFSave = pngRGX.Replace(pic, "2.pdf");
        doc2.Save(strPDFSave);

        strPDFSave = pngRGX.Replace(pic, "3.pdf");
        doc3.Save(strPDFSave);
randombeggar
  • 25
  • 1
  • 5

1 Answers1

0

PDFsharp includes the complete image in the PDF, even if just a part of the image is visible on the page (other parts can be made visible by changing the media box).

If you want to go with three PDF files, then clip the images to the required dimensions before adding them to the PDF files.

If you shrink the screen shot from 935 x 2000 to a smaller size the resulting PDF should also become smaller - not sure if that is an option for you.

PDFsharp includes all images without any loss of quality. If loss of quality if acceptable for you, reduce the quality within your code.

  • Do you have any sample code for cropping or quality reduction I'm looking online, and having a little trouble. Would I just do doc1.resolution = int? I'd rather crop the image first but I can't find any code for that. – randombeggar Mar 04 '18 at 14:40
  • Some search results: https://stackoverflow.com/a/24199315/1015447 https://stackoverflow.com/a/6501997/1015447 https://stackoverflow.com/a/2320124/1015447 `DrawImage` of the `Graphics` class can be used for resizing and cropping. – I liked the old Stack Overflow Mar 04 '18 at 20:52