Realization of saving HTML to PDF screenshot

Time:2021-4-7

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

java+js

1. Prepare resources

itext.jar
 www.baidu.com

html2canvas.js
www.baidu.com

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
                    xhr.open ("POST", " http://localhost : 8080 / PDF "); // configure the transmission mode and address
                    xhr.send(formData);
                    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();
        try{
            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
            imageOutput.close();

            PdfWriter.getInstance (document, new fileoutputstream (filepath)); // itextpdf file
            document.open();
            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
            image.setAlignment(Image.MIDDLE);
            image.scalePercent(percent+3);
            document.add(image);
            document.close();

        }catch (DocumentException de) {
            System.err.println(de.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();

        }
    }

    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.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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

https://github.com/zhangjy520/learn_java/tree/master/boot 

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!