Javascript+java convert HTML to PDF document

Source: Internet
Author: User
Tags base64



  1. Introduction of the relevant jar package in the project



Itextasian-1.5.2.jar



Itext-4.2.1.jar



Itextpdf-5.1.2.jar



Itextpdf-5.1.2-sources.jar



  2. Add a button to a page that needs to convert the page to a PDF document



<span id= "Download" onclick= "exportpdf ();" > Conversion to Pdf</span>



<a id= "Pdfdown" style= "Display:none" ><span id= "Spanid" > Export pdf</span></a>



3. Then introduce the relevant JS and jar package



Html2canvas.js



4. Write the JS code that generates the PDF document





     / *
*Export PDF document
* /
function exportpdf(){
var title = "";
Layer. Prompt ({Title: "please enter PDF file name", formtype: 0, end: function(){
if(title != "" &amp;&amp; title != null){
Shot (title);
}
}}, function(pass, index){
title = pass;
layer.close(index);
};
}
//Convert page to picture
function shot(title){  
$("download"). Remove(); / / Hide button
Html2canvas (document. Body, {/ / object
//Detailed parameters can be configured here
Onrendered: function (canvas) {/ / callback canvas after rendering
canvas.id = "mycanvas"; 
//Generate Base64 picture data
Var dataurl = canvas.todataurl ("image / PNG"); / / specify the format or not
Var formdata = new formdata(); / / simulate form object
Formdata. Append ("imgdata", convertbase64urltoblob (dataurl)); / / write data
Var XHR = new xmlhttprequest(); / / data transfer method
XHR. Open ("post", ".. / pdftools / exportpdf? Filename =" + title); / / 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["mesg"] == "success"){
$("#pdfdown").attr("href","../file/downloadFile?fileName="+back[‘fileName‘]);
$("#spanid").click();
$("bodyid"). Prepend ("< span onclick =" exportpdf(); \ "id =" download \ "> Convert to PDF < / span >");
Layer.msg ("PDF export succeeded", {Icon: 1, time: 2000});
}else{
Layer.msg ("PDF export failed", {Icon: 2, time: 2000});
}
}
}
}
}
};
}
//Convert image URL data based on Base64 to blob
function convertBase64UrlToBlob(urlData){
//Remove the header from the URL and convert to byte
var bytes=window.atob(urlData.split(‘,‘)[1]); 
//Handle exception, convert 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"});
} 







5. Writing a background method





package com.sd.ddo.controller.pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfWriter;
import com.sd.cloud.util.alipay.HttpRequest;
import com.sd.cloud.util.alipay.HttpResponse;
import com.sd.cloud.util.common.CommonUtil;
import com.sd.cloud.util.common.SDConstants;
* *
*Export PDF document
* @author yugb
*Transforming HTML and JSP pages into PDF documents
* /
@Controller
@RequestMapping("/pdftools")
public class PDFExportController {
* *
*Export PDF document
* @param request
* @param response 
* @throws ServletException
* @throws IOException
* @throws DocumentException
* /
@SuppressWarnings("rawtypes")
@RequestMapping("/exportPdf")
public @ResponseBody Object exportPdf(MultipartHttpServletRequest request,HttpServletResponse response)throws ServletException, IOException, DocumentException {
Jsonobject result = new jsonobject(); / / custom result format
Try{
String filename = URLDecoder.decode(request.getParameter("filename"),"utf-8");
String filePath =SDConstants.fileDir+filename+".pdf";
String imagePath = SDConstants.fileDir +filename+".bmp";
Document document = new Document(); 
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));
Imageoutput. Write (filebyte, 0, filebyte. Length); / / generate local picture file
imageOutput.close();
Pdfwriter.getinstance (document, new fileoutputstream (filepath)); / / itextpdf file
document.open();
Image image = Image.getInstance(imagePath); // itext-pdf-image
float heigth = image.getHeight(); 
float width = image.getWidth(); 
Int percent = getpercent (height, width); / / scale down the picture
image.setAlignment(Image.MIDDLE); 
image.scalePercent(percent+3);
document.add(image);
document.close();
result.put("fileName", filename+".pdf");
result.put("imageName", filename+".bmp");
result.put("mesg", "success");
}catch (DocumentException de) {
System.err.println(de.getMessage());
}catch (Exception e) {
e.printStackTrace();
result.put("mesg", "error");
}
return result;
}
* *
*Percentage obtained
* @param H
* @param w
* @return
* /
private static int getPercent(float h, float w) {
Int p = 0;
float p2 = 0.0f;
p2 = 560 / w * 100;
p = Math.round(p2);
Return p;
}
} 





Javascript+java convert HTML to PDF document


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.