首先创建一个 Java 工程,把下载好的 pdfbox-2.0.2.jar 作为类库加入工程
//pdf转图片上传到ftp上
public String pdfImage(String pdfUrl,String title){ StringBuffer imageUrls = new StringBuffer(); try { InputStream responseBodyAsStream = null; org.apache.commons.httpclient.HttpClient client=new org.apache.commons.httpclient.HttpClient(); GetMethod getMethod=new GetMethod(pdfUrl); int executeMethod = client.executeMethod(getMethod); if(executeMethod==200){ responseBodyAsStream = getMethod.getResponseBodyAsStream(); } PDDocument doc = PDDocument.load(responseBodyAsStream); PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { //将PDF生成图片流 BufferedImage image = renderer.renderImageWithDPI(i, 90); ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); ImageIO.write(image, "PNG", outputStream); //将图片流上传到ftp,ftpDir目录 String dir = ftpDir + "/invoice/img/"; String filename = title+"_"+i+".jpg"; InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); boolean bln = ftp.upload(is, dir, filename); if(bln){//ftpViewUrl 预览/下载地址
imageUrls.append(ftpViewUrl + dir + filename).append(";"); } } return imageUrls.toString(); } catch (Exception e) { log.debug(e); return null; } }private static FTPClientConfigure config;
// 连接池
final GenericKeyedObjectPool<FTPClientConfigure, FTPClient> pool = new FTPClientPool(new FTPClientFactory(), new FTPPoolConfig());/**
* 获取. <br/> * */ private FTPClient get() { try { if (null == config) config = new FTPClientConfigure(host, port, username, password); return pool.borrowObject(config); } catch (Exception e) { e.printStackTrace(); } return null; }/**
* 归还. <br/> * obj */ private void returnObject(FTPClient obj) { pool.returnObject(config, obj); }//ftp上传
public boolean upload(InputStream fis, String dir, String fileName) {
boolean result = false; FTPClient client = get(); if (null == client) return result; try { // 切换至跟目录 client.changeWorkingDirectory("/"); // 设置上传目录 if (StringUtils.isNotBlank(dir)) { // 防止中文目录乱码 dir = new String(dir.getBytes(LOCAL_CHARSET), SERVER_CHARSET); // 切换目录 if (!client.changeWorkingDirectory(dir)) { // 切换失败,创建目录 String[] dirs = dir.replaceAll("\\\\", "/").replaceAll("//", "/").split("/"); for (String d : dirs) { if (StringUtils.isBlank(d)) continue; if (!client.changeWorkingDirectory(d)) { if (client.makeDirectory(d)) { if (!client.changeWorkingDirectory(d)) { log.error("切换目录失败!"); return result; } } else { log.error("创建目录失败!"); return result; } } } } } fileName = new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET); result = client.storeFile(fileName, fis); } catch (IOException e) { log.error(e); throw new RuntimeException("FTP客户端出错!", e); } finally { IOUtils.closeQuietly(fis); returnObject(client); } return result; }