PDFtoolkit VCL
Edit, enhance, secure, merge, split, view, print PDF and AcroForms documents
Compatibility
Delphi C++Builder

Convert PDF Documents to Multi-Page TIFF Images In Delphi

Learn to export PDF pages using PDFtoolkit VCL and create multi-page TIFFs using Windows GDI.
V. Subhash

PDFtoolkit offers several methods to export PDF pages. You could render to a canvas or to a stream. Recently, we had a customer who wanted to convert pages in a PDF document to a multi-page TIFF. So, Gnostice DevTools Team Sanjeev Kulkarni member created a PDF-to-EMF Conversion Unit specifically for this purpose.

In this article, I have provided a modified version of the conversion process. To convert a PDF to EMF, you need to:

  1. Use PDFtoolkit to render each page to a stream.
  2. Use Windows GDI to
    1. convert the stream to a single-page TIFF, and
    2. merge sigle-page TIFFs to a multi-page TIFF.

Now, here is the code example.

program Convert_PDF_to_TIFF;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes,
  gteGDIPAPI, gteGDIPOBJ, gteGDIPUTIL, ActiveX, TypInfo,
  gtPDFDoc, gtCstPDFDoc,  gtUtils;
var
    gtPDFDocument1: TgtPDFDocument;
    EMFStream : TStream;
    EMFStreamAdapter: IStream;
    PageWidth, PageHeight: Double;
    TIFFImage, TempTIFFImage, MultiPageTIFFImage: TGPImage;
    EncoderParameters: TEncoderParameters;
    EncoderParameterValue: TEncoderValue;
    clsidTIFF: TGUID;
    Status: TStatus;
    i, n: Integer;
    PageNum, TIFFPath: String;
    IsExported: Boolean;
begin
  // Initialize flag for giving go-ahead for
  // TIFF processing
  IsExported := false;

  // Initialize TEncoderParameters instance for
  // saving rendered PDF page content stream to TIFF
  EncoderParameters.Count := 1;
  EncoderParameters.Parameter[0].Guid := EncoderSaveFlag;
  EncoderParameters.Parameter[0].Type_ := EncoderParameterValueTypeLong;
  EncoderParameters.Parameter[0].NumberOfValues := 1;
  EncoderParameters.Parameter[0].Value := @EncoderParameterValue;
  GetEncoderClsid('image/tiff', clsidTIFF);

  // Create a document object
  gtPDFDocument1 := TgtPDFDocument.Create(nil);

  try
    Writeln('Loading sample_doc.pdf...');
    // Load a PDF document
    gtPDFDocument1.LoadFromFile('sample_doc.pdf');

    // Check if document was loaded successfully
    if gtPDFDocument1.IsLoaded then begin
      // Check each page in the document
      n := gtPDFDocument1.PageCount;
      for i := 1 to n do begin
        PageNum := IntToStr(i);

        // Obtain page dimensions
        PageWidth := gtPDFDocument1.GetPageSize(1, muPixels).Width;
        PageHeight := gtPDFDocument1.GetPageSize(1, muPixels).Height;

        try
          EMFStream := TMemoryStream.Create;
          Write('Rendering page #' + PageNum);
          // Export current page to a stream
          gtPDFDocument1.RenderToStream(
                  EMFStream,      // Memory stream
                  i,              // Page number
                  PageWidth,      // Page width
                  PageHeight,     // Page height
                  96,             // X-axis DPI
                  96);            // Y-axis DPI

          // Save stream to TIFF image file
          EMFStream.Position := 0;
          EMFStreamAdapter := TStreamAdapter.Create(EMFStream);
          TIFFImage := TGPImage.Create(EMFStreamAdapter);
          Writeln(' and saving it to page' + PageNum + '.tiff.');
          TIFFImage.Save('page' + PageNum + '.tiff', clsidTIFF);
        finally
          TIFFImage.Free;
          EMFStream.Free;
        end;
        // Give okay for TIFF processing
        IsExported := true;
      end;
    end else begin
      Writeln('Sorry, I could not load sample_doc.pdf.');
    end;
  except
    on Err:Exception do begin
        Writeln('Sorry, an exception was raised. ');
        Writeln(Err.Classname + ': ' + Err.Message);
    end;
  end;

  // Close PDF document before converting
  // single-page TIFFs to multi-page TIFF
  gtPDFDocument1.Reset;
  FreeAndNil(gtPDFDocument1);


  // Create multi-page TIFF
  if IsExported then begin
    // Add first frame to a multi-page TIFF
    EncoderParameterValue := EncoderValueMultiFrame;
    MultiPageTIFFImage := TGPImage.Create('page1.tiff');
    Status :=
      MultiPageTIFFImage.Save('multipage.tiff', clsidTIFF, @EncoderParameters);
    Writeln('Adding page1.tiff ... ' +
            GetEnumName(TypeInfo(TStatus), Integer(Status)));

    // Add other frames to the multi-page TIFF
    EncoderParameterValue := EncoderValueFrameDimensionPage;
    for i := 2 to n  do begin
      PageNum := IntToStr(i);
      TIFFPath := 'page' + PageNum + '.tiff';
      TempTIFFImage := TGPImage.Create(TIFFPath);
      Status := MultiPageTIFFImage.SaveAdd(TempTIFFImage, @EncoderParameters);
      FreeAndNil(TempTIFFImage);
      Writeln('Adding page' + PageNum + '.tiff ... ' +
              GetEnumName(TypeInfo(TStatus), Integer(Status)));
    end;

    // Flush multi-page TIFF to file
    EncoderParameterValue := EncoderValueFlush;
    Status := MultiPageTIFFImage.SaveAdd(@EncoderParameters);
    MultiPageTIFFImage.Free;

    // Delete single-page TIFF image files
    Write('Cleaning up single-page TIFF files... ');
    for i := 1 to n do begin
      DeleteFile('page' + IntToStr(i) + '.tiff');
    end;
  end;

  Writeln('finished.');
  Writeln('Check multipage.tiff.');
  Writeln('Press Enter to exit.');
  Readln;
end.

In the above code, some Delphi wrappers for Windows API have been used. To avoid name conflicts, the DCUs have been renamed. Finally, here is the TIFF output.

TIFF image converted from a PDF file
---oO0Oo---

Downloads

Privacy | Legal | Feedback | Newsletter © 2002-2010 Gnostice Information Technologies Private Limited. All rights reserved.

This site is best viewed on a screen with minimum resolution of 1152 x 864 pixels. Windows users are advised to use Microsoft ClearType Tuning for optimal experience. Linux and other users can enable font smoothing, as supported by their OS. Also, please use the latest version of a standards-compliant browser such as Opera, FireFox, Chrome or Safari.