Realization of saving HTML to PDF screenshot


Using technology

itext.jar : convert byte file input stream to image, PDF, etc

html2 canvas.js : take a screenshot of the HTML page area as a Base64 encoded image resource


1. Prepare resources



2. Front end code:

//Take a screenshot, document.querySelector ("body") is the area to be shot
     function test() {
            html2canvas(document.querySelector("body"), {
                onrendered: function (canvas) {
                    var dataUrl = canvas.toDataURL('image/png');
                    Var formdata = new formdata(); // simulate form objects
                    formData.append ("imgdata", convertbase64urltoblob (dataurl)); // write data
                    Var XHR = new xmlhttprequest(); // data transfer method
           ("POST", " http://localhost : 8080 / PDF "); // configure the transmission mode and address
                    xhr.onreadystatechange  =Function () {// callback function

        //Format image Base64 encoding into byte file stream
        function convertBase64UrlToBlob(urlData){
            //Remove the header of the URL and convert it to byte
            var bytes=window.atob(urlData.split(',')[1]);
            //Exception handling, the ASCII code less than 0 to greater than 0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);
            for (var s = 0;s<bytes.length;s++){
                ia[s] = bytes.charCodeAt(s);
            return new Blob( [ab] , {type : 'image/png'});
        < body onclick = "test()" > // call the screenshot method

3. Back end code:

@RequestMapping(value = "/pdf",method = RequestMethod.POST)
    public void test(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = "D:\blog\exportPdf2.pdf";
        String imagePath = "D:\blog\exportImg2.png";
        Document document = new Document();
            Map getMap = request.getFileMap();
            MultipartFile mfile = (MultipartFile)  getMap.get ("imgdata"); // get data
            InputStream file = mfile.getInputStream();
            byte[] fileByte = FileCopyUtils.copyToByteArray(file);

            Fileimageoutputstream imageoutput = new fileimageoutputstream (new file (imagepath)); // open the input stream
            imageOutput.write (fileByte, 0,  fileByte.length ); // generate local image file

            PdfWriter.getInstance (document, new fileoutputstream (filepath)); // itextpdf file
            document.add(new Paragraph("JUST TEST ..."));
            Image image = Image.getInstance(imagePath); //itext-pdf-image
            float heigth = image.getHeight();
            float width = image.getWidth();
            Int percent = getpercent2 (height, width); // scale down the image

        }catch (DocumentException de) {
        catch (Exception e) {


    private static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;

4 package names

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

4 front end screenshot, access the back-end interface, save the screenshot file to the local PDF or other format file.

Interested students can change the back end to download files to the local

5 project source address 

This article about the realization of HTML to PDF screenshot saving function is introduced here. For more relevant HTML to PDF screenshot saving content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!