PDF转换成图片

需求:公司现在有个将PDF文件转换成.tif格式的图片,然后利用FTP上传到服务器。

所需jar:PDFRenderer-0.9.1.jar

下面代码是将PDF文件转换成.tif格式

package com.xu.test;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class PDFchangToImage {
	
	public static void main(String[] args) {
		
		PDFchangToImage.changePdfToImg();
		
	}

	public static void changePdfToImg() {

		try {
			File file = new File("D:\\LT000091209.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);	//加载pdf文件
			for (int i = 1; i <= pdffile.getNumPages(); i++) {
				PDFPage page = pdffile.getPage(i);	//获取PDF第几页
				Rectangle rect = new Rectangle(70, -20, ((int) 320),((int) page.getBBox().getHeight()));
				int w = 3;	//设置图片的宽放大多少倍
				int h = 3;  //设置图片的高放大多少倍
				Image img = page.getImage(rect.width * w, rect.height * h,
						rect, 
						null, // null for the ImageObserver
						true, // fill background with white
						true // block until drawing is done
						);
				BufferedImage tag = new BufferedImage(rect.width * w,rect.height * h, BufferedImage.TYPE_BYTE_GRAY);
				tag.getGraphics().drawImage(img, 0, 0, rect.width * w,rect.height * h, null);
				FileOutputStream out = new FileOutputStream("D:\\" + i+ ".tif"); // 输出到文件流
				JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
				JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
				param.setQuality(1f, false);// 1f是提高生成的图片质量 0-1之间
				encoder.setJPEGEncodeParam(param);
				encoder.encode(tag); // JPEG编码
				out.flush();
				out.close();
			}
			channel.close();
			raf.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值