Document Solutions for PDF
In This Topic
    Save PDF as Image
    In This Topic

    PDF pages often contain important information, which can be used for Powerpoint presentations, webpages or word processing documents. In such cases, you might want to make small changes in the PDF pages. With DsPdf library, you can save PDF documents as high quality image files, without turning to online PDF-to-Image converter tools.

    You can save a PDF document as an image by using the below methods:

    Using SaveAs methods

    DsPdf library provides methods to save the entire PDF document or a specific range as an image. The user can provide the file names and call the SaveAsBmp, SaveAsPng, SaveAsGif, SaveAsJpeg, and SaveAsTiff methods of the GcPdfDocument class.

    To save a PDF as an image, follow the steps given below:

    1. Create an instance of GcPdfDocument class.
    2. Load the PDF document using the Load method of GcPdfDocument class.
    3. Call the OutputRange method to define the pages of the document that need to be saved.
    4. Call the SaveAsImageOptions method to save the image in different formats (JPEG, BMP, PNG and GIF).
      C#
      Copy Code
      GcPdfDocument doc = new GcPdfDocument();
      var fs = new FileStream(Path.Combine("Wetlands.pdf"), FileMode.Open, FileAccess.Read);
      doc.Load(fs);  //Load the document
      
      //Create an output range object which defines which pages of the document should be saved
      //If no output range is defined then all the pages of the document will be saved
      OutputRange pageRange = new OutputRange(1, 2);
      
      //Specify the options that should be used while saving the document's pages to image 
      SaveAsImageOptions op = new SaveAsImageOptions();
      SaveAsImageOptions saveOptions = new SaveAsImageOptions()
      {
          BackColor = Color.LightCyan,
          DrawAnnotations = false,
          DrawFormFields = false,
          Resolution = 100
      };
      doc.SaveAsJpeg("WetlandsImage{0}.jpeg", pageRange, saveOptions); //Saves the document pages as images in JPEG format
      doc.SaveAsBmp("WetlandsImage{0}.bmp", pageRange, saveOptions); //Saves the document pages as images in BMP format
      doc.SaveAsGif("WetlandsImage{0}.gif", pageRange, saveOptions); //Saves the document pages as images in GIF format
      doc.SaveAsPng("WetlandsImage{0}.png", pageRange, saveOptions); //Saves the document pages as images in PNG format
      

    Back to Top

    DsPdf enables a user to save PDF pages as images by simply calling methods of the Page class like SaveAsBmp, SaveAsPng, SaveAsGif, SaveAsTiff and SaveAsJpeg methods.

    To save a PDF page directly as an image, follow the steps given below:

    1. Create an instance of the GcPdfDocument class.
    2. Load the PDF document.
    3. Set BackColor and Resolution properties of the PDF page in SaveAsImageOptions class.
    4. Save the required page of the PDF document by invoking the appropriate method of Page class.
      C#
      Copy Code
      GcPdfDocument doc = new GcPdfDocument();
      var fs = new FileStream(Path.Combine("Wetlands.pdf"), FileMode.Open, FileAccess.Read);
      doc.Load(fs);  //Load the document
      
      //Specify the options that should be used while saving the page to image 
      SaveAsImageOptions saveOptions = new SaveAsImageOptions()
      {
          BackColor = Color.LightCyan,
          DrawAnnotations = false,
          DrawFormFields = false,
          Resolution = 100
      };
      
      //Saves the document's first page as an image to a file in JPEG format
      doc.Pages[0].SaveAsJpeg("WetlandsImage.jpeg",saveOptions);
      
      //Saves the document's first page as an image to a stream in JPEG format
      MemoryStream stream = new MemoryStream();
      doc.Pages[0].SaveAsJpeg(stream,saveOptions);
      

    Back to Top

    DsPdf library also provides InterpolationMode property in the SaveAsImageOptions class, which is utilized to set interpolation mode while drawing bitmap images in PDF files or saving the PDF files as images; by default, it is NearestNeighbor.

    Refer to the following example code to set InterpolationMode while saving the PDF file as images:

    C#
    Copy Code
    class Program
    {
        GrapeCity.Documents.Pdf.GcPdfDocument Document;
        GrapeCity.Documents.Pdf.GcPdfGraphics Graphics;
        GrapeCity.Documents.Pdf.Page Page;
        public const float Resolution = 25.4f;
        public const float MM = 1;
        public const float CM = MM * 10;
        System.Drawing.SizeF PageSize;
        System.Drawing.RectangleF TextRect;
        static void Main(string[] args)
        {
            // Initialize GcPdfDocument.
            var pdf = new GrapeCity.Documents.Pdf.GcPdfDocument();
    
            // Draw page in PDF document.
            new Program(pdf).DrawPage();
    
            // Instantiate SaveAsImageOptions.
            SaveAsImageOptions options = new SaveAsImageOptions();
    
            // Set InterpolationMode to NearestNeighbor.
            options.InterpolationMode = GrapeCity.Documents.Drawing.InterpolationMode.NearestNeighbor;
    
            // Save PDF document.
            pdf.Save("test.pdf");
    
            // Save PDF document as BMP image with SaveAsImageOptions.
            pdf.SaveAsBmp("test.bmp", null, options);
    
            // Save PDF document as PNG image with SaveAsImageOptions.
            pdf.SaveAsPng("test.png", null, options);
    
            // Save PDF document as JPEG image with SaveAsImageOptions.
            pdf.SaveAsJpeg("test.jpg", null, options);
    
        }
        Program(GrapeCity.Documents.Pdf.GcPdfDocument doc)
        {
            Document = doc;
        }
        
        // Configure page settings for PDF document.
        void AddPage()
        {
            Page = Document.NewPage();
            Page.PaperKind = GrapeCity.Documents.Common.PaperKind.A4;
            Page.Landscape = false;
            PageSize = Page.GetRenderSize(Resolution, Resolution);
            Graphics = Page.Graphics;
            Graphics.Resolution = Resolution;
            TextRect = new System.Drawing.RectangleF(0, 0, PageSize.Width, PageSize.Height);
            TextRect.Inflate(-2.5f * CM, -2.7f * CM);
            Graphics.DrawRectangle(TextRect, new GrapeCity.Documents.Drawing.Pen(System.Drawing.Color.Green, 2f * MM));
        }
        
        // Draw image on Bitmap.
        void DrawBitmap(System.Drawing.RectangleF rect)
        {
            var pngImage = GrapeCity.Documents.Drawing.Image.FromFile(@"..\..\..\qrcode.png");
            Graphics.DrawImage(pngImage, rect, rect, GrapeCity.Documents.Drawing.ImageAlign.StretchImage);
        }
    
        // Draw page in PDF document.
        void DrawPage()
        {
            AddPage();
            DrawBitmap(new System.Drawing.RectangleF(5 * CM, 5 * CM, 10 * CM, 10 * CM));
        }
    }
    
    Note: The interpolation mode only affects the way bitmap images are drawn on a graphic, i.e., the result of DrawImage method and bitmap image resizing. Interpolation mode does not affect any other graphics operations. In particular, if a PDF is saved to an image format, the only items affected by interpolation mode would be bitmap images embedded in the original PDF, if they exist.

    Back to Top

    Save as SVG

    In addition to above mentioned common image formats, DsPdf also lets you save the PDF pages as SVG or its compressed format SVGZ. You can use SaveAsSvg and ToSvgz methods of the GrapeCity.Documents.Pdf.Page class to export an instance of pdf page to SVG file or stream(.svg) or a byte array(.svgz).

    C#
    Copy Code
    var pdfDoc = new GcPdfDocument(); 
        using (var fs = new FileStream("Test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read)) 
        { 
            pdfDoc.Load(fs); 
            var page = pdfDoc.Pages[0];
    
            // Render a PDF page to the .svg file 
            page.SaveAsSvg("DsPDFRenderToSVG.svg", null, 
                new SaveAsImageOptions() { Zoom = 2f }, 
                new XmlWriterSettings() { Indent = true });  
    
            // Render a PDF page to the byte array with compressed data in SVGZ format 
            var svgzData = page.ToSvgz(new SaveAsImageOptions() { Zoom = 1f }); 
            File.WriteAllBytes("DsPDFRenderToSVGZ.svgz", svgzData); 
        }    
    

    Limitation

    Text is always rendered as graphics using paths. Hence, resulting .svg files for text pages are large and it is not possible to select or copy text on the SVG images opened in the browsers.

    Render PDF pages on GcGraphics

    DsPdf allows a user to render specific PDF pages, annotations or a mix of PDF pages to images. The user can draw PDF pages on the image graphics using Draw method of the Page class. If the PDF pages contain annotations, you can draw the PDF page annotations on the graphics object with DrawAnnotations method of the Page class. After drawing on the graphics object, the bitmap image can be saved in any image format by calling the SaveAsPng, SaveAsJpeg or SaveAsTiff methods of the GcBitmap class.

    Note: To implement this method, you will need the license for DsImaging library.

    To save a PDF as an image, follow the steps given below:

    1. Create an instance of GcPdfDocument class.
    2. Load any existing PDF file using the Load method.
    3. Create an instance of GcBitmap class to render the PDF into an image.
    4. Call the Draw method of Page class to render the PDF file pages content with or without annotations and the DrawAnnotations method of Page class to render only the page annotations on the image graphics.
    5. Save the rendered PDF page into the required image format by calling SaveAsPng, SaveAsJpeg or SaveAsTiff methods of the GcBitmap class.

    The code snippet below illustrates how to save a PDF document as an image.

    C#
    Copy Code
    GcPdfDocument doc = new GcPdfDocument();
    doc.Load(new FileStream("SampleDoc.pdf", FileMode.Open, FileAccess.Read));
    
    var page = doc.Pages[0];
    var sz = page.Bounds;
    GcBitmap bmp1 = new GcBitmap((int)(sz.Width + 0.5f), (int)(sz.Height + 0.5f), true);
    using (GcGraphics g = bmp1.CreateGraphics(Color.White))
    {
        //render whole page content (including the annotations)
        page.Draw(g, new RectangleF(0, 0, sz.Width, sz.Height));
    }
    
    GcBitmap bmp2 = new GcBitmap((int)(sz.Width + 0.5f), (int)(sz.Height + 0.5f), true);
    using (GcGraphics g = bmp2.CreateGraphics(Color.White))
    {
        //render page content without annotations
        page.Draw(g, new RectangleF(0, 0, sz.Width, sz.Height), false);
    }
    
    GcBitmap bmp3 = new GcBitmap((int)(sz.Width + 0.5f), (int)(sz.Height + 0.5f), true);
    using (GcGraphics g = bmp3.CreateGraphics(Color.White))
    {
        //render only the page's annotations
        page.DrawAnnotations(g, new RectangleF(0, 0, sz.Width, sz.Height));
    }
    
    /*Once the PDF page has been rendered on GcGraphics, 
     *then the rendered PDF page can be saved as an image in various image formats
     *such as, JPEG, PNG, BMP, TIFF, and GIF.
    */
    bmp1.SaveAsPng("WholePageContents.png");
    bmp2.SaveAsJpeg("PageContentsWithoutAnnotations.jpeg");
    bmp3.SaveAsTiff("PageAnnotations.tiff");
                
    

    Back to Top

    Apart from the above, you can also render text in PDF and save it as an image by enabling TrueType hinting instructions as explained below:

    Support for TrueType Hinting Instructions

    DsPdf supports enabling TrueType hinting instructions while rendering text on GcPdfGraphics and saving it as an image.

    Hinting instructions are included in some TrueType fonts which improve their look by reusing some glyph parts in different glyphs regardless of their font size. TrueType hinting instructions, in DsPdf, supports drawing CJK characters as combinations of other smaller glyph pieces which enhances their final look.

    For fonts which include TrueType glyph hinting instructions, the EnableHinting property of the Font class is set to true, for the others it is set to False. Further, to apply the hinting instructions of the font, EnableFontHinting property of the SaveAsImageOptions class must be set to true (the default value).

    However, if the EnableHinting property is explicitly set to false, then the hinting instructions cannot be enabled.

    As the default value of both the properties is true, hence the hinting instructions are supported for any TrueType font which includes them.

    Disabled Hinting Intructions
    Disabled Hinting Intructions
    Disabled Hinting Intructions for Chinese string


    Enabled Hinting Intructions
    Enabled Hinting Intructions
    Enabled Hinting Intructions for Chinese string

    To enable TrueType hinting instructions for Chinese string:

    1. Load a Chinese Font file.
    2. Initialize the GcPdfGraphics class which represents a graphics object on a PDF page.
    3. Define a Chinese string and configure TextFormat properties.
    4. Draw the Chinese string.
    5. Create an instance of SaveAsImageOptions class and use it to set the EnableFontHinting property to true .
    6. Save the image.
    C#
    Copy Code
     var font = Font.FromFile("kaiu.ttf");
    GcPdfDocument doc = new GcPdfDocument();
    {
    
        GcPdfGraphics g = doc.NewPage().Graphics;
        {
            //Draw the string with hinting instructions set to true
            string s1 = @"入秋空污警報!這幾招遠離PM2.5學起來";
            //Define text formatting attributes
            var tf1 = new TextFormat()
            {
                Font = font,
                FontSize = 20,
    
            };
            g.DrawString(s1, tf1, new PointF(10, 110));
    
            SaveAsImageOptions imgOptions = new SaveAsImageOptions();
            imgOptions.EnableFontHinting = true;
    
            doc.SaveAsPng("ChineseFontwithHintingInstructions1.png", null, imgOptions);
        }
    }
    

    Back to Top