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

MySQL InnoDB transaction lock source code analysis

Table of contents 1. Lock and Latch 2. Repeatable...

Solve the problems encountered when installing MySQL 8.0 on Win10 system

The problems and solutions encountered when insta...

A brief analysis of how to upgrade PHP 5.4 to 5.6 in CentOS 7

1. Check the PHP version after entering the termi...

Steps to create a WEBSERVER using NODE.JS

Table of contents What is nodejs Install NodeJS H...

Learn javascript iterator

Table of contents Introduction What does an itera...

Detailed explanation of Angular data binding and its implementation

Table of contents Preface What is data binding? T...

JavaScript ECharts Usage Explanation

I used ECharts when doing a project before. Today...

How to install babel using npm in vscode

Preface The previous article introduced the insta...

Detailed explanation of incompatible changes in rendering functions in Vue3

Table of contents Rendering API changes Render fu...

OpenLayers realizes the method of aggregate display of point feature layers

Table of contents 1. Introduction 2. Aggregation ...

Introducing multiple custom fonts in CSS3

Today I found a problem in HTML. There are many d...

Docker custom network implementation

Table of contents 1. Customize the network to rea...

Summary of block-level elements, inline elements, and variable elements

Block element p - paragraph pre - format text tabl...