package com.uboobo.pdf; 



 import java.awt.image.BufferedImage; 

 import java.awt.image.RenderedImage; 

 import java.io.BufferedInputStream; 

 import java.io.BufferedOutputStream; 

 import java.io.ByteArrayOutputStream; 

 import java.io.File; 

 import java.io.FileInputStream; 

 import java.io.FileNotFoundException; 

 import java.io.FileOutputStream; 

 import java.io.IOException; 

 import java.io.InputStream; 

 import java.io.OutputStream; 

 import java.util.ArrayList; 

 import java.util.HashMap; 

 import java.util.List; 

 import java.util.Map; 

 import java.util.zip.ZipEntry; 

 import java.util.zip.ZipOutputStream; 



 import javax.imageio.ImageIO; 

 import javax.media.jai.JAI; 

 import javax.media.jai.RenderedOp; 



 import org.apache.commons.lang.StringUtils; 

 import org.apache.commons.net.ftp.FTPClient; 

 import org.apache.commons.net.ftp.FTPFile; 

 import org.apache.commons.net.ftp.FTPReply; 

 import org.dom4j.DocumentHelper; 

 import org.dom4j.Element; 

 import org.dom4j.io.OutputFormat; 

 import org.dom4j.io.XMLWriter; 

 import org.icepdf.core.pobjects.Document; 

 import org.icepdf.core.pobjects.Page; 

 import org.icepdf.core.util.GraphicsRenderingHints; 

 import org.xhtmlrenderer.pdf.ITextFontResolver; 

 import org.xhtmlrenderer.pdf.ITextRenderer; 



 import com.lowagie.text.pdf.BaseFont; 

 import com.sun.media.imageio.plugins.tiff.TIFFTag; 

 import com.sun.media.jai.codec.ImageCodec; 

 import com.sun.media.jai.codec.ImageEncoder; 

 import com.sun.media.jai.codec.TIFFEncodeParam; 

 import com.sun.media.jai.codec.TIFFField; 



 public class HTMLToPDF { 

 

/** 

      * 把二进制流转化为byte字节数组 

      * @param instream 

      * @return byte[] 

      * @throws Exception 

      */ 

     public static byte[] readInputStream(InputStream instream) throws Exception { 

         ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 

         byte[]  buffer = new byte[1204]; 

         int len = 0; 

         while ((len = instream.read(buffer)) != -1){ 

             outStream.write(buffer,0,len); 

         } 

         instream.close(); 

         return outStream.toByteArray();          

     } 

     /** 

      * 通过网站域名URL获取该网站的源码 

      * @param url 

      * @return String 

      * @throws Exception 

      */ 

     public static String getURLSource(File url) throws Exception    { 

         //HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 

         InputStream inStream = new FileInputStream(url); 

         /*conn.setRequestMethod("GET"); 

         conn.setConnectTimeout(5 * 1000); 

         InputStream inStream =  conn.getInputStream();*/  //通过输入流获取html二进制数据 

         byte[] data = readInputStream(inStream);        //把二进制数据转化为byte字节数据 

         String htmlSource = new String(data,"UTF-8"); 
 //将二进制数据转为utf-8的字符串,即最终将网页数据转为字符串 

         inStream.close(); 

         return htmlSource; 

     } 

     /** 

      *  

      * @param newString 

      * @return 

      * @throws Exception 

      */ 

     public static String htmlString(String newString) throws Exception{ 

     
String urlSource = getURLSource(new File("D:/index.html")); 

     
urlSource.replace("xxxx", newString);  //将URLSource中的字符替换成需要的字符 

     
return urlSource; 

     } 

     /** 

      * 支持中文 

      * 将字符串转为PDF文件 

      * @param str 要转的HTML转化字符,要求HTML要是标准的HTML并且HTML头信息(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">) 

      * @param path PDF文件生成的路径 

      * @throws Exception 

      */ 

     public void htmlToPdf(String str,String path) throws Exception  

     { 

         String outputFile = path+"/insured.pdf";        

         System.out.println("path = "+path);   

         OutputStream os = new FileOutputStream(outputFile);        

         ITextRenderer renderer = new ITextRenderer(); 

         ITextFontResolver fontResolver = renderer.getFontResolver();        

 //      fontResolver.addFont("/usr/share/fonts/local/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//指定ftp服务器上的字体 

         fontResolver.addFont("C:/Windows/Fonts/SimSun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//本地,指定字体 

         renderer.setDocumentFromString(str); 

         // 解决图片的相对路径问题 

         renderer.getSharedContext().setBaseURL(this.getClass().getClassLoader().getResource("tian.png").toString());//"file:/D:/apache-tomcat-7.0.40/webapps/my_bsc/sign/tian.png" 

         renderer.layout();     

          

         renderer.createPDF(os); 

         System.out.println("======转换成功!");  

         os.flush(); 

         os.close();        

     } 

     /** 

* 转换指定pdf文件为图片到指定的文件夹目录下 

* @param pdfFilePath 
 需要转换的pdf文件路径 

* @param imgPushPath 
 需要存放转换后的图片文件目录路径 

* @param name 
  文件名 

* @param imgScaling 
 图片缩放的比例 

* @return 
  转换后图片的文件名集合 

*/ 

public Map<String, Object> converPdfToImg(String pdfFilePath,String imgPushPath,String name,float imgScaling){ 

//定义Document,用于转换图片 

         Document document = new Document(); 

         //用来保存当前页的页码 

         Map<String, Object> map = new HashMap<String, Object>(); 

         

         try { 

             document.setFile(pdfFilePath); 

         } catch (Exception ex) { 

         
ex.printStackTrace(); 

         } 

         // save page caputres to file. 

         float rotation = 0f; 

         int maxPages = document.getNumberOfPages(); 

         // 循环把每页的数据转换成对应的图片 

         List<String> listName = new ArrayList<String>(); 

         for (int i = 0; i < document.getNumberOfPages(); i++) { 

             BufferedImage image = (BufferedImage) 

             
document.getPageImage(i,GraphicsRenderingHints.SCREEN,Page.BOUNDARY_CROPBOX, rotation, imgScaling); 

             RenderedImage rendImage = image; 

             try { 

                 int j = i+3; 

                 File file = new File(imgPushPath+name+"_"+j+"_0001.jpg"); 

                 ImageIO.write(rendImage, "jpg" , file); 

                 listName.add(name+"_"+j+"_0001.tif"); 

             } catch (IOException e) { 

                 e.printStackTrace(); 

             } 

             image.flush(); 

         } 

         // 清理document资源 

         document.dispose(); 

         map.put("pageCount", maxPages); 

         map.put("listName", listName); 

return map; 

} 

/** 

*  

* @param pdfpath  

* @param path 

* @param prtno 

* @param tiffPath 

* @param fileName 

* @param teamcode 

* @return 

*/ 

public List<String> toJpg(String pdfpath , String path,String prtno,String tiffPath,String fileName,String teamcode){ 

Map<String, Object> converPdfToImg = this.converPdfToImg(pdfpath, path+"/", teamcode+"_"+prtno,3.145f);//机构_单号_序号_0001  例如:3006_010_0001 

List<String> listName = (List<String>) converPdfToImg.get("listName"); 

this.BuildXMLDoc(tiffPath+"/"+prtno,listName,prtno,fileName,"0001"); 

return listName; 

} 

/** 

* 创建XML文档 

* @param path 影像文件路径 

* @param listName 影像文件名称集合 

* @param proposalprtno 单号 

* @param fileName1 

* @param billcard1 

*/ 

public void BuildXMLDoc(String path , List<String> listName , String prtno ,String fileName1,String billcard1){ 

 //1.创建document对象,代表整个xml文档 

 org.dom4j.Document document = DocumentHelper.createDocument(); 

     //2.创建根节点lifeInsurance 

     Element request = document.addElement("request"); 

     //3.向lifeInsurance节点中添加version属性 

     //request.addAttribute("version", "2.0"); 

     //4.生成子节点及节点内容 

     Element main = request.addElement("main"); 

     Element proposalNumber = main.addElement("proposalNumber"); 

     proposalNumber.setText(prtno); 

     Element images = request.addElement("images"); 

     for (int i = 0; i < listName.size(); i++) { 

    
  Element image = images.addElement("image"); 

    
  Element billcard = image.addElement("billcard"); 

    
  billcard.setText(billcard1); 

    
  Element fileName = image.addElement("fileName"); 

    
  fileName.setText(listName.get(i)); 

    
  Element pageNo = image.addElement("pageNo"); 

    
  if("014".equals(billcard1)){ 

    
  pageNo.setText(String.valueOf(i+1)); 

    
  }else{ 

    
  pageNo.setText(String.valueOf(i+3)); 

    
  } 

     } 

     //5.设置生成xml的格式 

     OutputFormat format = OutputFormat.createPrettyPrint(); 

     format.setEncoding("UTF-8"); 

     //6.生成xml文件 

     fileName1 = fileName1.substring(fileName1.indexOf("_")+1,fileName1.length()); 

     File file = new File(path+"_"+fileName1+"_25"+".xml"); 

     XMLWriter writer; 

     try { 

         writer = new XMLWriter(new FileOutputStream(file), format); 

         //设置是否转义,默认是true,代表转义 

         writer.setEscapeText(false); 

         writer.write(document); 

         writer.close(); 

     } catch (IOException e) { 

         e.printStackTrace(); 

         System.out.println("生成xml时发生异常"); 

     } 

} 

     /** 

      * 将图片转成TIFF CCITT 6压缩 300dpi 

      * 

      * @param sourceFilePath 

      * @param outputFilePath 

      * @param dpi 

      */ 

     public static void TiffOutput(String sourceFilePath, String outputFilePath, int dpi) { 

         try { 

             FileOutputStream fos = new FileOutputStream(outputFilePath); 

             RenderedOp src = JAI.create("fileload", sourceFilePath); 

             BufferedImage buf = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY); 

             buf.getGraphics().drawImage(src.getAsBufferedImage(), 0, 0, null); 

             RenderedImage ri = (RenderedImage) buf; 



             TIFFEncodeParam encodeParam = new TIFFEncodeParam(); 

             encodeParam.setCompression(TIFFEncodeParam.COMPRESSION_GROUP4); 

             TIFFField[] extras = new TIFFField[2]; 

             extras[0] = new TIFFField(282, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) dpi, 1}, {0, 0}}); 

             extras[1] = new TIFFField(283, TIFFTag.TIFF_RATIONAL, 1, (Object) new long[][]{{(long) dpi, 1}, {0, 0}}); 

             encodeParam.setExtraFields(extras); 



             ImageEncoder enc = ImageCodec.createImageEncoder("TIFF", fos, encodeParam); 

             enc.encode(ri); 

         } catch (IOException ex) { 

             ex.printStackTrace(); 

         } 

     } 

     /** 

      * 将jpg目录下的所有图片生成到TIFF目录下的TIFF文件 

      * @param sourceFilePath  

      * @param outputFilePath 

      */ 

     public static void totif(String sourceFilePath , String outputFilePath) { 

     
try { 

             File sourcePath = new File(sourceFilePath); 

             File[] files = sourcePath.listFiles(); 

             for (File file : files) { 

                 TiffOutput(file.getAbsolutePath(), outputFilePath + file.getName().substring(0,file.getName().length()-4) + ".tif", 400); 

             } 

         } catch (Exception e) { 

             e.printStackTrace(); 

         } 

     } 

     /** 

      * 压缩文件 

      * @param sourceFilePath 

      * @param zipFilePath 

      * @return 

      */ 

     public boolean fileToZip(String sourceFilePath, String zipFilePath) { 

boolean flag = false; 

File sourceFile = new File(sourceFilePath); 

FileInputStream fis = null; 

BufferedInputStream bis = null; 

FileOutputStream fos = null; 

ZipOutputStream zos = null; 



if (sourceFile.exists() == false) { 

System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 不存在. <<<<<<"); 

} else { 

try { 

File zipFile = new File(zipFilePath); 

if (zipFile.exists()) { 

} else { 

File[] sourceFiles = sourceFile.listFiles(); 

if (null == sourceFiles || sourceFiles.length < 1) { 

System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath 
 + " 里面不存在文件,无需压缩. <<<<<<"); 

} else { 

fos = new FileOutputStream(zipFile); 

zos = new ZipOutputStream(new BufferedOutputStream(fos)); 

byte[] bufs = new byte[1024 * 10]; 

for (int i = 0; i < sourceFiles.length; i++) { 

// 创建ZIP实体,并添加进压缩包   

ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName()); 

zos.putNextEntry(zipEntry); 

 

// 读取待压缩的文件并写进压缩包里   

fis = new FileInputStream(sourceFiles[i]); 

bis = new BufferedInputStream(fis, 1024 * 10); 

int read = 0; 

while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) { 

zos.write(bufs, 0, read); 

} 

} 

flag = true; 

} 

} 

} catch (FileNotFoundException e) { 

e.printStackTrace(); 

} catch (IOException e) { 

e.printStackTrace(); 

} finally { 

// 关闭流   

try { 

if (null != bis) 

bis.close(); 

if (null != zos) 

zos.close(); 

} catch (IOException e) { 

e.printStackTrace(); 

} 

} 

} 

