Facing ‘Out of Memory’ exceptions when converting TIFF files to PDF using Aspose.Pdf, even after implementing image optimization and resource management.
internal void images(string _imageFile, string pdfFileName)
{
string tempFile = string.Empty;
using (Aspose.Pdf.Document _pdf = new Aspose.Pdf.Document())
{
Aspose.Pdf.Image image = null;
MemoryStream ms = new MemoryStream();
System.Drawing.Image frameOrImage = System.Drawing.Image.FromFile(_imageFile);
Aspose.Pdf.Page page = _pdf.Pages.Add();
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;
try
{
double fixHeight;
double fixWidht;
GetConversionSize(frameOrImage, out fixHeight, out fixWidht);
double height = fixHeight;
double width = fixWidht;
image = new Aspose.Pdf.Image
{
FixHeight = height * 72,
FixWidth = width * 72
};
page.PageInfo.Height = height * 72;
page.PageInfo.Width = width * 72;
// Set is B&W based on pixel format and override
bool isBlackAndWhite = frameOrImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format1bppIndexed;
image.IsBlackWhite = isBlackAndWhite;
//Add to PDF
frameOrImage.Save(ms, ImageFormat.Jpeg);
//_app.Log("Save frame Or image");
image.ImageStream = ms;
//_app.Log("Image Stream");
page.Paragraphs.Add(image);
Aspose.Pdf.PdfFormat pdfformat = (Aspose.Pdf.PdfFormat)Enum.Parse(typeof(Aspose.Pdf.PdfFormat), Config.GetInstance().PdfConversionSetting.Format.ToString());
tempFile = Path.GetTempFileName();
_pdf.Optimize();
_pdf.Save(tempFile);
_pdf.FreeMemory();
using (Aspose.Pdf.Document document = new Aspose.Pdf.Document(tempFile))
{
_app.Log("Before OptimizationOptions");
document.OptimizeResources(new Aspose.Pdf.Document.OptimizationOptions()
{
LinkDuplcateStreams = true,
RemoveUnusedObjects = true,
RemoveUnusedStreams = true,
CompressImages = true,
ImageQuality = Config.GetInstance().PdfConversionSetting.ImageQuality
});
document.Save(pdfFileName);
document.FreeMemory();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
frameOrImage.Dispose();
_pdf.Dispose();
ms.Dispose();
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
}