Save HTML pages as pictures, images written to PDF implementation method (recommended) _javascript tips

Source: Internet
Author: User
Tags base64 domain server

The requirement is a function of exporting PDF, the multi-party run finally realized, took a lot of detours, and doubt now this method is still curved.

There is a jspdf plug-in can be directly generated in the front-end PDF, very simple, but does not support ie.

Front:

First introduce html2canvas.js

Html2canvas (document.body, {//Screenshot object///Here configurable detailed parameters Onrendered:function (canvas) {//render complete callback canvas Canvas.id 
       = "MyCanvas";  Generate Base64 picture data var dataurl = Canvas.todataurl (' image/png '); Specifies the format, and can also be without parameters var formData = new FormData (); Simulate the Form object Formdata.append ("Imgdata", Convertbase64urltoblob (Dataurl), "123.png"); Write data var xhr = new XMLHttpRequest (); Data transfer Method Xhr.open ("POST", ".. /bulletin/exportpdf ");
       Configure transmission mode 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 exported successfully!)
               ', lock:true,drag:false,ok:true}); }else{Alertbox ({content: ' PDF export failed!)
               ', lock:true,drag:false,ok:true});
     }
            }
         }
       }; 
  
}
}); Converts a base64 picture URL data to a blob functIon Convertbase64urltoblob (Urldata) {//Remove the header of the URL and convert to byte var Bytes=window.atob (Urldata.split (', ') [1]);
  Handles the exception, converts the ASCII code 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+

Not supported: IFRAME, browser plugin, Flash

Cross-domain pictures need to cross domain server header plus allow Cross-domain requests

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

SVG pictures are not directly supported, there is already a patch package, but I did not try.

IE9 does not support formdata data formats or blobs, in which case the canvas generated 64base string is removed directly to the background after the URL header is received:

String base64 = Img.split (",") [1];
Base64decoder decode = new Base64decoder (); 
byte[] Imgbyte = Decode.decodebuffer (base64);

Back end:

Import Itext jar Package

@RequestMapping ("/exportpdf") public @ResponseBody void Exportpdf (Multiparthttpservletrequest request,  HttpServletResponse response) throws Servletexception, IOException {resultdata result = new Resultdata ();
  Custom 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");
    Gets the 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 picture 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 heigth = Image.getheight (); 
        Float width = image.getwidth ();  int percent = GetPercent2 (heigth, width); 
        Shrink the picture image.setalignment (Image.middle) proportionally;
    Image.scalepercent (percent+3);
    Document.add (image);
  
    Document.close ();
    Result.setsuccess (TRUE);
  Operatelogservice.addoperateloginfo (Request, "Export success: Successful export newsletter PDF");
  }catch (Documentexception de) {System.err.println (De.getmessage ());
    catch (Exception e) {e.printstacktrace ();
    Result.setsuccess (FALSE);
    Result.seterrormessage (E.tostring ());
    try {operatelogservice.addoperatelogerror (Request, "Export failed: Server exception");
    catch (Exception E1) {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 well-known open source site SourceForge a project that is used to generate a PDF document of a Java class library.

Fast processing and supports many PDF "advanced" features.

But Itext error will not complain, skip directly, look back at the PDF document damage, can not find the cause of the error, really nasty dead.

Finally, thank you for the online blog posts and posts as well as Baidu search.

This article will be the HTML page to save the image, the image written to the PDF implementation method (recommended) is small to share all the content of the whole, hope to give you a reference, but also hope that we support cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.