The open blogging platform. Say no to algorithms and paywalls.

Screen Capture a Page Using Angular Ngx Capture

Screen capture library for Angular. Define a zone and it will capture it and return a string containing a base64 PNG.

image

In this tutorial, we will learn how to take a screenshot of a web page using Angular. We can write our own JavaScript code to capture the screen. However, it is a time-consuming process. We have a predefined library to do this task in Angular. That is the ngx capture library. One of my clients needs to take a web application page as an image(screenshot) and send it to multiple people. I tried using plain JavaScript. It was not successful. I met many errors while doing this task. And I found the ngx capture. This saved my time. I thought to share this with you guys. It may be very helpful for someone who needs this.

So the process is very simple and straight forward.

  1. Define an HTML tag as a root element.

  2. Capture all the elements as an image inside the root element using the ngx capture library.

That's all. No other extra work. It output a base64 png image. You can save this on your server if you want.

Let's see how to do this in a step by step example.

Create Angular Project

Create an Angular project using the below command on your terminal.

ng new demo-project

Install NGX-CAPTURE Library

Now install the NGX-CAPTURE library inside the project using the below command.

npm i ngx-capture

Import to App Module

Whenever we install a library, that must be imported to the app.module.ts file. So first import the NgxCaptureModule to the app.module.ts file.

import { NgxCaptureModule } from "ngx-capture";

Then include the NgxCaptureModule to the import section of the app.module.ts file.


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ]
imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule,
    NgxCaptureModule
    ]
})

Capture Image

Now create a div tag and add the id to the tag in the home.component.html file.

<div #screen>
  <h1>Hey!</h1>
  <p>some content</p>
</div>

<button (click)="capture()">Take</button>
  1. The screen is the id in the above code.

  2. Click event used to capture the page as an image.

Now we can capture the page as an image using the NgxCaptureService. So import the NgxCaptureService to the home.component.ts file.

import { NgxCaptureService } from "ngx-capture";

Then inject the NgxCaptureService to the constructor of the home.component.ts file.

Create a reference variable to the NgxCaptureService using the constructor.

constructor(private captureService:NgxCaptureService) {

}

Create a view child reference variable to the root element.

  @ViewChild('screen', { static: true }) screen: any;

Then call the getImage() function to capture the element as an image.

capture();
{
  this.captureService.getImage(this.screen.nativeElement, true).then((img) => {
    console.log(img);
  });
}

That's all. It outputs the base64 png image. Now my goal is to save the image on the server.

Convert Base64 to Image

Convert the base64 output to the image using the below code.

DataURIToBlob(dataURI: string) {
    const splitDataURI = dataURI.split(',')
    const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
    const mimeString = splitDataURI[0].split(':')[1].split(';')[0]

    const ia = new Uint8Array(byteString.length)
    for (let i = 0; i < byteString.length; i++)
        ia[i] = byteString.charCodeAt(i)

        return new Blob([ia], { type: mimeString })
}

Upload to Server Using HTTP

Here I am converting the base64 string to an image and passing the image to the server using the HTTP.

ip="http://localhost/fileupload/"
save(){
  const file = this.DataURIToBlob(this.imgBase64)
  const formData = new FormData();
  formData.append('file', file, 'image.png')
  let url="upload2.php"
  this.http.post(this.ip+url,formData).subscribe(data=>{


  })
}

PHP Code To Capture Image

This code captures the image and saves it on the server.

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');

if(isset($_FILES['file'])){

	$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

	if(!in_array(strtolower($extension), $allowed)){
		echo '{"status":"error"}';
		exit;
	}

	if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name'])){
		echo '{"status":"success"}';
		exit;
	}
}else{
	echo "Not Found";
}

//echo '{"status":"error"}';
//exit;

?>

Full home.component.ts file code

import { HttpClient } from "@angular/common/http";
import { Component, OnInit, ViewChild } from "@angular/core";
import { NgxCaptureService } from "ngx-capture";

@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"],
})
export class HomeComponent implements OnInit {
  constructor(
    private captureService: NgxCaptureService,
    private http: HttpClient
  ) {}

  ngOnInit() {}
  imgBase64: any = "";
  @ViewChild("screen", { static: true }) screen: any;

  capture() {
    this.captureService
      .getImage(this.screen.nativeElement, true)
      .then((img) => {
        console.log(img);
        this.imgBase64 = img;
        this.save();
      });
  }

  DataURIToBlob(dataURI: string) {
    const splitDataURI = dataURI.split(",");
    const byteString =
      splitDataURI[0].indexOf("base64") >= 0
        ? atob(splitDataURI[1])
        : decodeURI(splitDataURI[1]);
    const mimeString = splitDataURI[0].split(":")[1].split(";")[0];

    const ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++)
      ia[i] = byteString.charCodeAt(i);

    return new Blob([ia], { type: mimeString });
  }

  ip = "http://localhost/fileupload/";
  save() {
    const file = this.DataURIToBlob(this.imgBase64);
    const formData = new FormData();
    formData.append("file", file, "image.png");
    let url = "upload2.php";
    this.http.post(this.ip + url, formData).subscribe((data) => {});
  }
}

That's all guys. I hope you like this tutorial. Stay tuned for more articles.

If you have any doubt then please comment on it.

Thank you for reading this article.

Conclusion

In this tutorial, you learned how to capture the screen using Angular. Many browsers offers the screen capturing facility. However, integrating inside your application is a tedious task. Here I gave code for how to convert the taken base64 string to image and how to upload the image using the PHP. It is full implementation from taking an image to uploading it to the server.

Library Link:

https://www.npmjs.com/package/ngx-capture




Continue Learning