Java使用aspose把PDF文件转换成PNG文件,以及把PDF文件水印转换成PNG格式

2021-08-03 00:00:00 文件 水印 转换成

Java代码把PDF文件转换成PNG文件

需要引用aspose包,引入操作我写了一个博客,地址如下

https://blog.csdn.net/weixin_46713508/article/details/125495770?spm=1001.2014.3001.5502

直接上代码了

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>aspose-word-excel</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--word文件转PDF以及水印-->
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.pdf.free</artifactId>
            <version>3.9.0</version>
        </dependency>
        <!--解析word时用到的包-->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>compile</scope>
        </dependency>
        <!--Aspose相关依赖 需要在本地指定导入-->
        <dependency>
            <groupId>com.aspose.words</groupId>
            <artifactId>aspose-words</artifactId>
            <version>words-15.8.0-jdk16</version>
            <scope>system</scope>
            <systemPath>${ project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose.cells</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>cell-8.5.2</version>
            <scope>system</scope>
            <systemPath>${ project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose.pdf</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>pdf-17.3.0</version>
            <scope>system</scope>
            <systemPath>${ project.basedir}/src/main/resources/lib/aspose.pdf-17.3.0.jar</systemPath>
        </dependency>
        <!--文件上传-->

        <!--骑缝章相关依赖-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.13</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
            <version>2.0.1</version>
        </dependency>

    </dependencies>
    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>

</project>

license.xml

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  </Data>
  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
   /** * 获取license * * @return */
    public static boolean getLicense() { 
        boolean result = false;
        try { 
            InputStream is = ConvertPDFUtils.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return result;
    }
	//pdf转换png
  public boolean pngConvertPdf(MultipartFile file, String outPath) throws Exception { 
        // 验证License
        if (!ConvertPDFUtils.getLicense()) { 
            return false;
        }
        try { 
            Document pdfDocument = new Document(file.getInputStream());
            Resolution resolution = new Resolution(960);;
            PngDevice pngDevice = new PngDevice(resolution);
            for (int index = 1; index <= pdfDocument.getPages().size(); index++) { 
                // 输出路径
                File fileInfo = new File(outPath);
                FileOutputStream fileOs = new FileOutputStream(fileInfo);
                pngDevice.process(pdfDocument.getPages().get_Item(index), fileOs);
                fileOs.close();
            }
            return true;
        } catch (Exception e) { 
            e.printStackTrace();
            return false;
        }
    }
  public static void main(String[] args) { 
        String sourcePath = "D:\\File\\test.pdf";
        String targetPath = "D:\\File\\";
        long old = System.currentTimeMillis();
        ConvertPDFUtils.pdfToImage(sourcePath, targetPath);
        long now = System.currentTimeMillis();
        System.out.println("pdf转图片成功,共耗时:" + ((now - old) / 1000.0) + "秒");

    }

PDF文件水印转换成PNG格式

    /** * @param sourceFile 需要重新重命名的图片路径 * @param targetPath 重命名的图片路径保存地址 */
    public static void fileCopyRightWay(String sourceFile, String targetPath) { 
        try { 
            //读取源地址文件的字节流
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(targetPath);
            byte[] bs = new byte[1026];
            int count = 0;
            while ((count = in.read(bs, 0, bs.length)) != -1) { 
                //把读取到的字节流写入到目的地址的文件里面
                out.write(bs, 0, count);
            }
            //刷新下输出流
            out.flush();
            // 关闭输入流和输出流
            out.close();
            out.close();
        } catch (FileNotFoundException e) { 
            e.printStackTrace();
        } catch (IOException e) { 
            e.printStackTrace();
        }
    }
public static void main(String[] args) throws IOException { 
        String sourcePath = "D:\\file\\体重变化图表.pdf";
        String targetPath = "D:\\file\\";
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(sourcePath);
        //添加一个空白页,目的为了删除jar包添加的水印,后面再移除这一页
        pdf.getPages().add();
        PdfReader reader = new PdfReader(sourcePath);
        BufferedImage image;
        int total1 = reader.getNumberOfPages();
        for(int i =0 ; i<total1;i++){ 
            image = pdf.saveAsImage(i);//将每一页pdf拆分出来保存为图片
            File file = new File(String.format(targetPath+"Watermark33"+i+".png",i));
            ImageIO.write(image,"PNG",file);
            ConvertPDFUtils.fileCopyRightWay(targetPath+"Watermark33"+i+".png",targetPath+"测试3_"+i+".png");//对图片进行重命名
        }
        pdf.getPages().remove(pdf.getPages().get(pdf.getPages().getCount()-1));
        pdf.close();

    }

意思代码可能不全 下面是全部工具类代码

package dmyz.util;

import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import com.aspose.pdf.*;
import com.aspose.pdf.devices.JpegDevice;
import com.aspose.pdf.devices.PngDevice;
import com.aspose.pdf.devices.Resolution;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class ConvertPDFUtils { 
    /** * 获取license * * @return */
    public static boolean getLicense() { 
        boolean result = false;
        try { 
            InputStream is = ConvertPDFUtils.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return result;
    }

    /** * 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br> * * @param excelfilePath [原始excel路径] * @param pdfFilePath [输出路径] */

    public static Boolean excelConvertToPdf(String excelfilePath, String pdfFilePath) { 
        // 验证License
        if (!getLicense()) { 
            return false;
        }

        try { 
            // 原始excel路径
            Workbook wb = new Workbook(excelfilePath);
            // 输出路径
            File pdfFile = new File(pdfFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            wb.save(fileOS, SaveFormat.PDF);
            return true;
        } catch (Exception e) { 
            e.printStackTrace();
            return false;
        }
    }

    /** * 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br> * * @param wordfilePath [原始excel路径] * @param pdfFilePath [输出路径] */
    public static Boolean wordConvertToPdf(String wordfilePath, String pdfFilePath) { 
        // 验证License
        if (!getLicense()) { 
            return false;
        }

        try { 
            // 原始word路径
            Document doc = new Document(wordfilePath);
            // 输出路径
            File pdfFile = new File(pdfFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            doc.save(fileOS,SaveFormat.PDF);
            return true;
        } catch (Exception e) { 
            e.printStackTrace();
            return false;
        }
    }

    /** * 将pdf转图片 * * @param inputStream pdf源文件流 * @param imgFilePath 转成一张图片文件全路径 例如 "D:\\home\\qq.png" */
    public static void pdfToImage(InputStream inputStream, String imgFilePath) { 
        try { 
            System.out.println("convert pdf2jpg begin");
            long old = System.currentTimeMillis();
            if (!getLicense()) { 
                return;
            }
            Document pdfDocument = new Document(inputStream);
            //分辨率
            Resolution resolution = new Resolution(130);
            JpegDevice jpegDevice = new JpegDevice(resolution);
            List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            List<File> fileList = new ArrayList<File>();
            for (int index = 1; index <= pdfDocument.getPages().size(); index++) { 
                File file = File.createTempFile("tempFile", "png");
                FileOutputStream fileOS = new FileOutputStream(file);
                jpegDevice.process(pdfDocument.getPages().get_Item(index), fileOS);
                fileOS.close();
                imageList.add(ImageIO.read(file));
                fileList.add(file);
            }
            //临时文件删除
            BufferedImage mergeImage = mergeImage(false, imageList);
            ImageIO.write(mergeImage, "png", new File(imgFilePath));
            long now = System.currentTimeMillis();
            System.out.println("convert pdf2jpg completed, elapsed :" + ((now - old) / 1000.0) + "秒");
            //删除临时文件
            for (File f : fileList) { 
                if (f.exists()) { 
                    f.delete();
                }
            }
        } catch (Exception e) { 
            e.printStackTrace();
        }

    }

    /** * 合并任数量的图片成一张图片 * * @param isHorizontal true代表水平合并,fasle代表垂直合并 * @param imgs 待合并的图片数组 * @return * @throws IOException */
    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException { 
        // 生成新图片
        BufferedImage destImage = null;
        // 计算新图片的长和高
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
        // 获取总长、总宽、最长、最宽
        for (int i = 0; i < imgs.size(); i++) { 
            BufferedImage img = imgs.get(i);
            allw += img.getWidth();

            if (imgs.size() != i + 1) { 
                allh += img.getHeight() + 5;
            } else { 
                allh += img.getHeight();
            }


            if (img.getWidth() > allwMax) { 
                allwMax = img.getWidth();
            }
            if (img.getHeight() > allhMax) { 
                allhMax = img.getHeight();
            }
        }
        // 创建新图片
        if (isHorizontal) { 
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else { 
            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D g2 = (Graphics2D) destImage.getGraphics();
        g2.setBackground(Color.LIGHT_GRAY);
        g2.clearRect(0, 0, allw, allh);
        g2.setPaint(Color.RED);

        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (int i = 0; i < imgs.size(); i++) { 
            BufferedImage img = imgs.get(i);
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            // 逐行扫描图像中各个像素的RGB到数组中
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
            if (isHorizontal) { 
                // 水平方向合并
                // 设置上半部分或左半部分的RGB
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1);
            } else { 
                // 垂直方向合并
                // 设置上半部分或左半部分的RGB
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1);
            }
            wx += w1;
            wy += h1 + 5;
        }


        return destImage;
    }

    /** * pfd转图片 * * @param pdf 源文件全路径 * @param outPath 转后的文件夹路径 */
    public static void pdfToImage(String pdf, String outPath) { 
        // 验证License
        if (!getLicense()) { 
            return;
        }

        try { 
            long old = System.currentTimeMillis();
            System.out.println("convert pdf2png begin");
            Document pdfDocument = new Document(pdf);
            //图片宽度:800
            //图片高度:100
            // 分辨率 960
            //Quality [0-100] 最大100
            //例: new JpegDevice(800, 1000, resolution, 90);
            Resolution resolution = new Resolution(960);
// JpegDevice jpegDevice = new JpegDevice(resolution);
            PngDevice pngDevice = new PngDevice(resolution);
            for (int index = 1; index <= pdfDocument.getPages().size(); index++) { 
                // 输出路径
                File file = new File(outPath + "/" + index + ".png");
                FileOutputStream fileOs = new FileOutputStream(file);
// jpegDevice.process(pdfDocument.getPages().get_Item(index), fileOs);
                pngDevice.process(pdfDocument.getPages().get_Item(index), fileOs);
                fileOs.close();
            }

            long now = System.currentTimeMillis();
            System.out.println("convert pdf2png completed, elapsed :" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) { 
            e.printStackTrace();
        }

    }

    /** * @param page 要添加水印的页面 * @param imageFile 水印图片路径 */
    public static void AddImageWatermark(PdfPageBase page, String imageFile) { 
        page.setBackgroundImage(imageFile);
        Rectangle2D rect = new Rectangle2D.Float();
        rect.setFrame(page.getClientSize().getWidth() / 2 - 100, page.getClientSize().getHeight() / 2 - 100, 200, 200);
        page.setBackgroundRegion(rect);
    }

    /** * @param page 要添加水印的页面 * @param textWatermark 水印文字 */
    public static void AddTextWatermark(PdfPageBase page, String textWatermark) { 
        Dimension2D dimension2D = new Dimension();
        dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 3, page.getCanvas().getClientSize().getHeight() / 3);
        PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
        brush.getGraphics().setTransparency(0.3F);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
        brush.getGraphics().rotateTransform(-45);
        brush.getGraphics().drawString(textWatermark, new PdfTrueTypeFont(new Font("新宋体", Font.PLAIN, 30), true), PdfBrushes.getGray(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
        brush.getGraphics().restore();
        brush.getGraphics().setTransparency(1);
        Rectangle2D loRect = new Rectangle2D.Float();
        loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
        page.getCanvas().drawRectangle(brush, loRect);
    }

    /** * @param sourceFile 需要重新重命名的图片路径 * @param targetPath 重命名的图片路径保存地址 */
    public static void fileCopyRightWay(String sourceFile, String targetPath) { 
        try { 
            //读取源地址文件的字节流
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(targetPath);
            byte[] bs = new byte[1026];
            int count = 0;
            while ((count = in.read(bs, 0, bs.length)) != -1) { 
                //把读取到的字节流写入到目的地址的文件里面
                out.write(bs, 0, count);
            }
            //刷新下输出流
            out.flush();
            // 关闭输入流和输出流
            out.close();
            out.close();
        } catch (FileNotFoundException e) { 
            e.printStackTrace();
        } catch (IOException e) { 
            e.printStackTrace();
        }
    }


    /** * 添加水印 * * @param filepath [文件路径] * @param data [水印文字内容] */
    public static void addWatermark(String filepath, String data) { 

        Document pdfDocument = new Document(filepath);
        TextStamp textStamp = new TextStamp(data);
        textStamp.setBackground(true);
        textStamp.setXIndent(100);
        textStamp.setYIndent(100);
        textStamp.setRotateAngle(50);

        textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
        textStamp.getTextState().setFontSize(34.0F);
        textStamp.getTextState().setFontStyle(FontStyles.Italic);
// textStamp.getTextState().setForegroundColor(Color.getLightGray());

        TextStamp textStamp1 = new TextStamp(data);
        textStamp1.setBackground(true);
        textStamp1.setXIndent(300);//设置位置
        textStamp1.setYIndent(300);
        textStamp1.setRotateAngle(50);//设置旋转角度
        textStamp1.getTextState().setFont(FontRepository.findFont("Arial"));
        textStamp1.getTextState().setFontSize(34.0F);//设置字体大小
        textStamp1.getTextState().setFontStyle(FontStyles.Italic);
// textStamp1.getTextState().setForegroundColor(Color.LIGHT_GRAY);//设置字体颜色

        TextStamp textStamp2 = new TextStamp(data);
        textStamp2.setBackground(true);
        textStamp2.setXIndent(500);
        textStamp2.setYIndent(500);
        textStamp2.setRotateAngle(50);
        textStamp2.getTextState().setFont(FontRepository.findFont("Arial"));
        textStamp2.getTextState().setFontSize(34.0F);
        textStamp2.getTextState().setFontStyle(FontStyles.Italic);
// textStamp2.getTextState().setForegroundColor(Color.getLightGray());


        PageCollection pages = pdfDocument.getPages();
        int size = pages.size();
        for (int i = 1; i <= size; i++) { 
            pages.get_Item(i).addStamp(textStamp);
            pages.get_Item(i).addStamp(textStamp1);
            pages.get_Item(i).addStamp(textStamp2);
        }
        pdfDocument.save(filepath);
    }
    public static void addWatermarkWYH(String filepath, String data) { 
        Document pdfDocument = new Document(filepath);
        TextStamp textStamp = new TextStamp(data);
        //背景(好像没用)
        textStamp.setBackground(true);
        //x坐标 可以通过xy坐标来定义水印的具体位置
        textStamp.setXIndent(100);
        //y坐标
        textStamp.setYIndent(10);
        //通过以下属性控制水印的样式 字体 大小 颜色等
        //旋转角度
        textStamp.setRotateAngle(0);
        //字体类型
        textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
        //字体大小
        textStamp.getTextState().setFontSize(20.0F);
        //字体样式
        textStamp.getTextState().setFontStyle(FontStyles.Italic);
        //字体颜色
        textStamp.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.yellow));

        TextStamp textStamp1 = new TextStamp(data);
        textStamp1.setBackground(true);
        textStamp1.setXIndent(200);//设置位置
        textStamp1.setYIndent(10);
        textStamp1.setRotateAngle(0);//设置旋转角度
        textStamp1.getTextState().setFont(FontRepository.findFont("Arial"));
        textStamp1.getTextState().setFontSize(30.0F);//设置字体大小
        textStamp1.getTextState().setFontStyle(FontStyles.Italic);
        textStamp1.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.green));


        TextStamp textStamp2 = new TextStamp(data);
        textStamp2.setBackground(true);
        textStamp2.setXIndent(300);
        textStamp2.setYIndent(10);
        textStamp2.setRotateAngle(0);
        textStamp2.getTextState().setFont(FontRepository.findFont("Arial"));
        textStamp2.getTextState().setFontSize(40.0F);
        textStamp2.getTextState().setFontStyle(FontStyles.Italic);
        textStamp2.getTextState().setForegroundColor(com.aspose.pdf.Color.fromRgb(Color.red));
        PageCollection pages = pdfDocument.getPages();
        System.out.println(pages);
        int size = pages.size();
        for (int i = 1; i <= size; i++) { 
            //如果只想要一个水印 只添加一个即可
            pages.get_Item(i).addStamp(textStamp);
            pages.get_Item(i).addStamp(textStamp1);
            pages.get_Item(i).addStamp(textStamp2);
        }
        pdfDocument.save(filepath);
    }

    //word->pdf
    public static boolean docToPdf(String inPath, String outPath) { 
        if (!getLicense()) {  // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        FileOutputStream os = null;
        try { 
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) { 
            e.printStackTrace();
            return false;
        }finally { 
            if (os != null) { 
                try { 
                    os.flush();
                    os.close();
                } catch (IOException e) { 
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

}

    原文作者:不允许摆烂
    原文地址: https://blog.csdn.net/weixin_46713508/article/details/125502904
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章