希望插入大图,图片能够自适应word宽度且图片不要被裁剪

测试环境:tomcat8+jdk1.8+aspose-word.18.9版本
图片尺寸: 3840 * 2160
详细描述见附件:
aspose图片问题.zip (1.5 MB)

@vpsoft,

谢谢你的询问。 为确保及时准确的回复,请在此处附上以下资源进行测试:

  • 您输入的Word和图像文件。
  • 请附加显示不良行为的输出Word文件。
  • 请创建一个简单的Java应用程序(没有编译错误的源代码),它可以帮助我们在最后重现您的问题并将其附加到此处进行测试。

一旦您准备好这些信息,我们将立即开始调查您的问题,并为您提供更多信息。 谢谢你的合作。

PS:要附加这些资源,请压缩并上传。

导出后的文件:
空白文档-草稿(1.0).docx.zip (6.7 MB)

@vpsoft

感谢您分享细节。 下面的代码示例演示如何插入图像并设置其原始大小。 希望这对你有所帮助。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

//将文件或URL中的图像插入到文档中。 图像以内嵌和100%比例插入。
builder.insertImage(MyDir + "input.jpg");
builder.writeln();
Shape shape = builder.insertImage(MyDir + "input.jpg");
// 设置图像原始大小
shape.setWidth(shape.getImageData().getImageSize().getWidthPoints());
shape.setHeight(shape.getImageData().getImageSize().getHeightPoints());

doc.save(MyDir + "out.docx");

使用场景:
目前我们是通过直接插入html内容生成Word,内容中图片的src为一个URL地址,我们通过地址自动获取图片插入word文档。

问题:
1、插入后的图片,无法通过代码调整图片的高度和宽度来适应父元素(例如:body、td等)的高度和宽度。

要求:
1、希望插入图片后保存文档前通过代码调整超宽图片适应父元素的宽度。

@vpsoft

谢谢你的询问。 请使用以下代码根据页面大小调整图像大小。 您需要在保存文档之前使用此代码。 希望这对你有所帮助。

如果您仍然遇到问题,请在此处输入您的输入HTML,有问题的输出Word文档和预期输出Word文档,以供我们参考。 然后,我们将根据您的要求为您提供代码示例。

public static void resizeLargeImage(Shape image) throws Exception
{
    // Return if this shape is not an image.
    if (!image.hasImage())
        return;

    // Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
    PageSetup ps = image.getParentParagraph().getParentSection().getPageSetup();
    double freePageWidth = image.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
    double freePageHeight = image.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();

    // Is one of the sides of this image too big for the page?
    ImageSize size = image.getImageData().getImageSize();
    boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight;

    if (exceedsMaxPageSize)
    {
        // Calculate the ratio to fit the page size based on which side is longer.
        boolean widthLonger = (size.getWidthPoints() > size.getHeightPoints());
        double ratio = widthLonger ? freePageWidth / size.getWidthPoints() : freePageHeight / size.getHeightPoints();
        
        // Set the new size.
        image.setWidth(size.getWidthPoints() * ratio);
        if(!image.getAspectRatioLocked())
            image.setHeight(size.getWidthPoints() * ratio);
    }
}

Document doc = new Document(MyDir + "Input.docx");

//你的代码
//你的代码
for (Shape shape : (Iterable<Shape>)doc.getChildNodes(NodeType.SHAPE, true)) {
    if(shape.hasImage())
        resizeLargeImage(shape);
}

doc.save(MyDir + "out.docx");