Programming Delphi How to capture a web page's content and save it to an image
Notice: Undefined variable: relatedArticlesCount in /home/wwwroot/codeback.net/plugins/content/tags.php on line 149

Some ranking sites and search engines like alexa and google always cached a site's index page and store as an image in database for the users searching.

We could have this functino very easy in delphi. In this sample we use the TWebBrowser component to load a webpage, then use a function to capture the contents of the page and save it to an image. Ok, let us see the codes.

uses ActiveX;

//Loading a webpage when the program run.
procedure TForm1.FormCreate(Sender: TObject) ;
begin
  WebBrowser1.Navigate('http://codeback.net') ;
end;

procedure TForm1.WebBrowser1NavigateComplete2(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant) ;
begin
  CaptureWebPagesContent(WebBrowser1,'c:\codeback.jpg') ;
end;

procedure CaptureWebPagesContent(const web: TWebBrowser; const fileName: TFileName) ;
var
  vObject : IvObject;
  r : TRect;
  bitmap : TBitmap;
begin
  if web.Document nil then
  begin
    web.Document.QueryInterface(IvObject, vObject) ;
    if Assigned(vObject) then
    try
      bitmap := TBitmap.Create;
      try
        r := Rect(0, 0, web.Width, web.Height) ;

        bitmap.Width := web.Width;
 bitmap.Height := web.Height;

        vObject.Draw(DVASPECT_CONTENT, 1, nil, nil, Application.Handle, bitmap.Canvas.Handle, @r, nil, nil, 0) ;

        //Convert the bitmap(.bmp format) to jpg file format.
        with TJPEGImage.Create do
        try
          Assign(bitmap) ; 
          SaveToFile(fileName) ;
        finally
          Free;
        end;
 //end of convert.

      finally
        bitmap.Free; //release the bitmap.
      end;
    finally
      vObject._Release; //release the viewObject.
    end;
  end;
end;

Note: this program will save the "http://codeback.net" site's frontpage as a jpg format of picture named codeback.jpg and stored it as "c:\codeback.jpg".
 


Add comment


Security code
Refresh

Programming - Delphi