文件流操作&pdf合并
1.根据文件的url路径, 输出到本地文件夹
private String getProxyLabelPdfPath(String urlStr) { String proxyLabelPdfPath = null; InputStream inputStream = null; FileOutputStream fos = null; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(5 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 String fileName = "订单标签" + System.currentTimeMillis() + ".pdf"; String filePath = pdfTempPath + fileName; File saveDir = new File(pdfTempPath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); fos = new FileOutputStream(file); fos.write(getData); proxyLabelPdfPath = filePath; System.out.println("info:" + url + " download success"); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } return proxyLabelPdfPath; }
/** * 从输入流中获取字节数组 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { bos.close(); } } return bos.toByteArray(); }
2.将本地文件以文件流方式输出 //合并成一个文件后以文件流方式输出
if (org.apache.commons.lang3.StringUtils.isNotBlank(totalPdfPath)) { OutputStream os = null; try { File file = new File(totalPdfPath); String filename = file.getName(); InputStream fis = new BufferedInputStream(new FileInputStream(totalPdfPath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名 response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")); response.addHeader("Content-Length", "" + file.length()); os = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); os.write(buffer);// 输出文件 os.flush(); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (os != null) { os.close(); } } }
3.合并pdf
public String mergeLabelPdfs(String[] pdfs, String servletContextRealPath) throws Exception { Integer month = Calendar.getInstance().get(Calendar.MONTH) + 1; String timestamp = String.valueOf(new Date().getTime()); // 合并PDF //String storeDir = servletContextRealPath.replaceAll("\\\\", "/") + month; String totalPdfPath = servletContextRealPath + month + "/" + timestamp + ".pdf"; File saveDir = new File(servletContextRealPath + month); if(!saveDir.exists()){ saveDir.mkdir(); } logger.debug("storeDirUrl={}", totalPdfPath); PdfUtils.mergePdfFiles(pdfs, totalPdfPath); return totalPdfPath; }
/** * @param files 要合并的PDF文件路径数组 * @param newfile 合并后的文件路径 * @return * @throws Exception */ public static boolean mergePdfFiles(String[] files, String newfile) throws Exception { boolean retValue = false; Document document = null; try { // 获得Document document = new Document(new PdfReader(files[0]).getPageSize(1)); // 通过document 和 保存路径构建PDF copy 对象 PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile)); document.open(); // 遍历文件 for (int i = 0; i < files.length; i++) { // 每个pdf文件依次生成PdfReader对象 PdfReader reader = new PdfReader(files[i]); int n = reader.getNumberOfPages(); for (int j = 1; j <= n; j++) { // 新的一页 document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } } retValue = true; } catch (Exception e) { throw e; } finally { if (document != null) { document.close(); } } return retValue; }