return flag; 

} 

      

     /** 

      * 检查ftp服务器上是否存在指定目录 

      * @param ftp 

      * @param dirName 指定目录名称 

      * @return 

      */ 

     public boolean checkDirectory(FTPClient ftp, String dirName) { 

         boolean _flag = false;   

         try {   

             FTPFile[] files = ftp.listFiles();   

             for (int i = 0; i < files.length; i++) {   

                 FTPFile file = files[i];   

                 if (file.isDirectory()) {   

                     if (dirName.equalsIgnoreCase(file.getName())) {   

                         _flag = true;   

                         break;   

                     }   

                 }   

             }   

         } catch (Exception e) {   

             e.printStackTrace();   

         }   

         return _flag;   

     }  

      

     /** 本地字符编码 */   

     private static String LOCAL_CHARSET = "GBK";   

     /** FTP协议里面,规定文件名编码为iso-8859-1 */  

     private static String SERVER_CHARSET = "ISO-8859-1"; 

     /**   

      * Description: 向FTP服务器上传文件   

      * @param url FTP服务器hostname   

      * @param port FTP服务器端口   

      * @param username FTP登录账号   

      * @param password FTP登录密码   

      * @param path FTP服务器保存目录   

      * @param filename 上传到FTP服务器上的文件名   

      * @param input 输入流   

      * @return 成功返回true,否则返回false   

      */     

     public int uploadFile(String path, String filename, InputStream input) { 

         int success = 0; 

         //ftp连接参数   

         String ftpServer =   "180.76.188.26";   

         int ftpPort = 21;   

         String ftpUser = "taftp";   

         String ftpPassword = "myftp";   

         FTPClient ftp = new FTPClient();     

         try {   

             int reply;   

             // 连接FTP服务器    

             ftp.connect(ftpServer, ftpPort);    

             // 登录ftp   

             ftp.login(ftpUser, ftpPassword);   

             // 看返回的值是不是230,如果是,表示登陆成功   

             reply = ftp.getReplyCode();    

             // 以2开头的返回值就会为真    

             if (!FTPReply.isPositiveCompletion(reply)) {   

                 ftp.disconnect();   

                 return success;   

             }   

             // 检查路径目录,没有就创建   

             path = StringUtils.removeStart(path, "/");   

             String[] typeArray = path.split("/");   

             for (int i = 0; i < typeArray.length; i++) {  

                 if (!checkDirectory(ftp, typeArray[i])){   

                     ftp.makeDirectory(typeArray[i]);   

                     System.out.println("不存在路径,创建路径"); 

                 }   

                 ftp.changeWorkingDirectory(typeArray[i]);   

             }   

             // 转到指定上传目录     

             ftp.changeWorkingDirectory(path);   

             //设置每次读取文件流时缓存数组的大小   

             ftp.setBufferSize(1024);    

             //设置编码格式,解决中文乱码问题   

             if (FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).   

                 LOCAL_CHARSET = "UTF-8";   

             }   

             ftp.setControlEncoding(LOCAL_CHARSET);   

             // 设置文件类型(二进制)    

             ftp.setFileType(FTPClient.BINARY_FILE_TYPE);    

             // 将上传文件存储到指定目录   

             ftp.storeFile(new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET), input); 

             // 退出ftp    

             ftp.logout();   

             success = 1;   

         } catch (IOException e) {   

             e.printStackTrace();     

         } finally {   

             try{   

                 if(input != null){   

                     input.close();   

                 }   

                 if (ftp.isConnected()) { 

                      ftp.disconnect();     

                 }   

             }catch(Exception e){   

                 e.printStackTrace();   

             }   

         }   

         return success;   

     }   

        

        

     /**   

      * Description: 删除ftp上的文件  

      * @return 成功返回true,否则返回false   

      */     

     public boolean deleteFileFtp(String path) {   

         boolean success = false;   

         //ftp连接参数   

         String ftpServer =  "180.76.188.26";   

         int ftpPort = 21;   

         String ftpUser = "taftp";   

         String ftpPassword = "myftp";  

         FTPClient ftp = new FTPClient();     

         try {   

              int reply;   

             // 连接FTP服务器    

             ftp.connect(ftpServer, ftpPort);    

             // 登录ftp   

             ftp.login(ftpUser, ftpPassword);   

             // 看返回的值是不是230,如果是,表示登陆成功   

             reply = ftp.getReplyCode();    

             // 以2开头的返回值就会为真    

             if (!FTPReply.isPositiveCompletion(reply)) {   

                 ftp.disconnect();   

                 return success;   

             }   

             success = ftp.deleteFile(path);   

         } catch (IOException e) {   

             e.printStackTrace();   

         } finally {     

             if (ftp.isConnected()) {   

                 try {     

                     ftp.disconnect();     

                 } catch (IOException ioe) {   

                 }   

             }   

         }   

         return success;   

     }  

      

 }