Java将图片转化为PDF的方法(1)

  新接到一个任务,需要将原来的tif图片转为PDF存储,并且需要在适合的存储大小下保证PDF清晰度,经过整理,转换方法分为插件和无插件两类,

需要插件一般都借助adobe pdf,wps控件,ImageMagick软件等,因为项目需要跨平台,所以选择无插件方式,经过查阅资料,总结了三种:

1. 使用收费版的aspose.pdf, 功能很强大,提供了丰富API,包括PDF转换,合成,压缩等。

2. 使用开源的ITEXT,最新版本功能很完善,几乎满足所有日常需求推荐。

3. 使用Apache的pdfbox类库

  首先,使用aspose.pdf完成转换,代码如下:

import com.aspose.pdf.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class Convert2Pdf {
    //授权
    public static boolean getLicense() {
        try {
            String license2 = ""
                    + "  "
                    + "    "
                    + "      Aspose.Total for Java"
                    + "      Aspose.Words for Java"
                    + "    "
                    + "    Enterprise"
                    + "    20991231"
                    + "    20991231"
                    + "    8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7"
                    + "  "
                    + "  111"
                    + "";
            InputStream is2 = new ByteArrayInputStream(license2.getBytes("UTF-8"));
            License asposeLic2 = new License();
            asposeLic2.setLicense(is2);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void convert(String sourcePath, String targetPath) throws IOException {
        //创建文档
        Document doc = new Document();
        //新增一页
        Page page = doc.getPages().add();
        //设置页边距
        page.getPageInfo().getMargin().setBottom(0);
        page.getPageInfo().getMargin().setTop(0);
        page.getPageInfo().getMargin().setLeft(0);
        page.getPageInfo().getMargin().setRight(0);
        //创建图片对象
        Image image = new Image();
        BufferedImage bufferedImage = ImageIO.read(new File(sourcePath));
        //获取图片尺寸
        int height = bufferedImage.getHeight();
        int width = bufferedImage.getWidth();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "tif", baos);
        baos.flush();
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        image.setImageStream(bais);
        //设置pdf页的尺寸与图片一样
        page.getPageInfo().setHeight(height);
        page.getPageInfo().setWidth(width);
        //添加图片
        page.getParagraphs().add(image);
        //保存
        doc.save(targetPath, SaveFormat.Pdf);
    }
    public static void main(String[] args) {
        String source = "E:/SETUP/1.tif";
        String target = "E:/SETUP/1.pdf";
        if(getLicense()) {
            try {
                convert(source, target);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

你可能感兴趣的:(Java将图片转化为PDF的方法(1))