Implementation of HTML to PDF screenshot saving function

Implementation of HTML to PDF screenshot saving function

Using Technology

itext.jar: Convert byte file input stream to images, PDF, etc.

html2canvas.js: screenshots of HTML page areas as base64-encoded image resources

java+js

1. Prepare resources

itext.jar
www.baidu.com

html2canvas.js
www.baidu.com

2. Front-end code:

//Perform screenshot operation, document.querySelector("body") is the area to be screenshot function test() {
            html2canvas(document.querySelector("body"), {
                onrendered: function (canvas) {
                    var dataUrl = canvas.toDataURL('image/png');
                    var formData = new FormData(); //Simulate form object formData.append("imgData", convertBase64UrlToBlob(dataUrl)); //Write data var xhr = new XMLHttpRequest(); //Data transmission method xhr.open("POST", "http://localhost:8080/pdf"); //Configure transmission method and address xhr.send(formData);
                    xhr.onreadystatechange = function () { //callback function};
                }
            });
        }

        //Format the image base64 encoding and convert it to byte file stream function convertBase64UrlToBlob(urlData){
            //Remove the URL header and convert it to byte
            var bytes = window.atob(urlData.split(',')[1]);
            //Handle exceptions and convert ascii codes 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. Backend 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 a local image file imageOutput.close();

            PdfWriter.getInstance(document, new FileOutputStream(filePath)); //itextpdf filedocument.open();
            document.add(new Paragraph("JUST TEST ..."));
            Image image = Image.getInstance(imagePath); //itext-pdf-image
            float height = image.getHeight();
            float width = image.getWidth();
            int percent = getPercent2(heigth, 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 Name

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 Take screenshots on the front end, access the back end interface, and save the screenshot files locally as pdf or other formats.

Interested students can change the backend to download files to local

5 Project source code address

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

This is the end of this article about the implementation of HTML to PDF screenshot saving function. For more relevant HTML to PDF screenshot saving content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

<<:  CSS pseudo-element::marker detailed explanation

>>:  About CSS floating and canceling floating

Recommend

Introduction to NFS service construction under Centos7

Table of contents 1. Server 2. Client 3. Testing ...

MySQL character set viewing and modification tutorial

1. Check the character set 1. Check the MYSQL dat...

Implementation of fuzzy query like%% in MySQL

1, %: represents any 0 or more characters. It can...

Detailed tutorial on VMware installation of Linux CentOS 7.7 system

How to install Linux CentOS 7.7 system in Vmware,...

Two ways to remove the 30-second ad code from Youku video

I believe everyone has had this feeling: watching ...

Usage and description of HTML tag tbody

The tbody element should be used in conjunction wi...

Vue implements zip file download

This article example shares the specific code of ...

The complete version of the common Linux tool vi/vim

Why learn vim Linux has a large number of configu...

Example of how to configure multiple virtual hosts in nginx

It is very convenient to configure virtual host v...

Mysql 5.7.19 free installation version encountered pitfalls (collection)

1. Download the 64-bit zip file from the official...

Some parameter descriptions of text input boxes in web design

<br />In general guestbooks, forums and othe...