English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation Method of Saving HTML Page as Image and Writing Image to PDF (Recommended)

The requirement is to implement an export pdf function, and after much effort, it has finally been realized, but a lot of detours have been taken, and it is suspected that the method now is still a detour.

There is a jsPDF plugin that can directly generate pdf on the front-end, which is very simple, but does not support IE.

Front-end:

Firstly introduce  html2canvas.js

html2canvas(document.body, { //Screenshot object
     //Here you can configure detailed parameters
     onrendered: function(canvas) { //Rendering completed callback canvas
       canvas.id = "mycanvas"; 
       // Generate base64Image data
       var dataUrl = canvas.toDataURL('image/png');  //Specify the format, or you can also not pass parameters
       var formData = new FormData(); //Simulated form object
       formData.append("imgData", convertBase64UrlToBlob(dataUrl), "123.png"); //Write data
       var xhr = new XMLHttpRequest(); //Data transmission method
       xhr.open("POST", "../bulletin/exportPdf"); //Configure the transmission method and address
       xhr.send(formData);
       xhr.onreadystatechange = function(){ //callback function
         if(xhr.readyState === 4{
            if (xhr.status === 200) {
               var back = JSON.parse(xhr.responseText);
               if(back.success == true){
                 alertBox({content: 'Pdf export successful!',lock: true,drag: false,ok: true});
               }else{
                 alertBox({content: 'Pdf export failed!',lock: true,drag: false,ok: true});
               }
            }
         }
       };
     }
}); 
//will be in base64convert the image URL data to Blob
function convertBase64UrlToBlob(urlData){
  //Remove the URL header and convert to byte
  var bytes=window.atob(urlData.split(',')[1]);    
  //Handle exceptions, convert ascii codes less than 0 to greater than 0
  var ab = new ArrayBuffer(bytes.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob( [ab] , {type : 'image/png'});
}

Compatibility: Firefox 3.5+, Chrome, Opera, IE10+

Does not support: iframe, browser plugins, Flash

Cross-domain images need to add the header allowing cross-domain requests on the cross-domain server

access-control-allow-origin: *  access-control-allow-credentials: true

SVG images cannot be supported directly, there is already a patch package, but I haven't tried it yet.

IE9Does not support FormData data format, nor Blob, in this case, the canvas generated64Pass the base string after removing the URL header directly to the backend, and after the backend receives it:

String base64 = Img.split(",")[1];
BASE64Decoder decode = new BASE64Decoder(); 
byte[] imgByte = decode.decodeBuffer(base64);

Backend:

Import itext jar package

 

@RequestMapping("/exportPdf)
public @ResponseBody void exportPdf(MultipartHttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
  ResultData result = new ResultData();  //Customize result format
  String filePath = "c:\\exportPdf2.pdf";
  String imagePath = "c:\\exportImg2.bmp";
  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 input stream
    imageOutput.write(fileByte, 0, fileByte.length);//Generate local image file
    imageOutput.close();
    PdfWriter.getInstance(document, new FileOutputStream(filePath)); //itextpdf file
//    document.setPageSize(PageSize.A2);
    document.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(height, width);  //Reduce the image proportionally
        image.setAlignment(Image.MIDDLE); 
        image.scalePercent(percent+3);
    document.add(image);
    document.close();
    result.setSuccess(true);
    operatelogService.addOperateLogInfo(request, "Export successful: Successfully exported brief report Pdf");
  catch (Exception e) {
    e.printStackTrace();
  }
  result.setSuccess(false);
    result.setErrorMessage(e.toString());
    try {
    operatelogService.addOperateLogError(request, "Export failed: Server exception");
    ) {
      catch (Exception e
    }1) {
      e1.printStackTrace();
    }
  }
  response.getWriter().print(JSONObject.fromObject(result).toString());
}
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;
}

 iText is a famous open-source project on the site sourceforge, which is a Java class library for generating PDF documents.

Fast processing speed, supporting many "advanced" features of PDF.

However, when iText fails, it will not report an error and will skip directly. Looking back, the PDF document is damaged and the cause of the error cannot be found, which is really frustrating.

Finally, thank you for the relevant articles and posts on the Internet and Baidu search.

This article will introduce the implementation method of saving an HTML page as an image and writing it into a PDF (recommended), which is all the content shared by the editor. It is hoped that it can provide a reference for everyone and everyone is welcome to support the Yell Tutorial.

You May Also Like