Print html as image

Declare these in any file:

[Guid(«3050f669-98b5-11cf-bb82-00aa00bdce0b»),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(true), ComImport]
interface IHTMLElementRender
void DrawToDC([In] IntPtr hDC);
void SetDocumentPrinter([In, MarshalAs(UnmanagedType.BStr)] string bstrPrinterName, [In] IntPtr hDC);
>; [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(«00000127-0000-0000-C000-000000000046»)]
public interface IViewObject
Int32 Draw(Int32 dwDrawAspect, Int32 lindex, IntPtr pvAspect, IntPtr ptd, Int32 hicTargetDev, IntPtr hdcDraw,
IntPtr prcBounds, RectangleF prcWBounds, IntPtr fnContinue, Int32 dwContinue);
>

Put this code in your DocumentCompleted callback of the webbrowser control:
IViewObject ViewObject = (IViewObject)webBrowser1.Document.DomDocument;

Graphics PB1 = pictureBox1.CreateGraphics();
IntPtr AddrOfPB1 = PB1.GetHdc();

//create a compatible DC
IntPtr AddrCreateCompatibleDC = GDI32.CreateCompatibleDC(IntPtr.Zero);

//create a memory bitmap in the DC just created, the size of the window we’re capturing
IntPtr AddrCreateCompatibleBitmap = GDI32.CreateCompatibleBitmap(AddrOfPB1, webBrowser1.ClientRectangle.Width, webBrowser1.ClientRectangle.Height);

//Prepare DC as a Bitmap using selectObject to configure the DC
GDI32.SelectObject(AddrCreateCompatibleDC, AddrCreateCompatibleBitmap);

//Draw the Rendered DomDocument to the Device Context
ViewObject.Draw(1, 1, IntPtr.Zero, IntPtr.Zero, 0, AddrCreateCompatibleDC, IntPtr.Zero, new RectangleF(), IntPtr.Zero, 0);

Image fullSizeImg1 = null;
fullSizeImg1 = Image.FromHbitmap(AddrCreateCompatibleBitmap);
pictureBox1.Image = fullSizeImg1.GetThumbnailImage(webBrowser1.ClientRectangle.Width, webBrowser1.ClientRectangle.Height, null, IntPtr.Zero);

string output = Path.GetDirectoryName(Name) + @»\out\» + Path.GetFileNameWithoutExtension(Name) + «.png»;
pictureBox1.Image.Save(output);

On my experience, IHTMLElementRender::DrawToDC() limits its output to DC HORZSIZE and VERTSIZE.
And CBitmapDC DC always has HORZSIZE and VERTSIZE from my display, not depending on window size.

As I need DrawToDC for printing (but not exactly to printer, I print later), VERTSIZE typically is too small for me.

I did not find any way to change VERTSIZE in DC obtained from screen.
If anybody can tell me a way, I shall be grateful.

IHTMLDocument2 * pDoc = (IHTMLDocumetn2 * ) NULL ; if(CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2, (void** )&pDoc) == S_OK) < if(pDoc != (IHTMLDocument2 *)NULL) < HRESULT hresult = S_OK; VARIANT *param; SAFEARRAY *sfArray; BSTR bstr = SysAllocString(OLESTR("HTML DISPLAY.")); sfArray = SafeArrayCreateVector(VT_VARIANT, 0, 1); if (sfArray == NULL || document == NULL) < //some problem; > hresult = SafeArrayAccessData(sfArray,(LPVOID*) & param); param->vt = VT_BSTR; param->bstrVal = bstr; hresult = SafeArrayUnaccessData(sfArray); hresult = pDoc->write(sfArray); hresult = pDoc->close(); CCreateHTMLImage::CreateImage(pDoc, "D:\\dd.jpg", CSize(800, 600), CSize(800, 600)) ; > >

1. Capturing snapshots is a resource hog.
2. Security was a big issue; websites containing harmful script cannot be captured because they have to be loaded on your server making it vulnerable
3. Huge bandwidth consumption
4. There are so many different websites and issues you will run into such as pop up messages, flash, and JavaScript to name a few. It is difficult to capture a wide range of websites correctly.

This artical has help me a lot !! Thanks to Rob Manderson

But still I have one problem ,I have tryed a lot to get whole html/mht files images page by page using follwing code..

IHTMLElement2 *pElement2;
.
height = 1056;
for(. )
.
pElement2->put_scrollTop(height)
height +=height;
. apply drawing functionality and saving image file.
>
.

