Resize Width Height of Large Images in MSG to Fit within the Page Bounds of Converted PDF File (Java)

Image got truncated from right side. we had converting the html file to pdf file.
I’m attaching the html file and converted pdf file.tarun.srivastava@genpact.digital_27-11-2020_07-18-20.pdf (175.5 KB)FW_ Issue 704.zip (252.9 KB)

sample code:

private void removeAttachmentAndConvertEmlOrMsgFile(int asposeFormat, InputStream docInputStream, OutputStream os,
		ByteArrayInputStream licenseFS, String timezone) throws Exception {
		MailMessage mailMsg;
		ByteArrayOutputStream arrayOutputStream = null;
		MhtSaveOptions saveOptions;
		com.aspose.email.License emailLicense = new com.aspose.email.License();
		emailLicense.setLicense(licenseFS);
		mailMsg = MailMessage.load(docInputStream, new EmlLoadOptions());
		arrayOutputStream = new ByteArrayOutputStream();
		saveOptions = SaveOptions.getDefaultMhtml();
		saveOptions.setSaveAttachments(true);
		AttachmentCollection attachmentCollection = mailMsg.getAttachments();
		if (attachmentCollection != null) {
			int size = attachmentCollection.size();
			for (int i = 0; i < size; i++) {
				Attachment att = attachmentCollection.get_Item(i);
				String attFileName = att.getName().replace(":", " ").replace("\\", " ").replace("/", " ")
						.replace("?", "").replace(">", "").replace("<", "").replace("|", "");
				att.setName(attFileName);
				att.setContentStream(new ByteArrayInputStream("".getBytes()));
			}
		}
		mailMsg.setTimeZoneOffset(TimeZone.getTimeZone(timezone).getOffset(mailMsg.getDate().getTime()));
		mailMsg.save(arrayOutputStream, saveOptions);
		wordLicense(getLicense());
		ByteArrayInputStream bis = new ByteArrayInputStream(arrayOutputStream.toByteArray());
		com.aspose.words.LoadOptions loadOptions = new com.aspose.words.LoadOptions();
		loadOptions.setLoadFormat(com.aspose.words.LoadFormat.MHTML);
		com.aspose.words.PdfSaveOptions pso = new PdfSaveOptions();
		pso.setJpegQuality(70);
		Document doc = new Document(bis, loadOptions);
		
		// make inline image resize
		@SuppressWarnings("rawtypes")
		NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
		int imageIndex = 0;
		for (Shape shape : (Iterable<Shape>) shapes)
		{
		    if (shape.hasImage() && (shape.getWidth() > 700 || shape.getHeight() > 900))
		    {
		    	double largeDim= shape.getWidth() > shape.getHeight()? shape.getWidth(): shape.getHeight();
		    	double q= shape.getWidth() > shape.getHeight()? 700: 900;
		    	double divExp= q/largeDim;
		        String imageFileName = MessageFormat.format(
		                "Aspose.Images.{0}{1}", imageIndex, com.aspose.words.FileFormatUtil.imageTypeToExtension(shape.getImageData()
		                                .getImageType()));
		        shape.setWidth(shape.getWidth()*divExp);
		        shape.setHeight(shape.getHeight()*divExp);

		        shape.getImageData().save(imageFileName);
		        imageIndex++;
		    }
		}

		doc.save(os, pso);
		//doc.save(os, com.aspose.words.SaveFormat.PDF);
	}

@ashishyadava

After working with sample code and source file provided by you, it seems to be an issue related to Aspose.Email while truncating the right side image when saving to MHTML. A ticket with ID EMAILJAVA-34784 has bee created to further investigate and resolve the issue.

You have shared MSG file where as you are using EmlLoadOptions(). You need to use MsgLoadOptions() for MSG file. Is this the case with you in another thread where you have reported InvalidOperation Exception issue?

Thanks for update. We are reading the outlook and process the eml file for conversion.
If I used below code than it’s correct right?
mailMsg = MailMessage.load(docInputStream, new EmlLoadOptions());

I have the eml file that causing the InvalidOperarion exception issue. If you want, I can share with you.docset_pvai_10378803.zip (34.4 KB)

@ashishyadava

There is no InvalidOperarion exception issue with the new file shared by you as well on our end. I have shared the output and used sample code with you for this in another thread as well where you have shared the same thing.

TestEmail.java.zip (2.1 KB)

Hi,

Can you provide any tentative date or ETA for issue EMAILJAVA-34784.

Thanks
Ashish

@ashishyadava

I regret to share that at present the issue is still unresolved and we request for your patience. We will share the good news with you as soon as the issue will be addressed.

Hi Team,

Any update on this ?

Regards
Ashish

@ashishyadava

From Aspose.Email perspective, this issue is not reproduced as API produced the same output as MS Outlook. If you can try the solution mentioned in following link for your convenience.

Please share the complete program with imported packages and confirm the aspose-word version.

Can you please try using the attached file on your end.
EmailToPDF.java.zip (1015 Bytes)

1 Like

Hi,

It’s still not working for right cut image issue. can you again cross check nd update?

I have updated below code: -

// make inline image resize
@SuppressWarnings(“rawtypes”)
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
int imageIndex = 0;
for (Shape shape : (Iterable) shapes)
{
if (shape.hasImage())
{
LOG.error("shape image "+shape);
// Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
PageSetup ps = shape.getParentParagraph().getParentSection().getPageSetup();
double freePageWidth = shape.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
double freePageHeight = shape.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();

	        ImageSize size = shape.getImageData().getImageSize();
	        Boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight
	            || shape.getWidth() > freePageWidth || shape.getHeight() > freePageHeight;

	        if (exceedsMaxPageSize)
	        {
	            // Set the new size.
	        	LOG.error("exceedsMaxPageSize" +exceedsMaxPageSize);
	        	shape.setAspectRatioLocked(true);
	        	shape.setWidth(ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin());
	        }
	    }
	        String imageFileName = MessageFormat.format(
	                "Aspose.Images.{0}{1}", imageIndex, com.aspose.words.FileFormatUtil.imageTypeToExtension(shape.getImageData()
	                                .getImageType()));
	        LOG.error("imageFileName "+imageFileName);
	        shape.getImageData().save(imageFileName);
	        imageIndex++;
	    }
	doc.save(os, pso);

Thanks
Ashish

@ashishyadava,

I have manually converted “FW_ Issue 704.msg” to MHT format by using MS Outlook 2019 and then converted this MHT to PDF format by using MS Word 2019 and attached the final PDF file here for your reference (see msw-2019.pdf (240.6 KB)). You can observe the same undesired behavior of image in MS Word’s generated PDF file. So, this is the expected behavior as Aspose.Words mimics the behavior of MS Word in this case.

But, you can workaround this issue by using the following code:

Document doc = new Document("C:\\Temp\\Aspose.Email generated.mht");

for (Shape shape : (Iterable<Shape>) doc.getChildNodes(NodeType.SHAPE, true)) {
    shape.setLeft(-55);
    resizeLargeImage(shape);
}

doc.save("C:\\Temp\\awjava-21.6.pdf");

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);
        image.setHeight(size.getHeightPoints() * ratio);
    }
}