Hi,
I’m using Aspose.PDF 24.1.0 to convert a JPG to a PDF file and have an issue where it loads/hangs forever.
Here is my sample code, using
Image2.jpg (651.4 KB)
// Set License
string licenseName = "Aspose.Total.NET.lic";
new License().SetLicense(licenseName);
// Test file paths
var jpgFilePath = @"C:\TestFiles\Image2.jpg";
var outputPath = @"C:\TestFiles\TestOutput.pdf";
using var document = new Document();
var documentsPages = document.Pages;
var newPage = documentsPages.Add();
var margin = 16.4; // This works fine if I use int 16 or 17 though
newPage.PageInfo.Margin = new MarginInfo(margin, margin, margin, margin);
using (var bitmap = new Bitmap(jpgFilePath))
{
newPage.Paragraphs.Add(new Image
{
File = jpgFilePath,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
ImageScale = GetImageDownScale(bitmap, newPage)
});
}
// This call hangs forever and valid pdf file is not created
document.Save(outputPath);
Console.WriteLine("Succesfully converted to pdf");
static double GetImageDownScale(System.Drawing.Image image, Page page)
{
// If the image has a bigger dimension then the page, we need to scale it down.
// https://forum.aspose.com/t/incorrect-aspect-ratio-when-adding-large-images-to-pdf/227538/2
// The way to calculate the image scale is to compare the vertical and horizontal scales to find the smaller one.
// The vertical scale is the "usable page width" (e.g. page with less horizontal margins) divided by the image width.
// The horizontal scale is the "usable page height" (e.g. page height less vertical margins) divided by the image height.
var pageInfo = page.PageInfo;
var pageMargin = pageInfo.Margin;
var minimumScale = Math.Min(
(pageInfo.Width - pageMargin.Left - pageMargin.Right) / image.Width,
(pageInfo.Height - pageMargin.Top - pageMargin.Bottom) / image.Height);
// If the minimum scale is larger than 1, that means the image is smaller than the page, there's no need to scale down.
return Math.Min(minimumScale, 1);
}
The code is adding margin to the page, and then scaling the image to fit inside that margin.
The issue happens when I set the PageInfo.Margin to a decimal value, eg 16.4. The call to Document.Save(outputPath) just hangs forever and the pdf document is not created.
Is there a reason that this code hangs forever and does not convert the image to a pdf?
Thanks,
Will