获取http的pdf文件并存到本地转为img

来源:互联网 发布:luajit windows 编辑:程序博客网 时间:2024/06/09 20:06

获取http的pdf文件并存到本地转为img,该方法是为了打印使用。因为市面上大部分打印插件无法直接将pdf扔到设备上打印,需要二次操作。从而影响了效率,为此转存为img,利用lodop插件img的base64编码打印。从而可以实现连打功能。

package com.fx.wms.common.util;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URL;import javax.imageio.ImageIO;import org.apache.commons.codec.binary.Base64;import org.apache.commons.io.FileUtils;import org.jpedal.PdfDecoder;import org.jpedal.exception.PdfException;import org.jpedal.fonts.FontMappings;public class JPedal {    public static void main(String[] args) throws IOException, PdfException,InterruptedException {         /**instance of PdfDecoder to convert PDF into image*/          PdfDecoder decode_pdf = new PdfDecoder(true);          /**set mappings for non-embedded fonts to use*/          FontMappings.setFontReplacements();          /**open the PDF file - can also be a URL or a byte array*/          try {          decode_pdf.openPdfFile("C:/Users/oftoo/pdf/EV930739775CN.pdf"); //file          //decode_pdf.openPdfFile("C:/myPDF.pdf", "password"); //encrypted file          //decode_pdf.openPdfArray(bytes); //bytes is byte[] array with PDF          //decode_pdf.openPdfFileFromURL("http://www.mysite.com/myPDF.pdf",false);          /**get page 1 as an image*/          //page range if you want to extract all pages with a loop          int start = 1, end = decode_pdf.getPageCount();          for(int i=start;i<end+1;i++){              BufferedImage img=decode_pdf.getPageAsImage(i);              ImageIO.write(img, "png", new File("C:/Users/oftoo/pdf/"+i+"123.png"));            }          /**close the pdf file*/          decode_pdf.closePdfFile();          } catch (PdfException e) {              e.printStackTrace();          }        System.out.println("22222222222");    }    /**     *      * @Title: PdftoImage      * @Description: TODO(本地的pdf文件转img)      * @param @param urlPath     * @param @param savePath     * @param @return     * @param @throws IOException     * @param @throws PdfException     * @param @throws InterruptedException 设定文件      * @return boolean 返回类型      * @throws      * @author:oftoo     */    public boolean PdftoImage(String urlPath, String savePath)throws IOException, PdfException, InterruptedException{         /**instance of PdfDecoder to convert PDF into image*/              PdfDecoder decode_pdf = new PdfDecoder(true);            /**set mappings for non-embedded fonts to use*/              FontMappings.setFontReplacements();            /**open the PDF file - can also be a URL or a byte array*/              try {                  decode_pdf.openPdfFile(urlPath); //file                  //decode_pdf.openPdfFile("C:/myPDF.pdf", "password"); //encrypted file                  //decode_pdf.openPdfArray(bytes); //bytes is byte[] array with PDF                  //decode_pdf.openPdfFileFromURL("http://www.mysite.com/myPDF.pdf",false);                  /**get page 1 as an image*/                  //page range if you want to extract all pages with a loop                  int start = 1, end = decode_pdf.getPageCount();                  for(int i=start;i<end+1;i++){                      BufferedImage img=decode_pdf.getPageAsImage(i);                      ImageIO.write(img, "png", new File(savePath+"_i"+".png"));                    }                  /**close the pdf file*/                  decode_pdf.closePdfFile();              } catch (PdfException e) {                  e.printStackTrace();                   return false;            }        return true;     }    /**     *      * @Title: savePdf      * @Description: TODO(获取http的pdf文件保存到本地路径)      * @param @param url     * @param @param savePath     * @param @return 设定文件      * @return boolean 返回类型      * @throws      * @author:oftoo     */    public boolean savePdf(String url,String savePath){        boolean res = downloadFromUrl("http://baidu.com/xxx.pdf","d:/");          return res;      }    public static String getFileNameFromUrl(String url){          String name = new Long(System.currentTimeMillis()).toString() + ".X";          int index = url.lastIndexOf("/");          if(index > 0){              name = url.substring(index + 1);              if(name.trim().length()>0){                  return name;              }          }          return name;      }   public boolean  downloadFromUrl(String url,String dir) {       try {             URL httpurl = new URL(url);             String fileName = getFileNameFromUrl(url);             System.out.println(fileName);             File f = new File(dir + fileName);             FileUtils.copyURLToFile(httpurl, f);         } catch (Exception e) {             e.printStackTrace();             return false;         }          return true;     }       /**    *     * @Title: GetImageStr     * @Description: TODO(将图片文件转化为字节数组字符串,并对其进行Base64编码处理  )     * @param @param imgFilePath    * @param @return 设定文件     * @return String 返回类型     * @throws     * @author:oftoo    */   public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理          byte[] data = null;      // 读取图片字节数组          try {              InputStream in = new FileInputStream(imgFilePath);              data = new byte[in.available()];              in.read(data);              in.close();          } catch (IOException e) {              e.printStackTrace();          }          // 对字节数组Base64编码          //BASE64Encoder encoder = new BASE64Encoder();          return new String(Base64.encodeBase64(data));// 返回Base64编码过的字节数组字符串      }     /**    *     * @Title: GenerateImage     * @Description: TODO(对字节数组字符串进行Base64解码并生成图片  )     * @param @param imgStr    * @param @param imgFilePath    * @param @return 设定文件     * @return boolean 返回类型     * @throws     * @author:oftoo    */    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片          if (imgStr == null) // 图像数据为空              return false;          try {          // Base64解码              byte[] bytes = Base64.decodeBase64(imgStr);             for (int i = 0; i < bytes.length; ++i) {                  if (bytes[i] < 0) {// 调整异常数据                      bytes[i] += 256;                  }              }          // 生成jpeg图片              OutputStream out = new FileOutputStream(imgFilePath);              out.write(bytes);              out.flush();              out.close();              return true;          } catch (Exception e) {              return false;          }      }}
0 0
原创粉丝点击