SpringBoot之图片转PDF

945 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

我之前有一个需求需要把图片转变成PDF 而在我苦思冥想之下终于找到了一个简单的办法去实现他 故记录下来 话不多说 下面正式进入主题

首先你总要新建一个项目吧 然后导入itextpdf依赖 这个东西主要是用来把图片 文档等东西转换成pdf的特别好用 在这里我只用它把图片转换成PDF 至于读者想实现其它的 请私信我 帮你解决 在此就不多赘述了

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>

导入依赖之后 然后就开始写一个类去实现它

首先我们需要先创建一个Document实例对象 创建对象的时候可以设置pdf的页边距来创建 如果不使用的话就是默认边距 在这里我为了让读者更清晰 所以使用了设置他的上下左右的页边距

//源码为 public Document(com.itextpdf.text.Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom) { /* compiled code */ }

Document doc = new Document(PageSize.A4, 20, 20, 20, 20);

然后我们再获取一个PdfWriter对象去创建一个PDF输出流和设置pdf的文件名

PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName+"\"+"beatiful"+".pdf"));

然后便开始去逐张去把图片设置参数和比例去添加进pdf文档里 具体代码如下

   /**
     * imageUrllist:图片路径集合,
     * mOutputPdfFileName:pdf输出位置
     * @param imageUrllist
     * @param mOutputPdfFileName
     * @return
     */
    public static File imageToPdf(List<String> imageUrllist, String mOutputPdfFileName) {

        String TAG = "PdfManager";
        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);


        try {
            PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName+"\"+"beatiful"+".pdf"));
            doc.open();
            for (int i = 0; i < imageUrllist.size(); i++) {
                doc.newPage();
//                doc.add(new Paragraph("简单使用iText"));
                Image png1 = Image.getInstance(imageUrllist.get(i));
                float heigth = png1.getHeight();
                float width = png1.getWidth();
                int percent = getPercent2(heigth, width);
                png1.setAlignment(Image.MIDDLE);
                png1.scalePercent(percent+3);// 表示是原来图像的比例;
                doc.add(png1);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            doc.close();

        }
        File mOutputPdfFile = new File(mOutputPdfFileName);
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile;
    }
    

private static int getPercent2(float h, float w) {
    int p = 0;
    float p2 = 0.0f;
    p2 = 530 / w * 100;
    p = Math.round(p2);
    return p;
}
    

最后便把图片转换成了PDF 其中参数为List是可以传入多张图片的地址来合成同一张PDF文件 也可以重复调用这个方法生成多张PDF