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

7 useful new TypeScript features

Table of contents 1. Optional Chaining 2. Null va...

Detailed examples of Docker-compose networks

Today I experimented with the network settings un...

A brief introduction to mysql mycat middleware

1. What is mycat A completely open source large d...

Sample code for configuring nginx to support https

1. Introduction Are you still leaving your websit...

How to create LVM for XFS file system in Ubuntu

Preface lvm (Logical Volume Manager) logical volu...

Master the commonly used HTML tags for quoting content in web pages

Use blockquote for long citations, q for short ci...

Using JavaScript difference to implement a comparison tool

Preface At work, I need to count the materials su...

JavaScript article will show you how to play with web forms

1. Introduction Earlier we introduced the rapid d...

Difference between src and href attributes

There is a difference between src and href, and t...

Detailed explanation of CSS multiple three-column adaptive layout implementation

Preface In order to follow the conventional WEB l...

About the pitfall record of Vue3 transition animation

Table of contents background Problem location Fur...

Text mode in IE! Introduction to the role of DOCTYPE

After solving the form auto-fill problem discussed...

Detailed steps to implement the Excel import function in Vue

1. Front-end-led implementation steps The first s...