I am getting image page of next page but that is not perfect sometime it clips or sometimes it includes previous page`s last image portion into next page image.

So i am confusued ,May I doing some thing wrong ??

But in order to use this example you’ve pointed to, you have to buy the product.

Lame plug for your company.

Источник

How to turn HTML webpage into an Image?

While working in one of my project I had to implement a feature where I have turn an HTML webpage to an Image. The first thought that occurred to me was to use an inbuilt library but like dom-to-image or using Chrome Headless or a wrapper library like Puppeteer. While working I came across this technique using pure Javascript. Let’s try to achieve this without using any library.

Converting HTML webpage into an Image by using Canvas.

We cannot directly draw the HTML into Canvas due to the security reasons. We will follow another approach which will be safer.

Steps

 xmlns="http://www.w3.org/2000/svg" width="200" height="200">  
 xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +  width="100%" height="100%">   
 xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +  width="100%" height="100%">  xmlns="http://www.w3.org/1999/xhtml">. emcolor:red;>  Hey there.   
const tempImg = document.createElement('img') tempImg.src = 'data:image/svg+xml,' + encodeURIComponent('
Hey there.
')
const newImg = document.createElement('img') newImg.src = 'data:image/svg+xml,' + encodeURIComponent('
Hey there.
') // add event listener to image. newImg.addEventListener('load', onNewImageLoad) // method to draw image to canvas and set data to target img.src function onNewImageLoad(e) ctx.drawImage(e.target, 0, 0) targetImg.src = canvas.toDataURL() >

You can find the complete code in the CodeSandox!

Reasons why using SVG and Canvas is safe?

Implementation of SVG image is very restrictive as we don’t allow SVG image to load an external resource even one that appears on the same domain. Scripting in an SVG image is not allowed, there is no way to access the DOM of an SVG image from other scripts, and DOM elements in SVG images cannot receive input events. Thus there is no way to load privileged information into a form control (such as a full path in a ) and render it.

The restriction that script can’t directly touch DOM nodes that get rendered to the canvas is important from the security point of view.

I tried to cover this topic and steps in brief. Please feel free to add on related to this topic. 😅

Источник

Export the HTML Canvas as print optimized file

Drawing things that result in an art sketches on the HTML Canvas is fun but how do you export them? For a quick export it’s fine to right click on the canvas and save it. The file will have a set resolution wich is the same as your canvas resolution. If you want to print your canvas content in a professional way you will need a much higher resolution and usually a fixed width/height. In this article I will show you how to configure your canvas to export a high dpi image optimized for printing.

How?

const cvs = document.getElementById("drawing"); const ctx = cvs.getContext("2d"); const dpr = window.devicePixelRatio; 

Printers use the measurement DPI wich stands for dots per inch. The canvas is based on pixels so there must be a conversion between these two. Let’s say I want my canvas content printed on a 2 inch by 2 inch piece with a resolution of 300 dpi. In this case my real canvas width/height must be 300*2 pixel:

const dpi = 300; let width = 2; let height = 2; cvs.width = width * dpi * dpr; cvs.height = height * dpi * dpr; ctx.scale(dpr, dpr); 

As you see there is a third constant multiplied with our canvas size, the device pixel ratio. It is the device specific ratio of physical pixel per pixel calculated by your website. Read more here We also need to scale the context to this ratio to make it look crisp.
The last step for the canvas setup is to scale it with css so it fits the screen. By doing this it will keep the set resolution but will appear smaller on the screen.

canvas  width: 600px; height: 600px; > 

And that’s it. If you now right click on the canvas and save it you can see the generated image has the defined size optimized for print.
Instead of a right click to download the image the canvas has a ‘toDataURL’ Function wich we can use to download the image with code. The generated DataURL can be added to an anchor tag to start the download:

function download()  const downloadUrl = cvs.toDataURL(); const a = document.createElement("a"); a.href = downloadUrl; a.setAttribute("download", "SketchDownload"); a.click(); > 

Simply link the function to a button and we can export a HTML canvas with a specific size on the click of a button.

Creative Coding Workbench

This article is part of my progress for the Digital Ocean Hackathon Project ‘Creative Coding Workbench’.

Features:

  • draw sketch on HTML canvas
  • export sketch for print
  • expose sketch settings to UI
  • toggle sketch animation
  • save sketch to a library
  • load sketch from a library
  • edit sketch from a library
  • .

Technologies:

Stay tuned for updates on this project as there will be posts for each part of it.

Источник

Читайте также:  Python change letter in string
Оцените статью