Home > database >  How do I copy HTML content to a TCanvas in Delphi?
How do I copy HTML content to a TCanvas in Delphi?

Time:01-17

I have an application that uses a TWebBrowser to display an HTML report. I use a TCanvas, named PrintCanvas to print a page header, footer, and images. Now I'd like to add the content from the TWebBrowser to the canvas so that the HTML report is printed as well. I've tried copying the TWebBrowser content to a Bitmap, and then adding the Bitmap to my PrintCanvas. This works, but only shows the displayed portion of the TWebBrowser.

Is there a way I can copy an entire HTML report to a TCanvas? This would allow me to use my existing printing code. I'm okay with using a method other than the TWebBrowser, if there is a better way.

Another thing I have tried is using the TWebBrowser's ExecWB method to execute the OLECMDID_PRINT command, which opens the browser's print dialog box. This works, but this doesn't allow me to print the other information already on my PrintCanvas, such as the page header, footer, and images.

CodePudding user response:

There are several ways to do that but all of them require different components.

Solution 1: Since you mention that you're OK using an alternative component then I would use CEF4Delphi.

CEF has an offscreen rendering mode (OSR) that draws the web contents in a raw bitmap buffer.

Several CEF4Delphi demos show how to use that mode like SimpleOSRBrowser, TabbedOSRBrowser or KioskOSRBrowser. You can use any demo as a template for your application.

Those demos copy the raw bitmap data with the web contents from the "buffer" parameter in the TChromiumCore.OnPaint event. As you can see here, the SimpleOSRBrowser copies scanlines from the buffer parameter to a custom bitmap.

Alternatively you can also use a CEF browser without using the offscreen rendering mode. If you build the MiniBrowser demo you can try the "Take screenshot" option in the menu button at the top-right corner. This option uses the "Page.captureScreenshot" DevTools method to take the screenshot and it saves it as a PNG image here.

Solution 2: Use WebView4Delphi. WebView4Delphi also has a MiniBrowser demo with a "Take snapshot..." menu option that calls TWVBrowser.CapturePreview to save the PNG file but you can also use the DevTools method mentioned previously with WebView4Delphi if you call TWVBrowser.CallDevToolsProtocolMethod.

  • Related