Convert HTML to PDF with Aspose.Java - Automatic resize images wich not fit inside pdf

Dear Support Team,

I have a similar problem as in this topic:

When I convert an HTML file to a PDF, it seems that the images are not resized to the correct PDF page size and just get cut off, if they are too large.

Are there any solutions in the meantime?

With kind regards

Version

  • com.Aspose.aspose-java:21.9
  • JDK 13

Example project

mvn_html_to_pdf.zip (2.0 MB)

@bennetpe There is no way to scale the images automatically upon loading document. However, you can easily do this in your code. For example see the following code:

Document doc = new Document("C:\\Temp\\test.html");

// Get all shapes in the document.
Iterable<Shape> shapes = doc.getChildNodes(NodeType.SHAPE, true);
for (Shape s : shapes)
{
    Section parentSection = (Section)s.getAncestor(NodeType.SECTION);
    PageSetup ps = parentSection.getPageSetup();
    double maxWidth = ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin();

    double scaleFactor = maxWidth / s.getWidth();
    if (scaleFactor < 1)
    {
        s.setAspectRatioLocked(true);
        s.setWidth(s.getWidth() * scaleFactor);
    }
}

doc.save("C:\\Temp\\out.pdf");

@alexey.noskov
This works fine for me, thanks for the quick reply.

1 Like