java pdf转换为png图片(1)

注意:

更为优化的版本(实现多页pdf):https://blog.csdn.net/datouniao1/article/details/110866883

首先需要引入两个jar pdfbox.jar,fontbox.jar,并且使用jar的时候尽量使用高版本的。大家可以从这个路径来下载到这两个jar

https://download.csdn.net/download/datouniao1/10427502

下载了之后将这两个导入到我们的项目工程,下面就是我们的代码的处理的工作了,将pdf转换为图片:

/*
	 * *
	 * 实现pdf文件转换为png
	 * 参数是第一个是要转的转换的是pdffile
	 * 第二个参数是是要存储的png图片的路径
	 */
	public static void pdfFileToImage(File pdffile,String targetPath){
        try {
            FileInputStream instream = new FileInputStream(pdffile);
            InputStream byteInputStream=null;
            try {
                PDDocument doc = PDDocument.load(instream);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                if (pageCount > 0) {
                    BufferedImage image = renderer.renderImage(0, 2.0f);
                    image.flush();
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    ImageOutputStream imOut;
                    imOut = ImageIO.createImageOutputStream(bs);
                    ImageIO.write(image, "png", imOut);
                    byteInputStream = new ByteArrayInputStream(bs.toByteArray());
                    byteInputStream.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            File uploadFile = new File(targetPath);
            FileOutputStream fops;
            fops = new FileOutputStream(uploadFile);
            fops.write(readInputStream(byteInputStream));
            fops.flush();
            fops.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
	}
	
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

	public static void main(String[] args) {
		File file =new File("D:\\08\\ceshi.pdf");
		//上传的是png格式的图片结尾
		String targetfile="D:\\08\\wdg3.png";
		pdfFileToImage(file,targetfile);
	}

上面就可以将pdf文件转换为png图片了

到这个地方我就不多说了,希望对你有所帮助

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值