Java编程:将pdf文件转成图片并删除源文件

发表于:2010-1-05 10:10

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

#
java

  /**
  * 将pdf转成img
  */
  public static void changePdfToImg() {
  try {
  File file = new File("E:\\test\\baseInfo_2.pdf");
  RandomAccessFile raf = new RandomAccessFile(file, "r");
  FileChannel channel = raf.getChannel();
  MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
  PDFFile pdffile = new PDFFile(buf);
  for (int i = 1; i <= pdffile.getNumPages(); i++) {
  PDFPage page = pdffile.getPage(i);
  Rectangle rect = new Rectangle(0, 0, ((int) page.getBBox().getWidth()), ((int) page.getBBox().getHeight()));
  Image img = page.getImage(rect.width, rect.height, rect,
  null, // null for the ImageObserver
  true, // fill background with white
  true // block until drawing is done
  );
  BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
  tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, null);
  FileOutputStream out = new FileOutputStream("E:\\test\\img\\" + i + ".jpg"); // 输出到文件流
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);
  param2.setQuality(1f, false);// 1f是提高生成的图片质量
  encoder.setJPEGEncodeParam(param2);
  encoder.encode(tag); // JPEG编码
  out.close();
  }
  channel.close();
  raf.close();
  unmap(buf);//如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
  /**
  * 清空缓冲
  * @param buffer
  */
  public static void unmap(final Object buffer) {
  AccessController.doPrivileged(new PrivilegedAction() {
  public Object run() {
  try {
  Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
  getCleanerMethod.setAccessible(true);
  sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
  cleaner.clean();
  } catch (Exception e) {
  e.printStackTrace();
  }
  return null;
  }
  });
  }

《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号