使用aspose.words在doc文档里面插入内容(文字或图片)

1.主要工作函数,先在doc文档里面插入书签,然后通过WordHandleContext方法将文档内容转成对象去获取Document节点,Document节点可以提取书签名和书签位置,从而在书签位置插入内容

    /**
     * 手动插入内容
     *
     * @param doc
     * @param pngPath
     * @throws Exception
     */
    public static void insertImageToPdf(Document doc, String pngPath) throws Exception {
        //设置宽高
        CombineImagesUtil tt = new CombineImagesUtil();
        BufferedImage top = tt.loadImageLocal(pngPath);
        if (top!=null){
            int width=top.getWidth()/2;
            int height=top.getHeight()/2;

            for (Bookmark bookmarks : doc.getRange().getBookmarks()) {
                if (bookmarks != null) {
                    switch (bookmarks.getName()) {
                        case "photo":
                            DocumentBuilder builder = new DocumentBuilder(doc);
                            File file = new File(pngPath);
                            if (file.exists()) {
                                //移动到书签位置
                                builder.moveToBookmark(bookmarks.getName());
                                //设置格式  WrapType.INLINE 参考:https://www.cnblogs.com/zhmlxx/p/14547931.html
                                builder.insertImage(pngPath, RelativeHorizontalPosition.DEFAULT, 1, RelativeVerticalPosition.MARGIN, 1, width, height, WrapType.INLINE);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }

 2.比较好用的工具,将图片转成BufferedImage对象可以更好的对图片进行修改

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d,int width,int height,int x ,int y) {

        try {
            Graphics2D graphics2D = d.createGraphics();
//            b.g
            graphics2D.drawImage(b, x, y, width, height, null);
            graphics2D.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return d;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "png", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值