tqt-java

word转PNG;pdf转PNG,及多张PNG合并

1.word转化为PNG

使用到 aspose.words

<!-- https://mvnrepository.com/artifact/com.aspose/aspose-words -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
        </dependency>  // 将word 转化为图片一张
    public static String parseFileToBase64_PNG(byte[] file, String fileName, String loginName) throws Exception {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(file);
        BufferedImage image = null;
        List<BufferedImage> bufferedImages = wordToImg(inputStream,loginName);
        image = mergeImage(false, bufferedImages);

        boolean png = ImageIO.write(image, "png", new File(fileName));// 写入流中

        if(png == false){
            return "转换失败";
        }
        //关闭流
        inputStream.close();
        return "转换成功";
    }



/**
     * @Description: word和txt文件转换图片
     */
    private static List<BufferedImage> wordToImg(InputStream inputStream, String loginName) throws Exception {
        if (!isWordLicense()) {
            return null;
        }
        try {

            Document doc = new Document(inputStream);
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
            options.setPrettyFormat(true);
            options.setUseAntiAliasing(true);
            options.setUseHighQualityRendering(true);
            int pageCount = doc.getPageCount();

            List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            for (int i = 0; i < pageCount; i++) {
                OutputStream output = new ByteArrayOutputStream();
                options.setPageIndex(i);

                doc.save(output, options);
                ImageInputStream imageInputStream = ImageIO.createImageInputStream(parse(output));
                BufferedImage image = ImageIO.read(imageInputStream);
                int width = image.getWidth();
                int height = image.getHeight();
                Graphics2D pen = image.createGraphics();
                pen.drawImage(image, 0, 0, width, height, null);
                pen.setColor(Color.GRAY);
                pen.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.1F));
                pen.rotate(Math.toRadians(30), (double) image.getWidth() / 2, (double) image.getHeight() / 2);
                // 设置画笔字体样式为微软雅黑,斜体,文字大小为20px
                pen.setFont(new Font("微软雅黑", Font.ITALIC, 30));
                int x = image.getWidth() / 3;
                int y = 50;
                int space = image.getHeight() / 50;
                for (int j = 0; j < space; j++) {
                    //如果最后一个坐标的y轴比height高,直接退出
                    if ((y + 50) > image.getHeight()) {
                        break;
                    }
                    //进行绘制
                    pen.drawString(loginName, x-200, y);
                    pen.drawString(loginName, x+50, y);
                    pen.drawString(loginName, x+300, y);
                    y += (3 * 50);
                }
                pen.dispose();
                imageList.add(image);
            }
            return imageList;

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

/**
     * 合并任数量的图片成一张图片
     *
     * @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() + 2;
            } 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];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }

            wx += w1;
            wy += h1 + 2;
        }
        return destImage;
    }
/**
 * @Description: 验证aspose.word组件是否授权:无授权的文件有水印和试用标记,以下license亲测可用,去除水印
 */
public static boolean isWordLicense() { boolean result = false; try { // InputStream inputStream = new // FileInputStream("D:\\Workspaces\\TestFilters\\lib\\license.xml"); // 避免文件遗漏 String licensexml = "<License>\n" + " <Data>\n" + " <Products>\n" + " <Product>Aspose.Total for Java</Product>\n" + " <Product>Aspose.Words for Java</Product>\n" + " </Products>\n" + " <EditionType>Enterprise</EditionType>\n" + " <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" + " <LicenseExpiry>20991231</LicenseExpiry>\n" + " <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" + " </Data>\n" + " <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" + "</License>"; InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes()); com.aspose.words.License license = new com.aspose.words.License(); license.setLicense(inputStream); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }

 

 

2.PDF转化为PNG

  使用到pdfbox

<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>fontbox</artifactId>
   <version>2.0.9</version>
</dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.9</version>
</dependency>

 

   
/**
PDF转化为PNG
*/
public static boolean pdf2OnePng(byte[] file, String fileName) throws IOException {
        List<BufferedImage> bufferedImages = pdf2png(file);
        BufferedImage bufferedImage = mergeImage(false, bufferedImages);
        return ImageIO.write(bufferedImage, "png", new File(fileName));
    }

 public static List<BufferedImage> pdf2png(byte[] file) {
        List<BufferedImage> imgs = new ArrayList<>();
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                imgs.add(image);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgs;
    }

/**
     * 合并任数量的图片成一张图片
     *
     * @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() + 2;
            } 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];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }

            wx += w1;
            wy += h1 + 2;
        }
        return destImage;
    }

 

 

posted on 2022-07-19 14:18  TQT*  阅读(412)  评论(0)    收藏  举报

导航