javascript+java实现html转化为PDF文档

  1. 项目中引入相关的jar包

    itextasian-1.5.2.jar

    itext-4.2.1.jar

    itextpdf-5.1.2.jar

    itextpdf-5.1.2-sources.jar

  2. 在需要将页面转化为pdf文档的页面中添加按钮

     <span id="download" οnclick="exportpdf();">转化为PDF</span>

     <a id="pdfdown" style="display: none"><span id="spanid">导出PDF</span></a>  

  3. 然后引入相关的js以及jar包

    html2canvas.js

  4.编写生成pdf文档的js代码

   

   /*

    * 导出pdf文档
    */
    function exportpdf(){
      var title = "";
      layer.prompt({title: "请输入pdf文件名", formType: 0,end:function(){
      if(title != "" && title != null){
        shot(title);
      }
    }}, function(pass, index){
      title = pass;
      layer.close(index);
    });
  };

  //将页面转化为图片
  function shot(title){    
    $("#download").remove();    //隐藏按钮
    html2canvas(document.body, { //截图对象
    //此处可配置详细参数
      onrendered: function(canvas) { //渲染完成回调canvas
      canvas.id = "mycanvas"; 
      // 生成base64图片数据
      var dataUrl = canvas.toDataURL("image/png"); //指定格式,也可不带参数
      var formData = new FormData(); //模拟表单对象
      formData.append("imgData",convertBase64UrlToBlob(dataUrl)); //写入数据
      var xhr = new XMLHttpRequest(); //数据传输方法
      xhr.open("POST", "../pdftools/exportPdf?filename="+title); //配置传输方式及地址
      xhr.send(formData);
      xhr.onreadystatechange = 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 οnclick=\"exportpdf();\" id=\"download\">转化为PDF</span>");
            layer.msg("Pdf导出成功",{icon:1,time:2000});
          }else{
            layer.msg("Pdf导出失败",{icon:2,time:2000});
          }
        }
       } 
     };
    }
  }); 
}
//将以base64的图片url数据转换为Blob
function convertBase64UrlToBlob(urlData){
  //去掉url的头,并转换为byte
  var bytes=window.atob(urlData.split(',')[1]); 
  //处理异常,将ascii码小于0的转换为大于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"});
}
View Code

 

 

  5. 编写后台方法

 

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;
/**
 * 导出pdf文档
 * @author yugb
 * 将html,jsp页面转化为pdf文档
 */
@Controller
@RequestMapping("/pdftools")
public class PDFExportController {
    /**
     * 导出pdf文档
     * @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(); //自定义结果格式
        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"); //获取数据
             InputStream file = mfile.getInputStream();
             byte[] fileByte = FileCopyUtils.copyToByteArray(file);
             FileImageOutputStream imageOutput = new FileImageOutputStream(new File(imagePath));
             imageOutput.write(fileByte, 0, fileByte.length);//生成本地图片文件
             imageOutput.close();
            
             PdfWriter.getInstance(document, new FileOutputStream(filePath)); //itextpdf文件
             document.open();
             Image image = Image.getInstance(imagePath); // itext-pdf-image
             float heigth = image.getHeight(); 
             float width = image.getWidth(); 
             int percent = getPercent(heigth, width);  //按比例缩小图片
             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;
    }
    /**
     * 获得百分比
     * @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;
    }
}

 

转载于:https://www.cnblogs.com/yugb/p/9571599.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值