Convert images into pdf

Thanks Alexy,

We have a method to covert images into pdf. I have updated to the code according to Aspose.PDF version 24.1. Providing old code and modified code below. Please let me know if we can optimize the code further in any other easiest way as you did in the above case.

Code with Aspose.Pdf version 7.3

private static Stream ConvertImageToPdf(string fileName)
{
    Aspose.Pdf.Generator.ImageInfo imageInfo = new Aspose.Pdf.Generator.ImageInfo();
    // Aspose.Pdf.ImageInfo imageInfo = new Aspose.Pdf.ImageInfo();
    switch (Path.GetExtension(fileName).ToLower())
    {
        case ".jpg":
        case ".jpeg":
            imageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg;
            break;
        case ".bmp":
            imageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Bmp;
            break;
        case ".png":
            imageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Png;
            break;
        case ".tiff":
        case ".tif":
            imageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Tiff;
            break;
        default:
            imageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Unknown;
            break;
    }

    Stream pdfOutPutStream = null;
    try
    {
        pdfOutPutStream = PDFUtilities.CreateOutPDFStream(fileName);
        imageInfo.File = fileName;

        Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
        Aspose.Pdf.Generator.Section section = pdf.Sections.Add();

        Aspose.Pdf.Generator.Image image = new Aspose.Pdf.Generator.Image(section);

        image.ImageInfo = imageInfo;
        section.Paragraphs.Add(image);
        pdf.Save(pdfOutPutStream);
    }

Modified code with Aspose.PDF version 24.1

private static Stream ConvertImageToPdf(string fileName)
{
    Stream pdfOutPutStream = null;
    try
    {
        pdfOutPutStream = PDFUtilities.CreateOutPDFStream(fileName);
        Aspose.Pdf.Document pdf = new Aspose.Pdf.Document();
        Page section = pdf.Pages.Add();
        Image image = new Image();
        image.File = fileName;
        section.Paragraphs.Add(image);
        pdf.Save(pdfOutPutStream);
    }

@Febinbabu Since your question is related to Aspose.PDF, I have moved it into the appropriate forum. My colleagues from Aspose.PDF team will help you shortly.

Hi Team,

Need one more clarification.

In Aspose.PDF version 7.3, both Aspose.Pdf.Generate and Aspose.Pdf.Facade cantatins PageSize property.

Aspose.Pdf.Facades.PageSize
Aspose.Pdf.Generator.PageSize

After upgrading to verion 23.12 , PageSize is not there in the above 2 places, instead it is moved to Aspose.Pdf.PageSize.

  1. In our existing code, both Aspose.Pdf.Facades.PageSize and Aspose.Pdf.Generator.PageSize in many places.Can we replace both with Aspose.Pdf.PageSize?

  2. In PdfPageEditor, a property named pages were available in the aspose,pdf version 7.3. It is not available in 23.12 version. How can we re write the code according to Aspose.Pdf vrsion 23.12.

Providing the existing code with aspose.pdf version 7.3 is given below

public ActionStatus Resize(int[] pages, Aspose.Pdf.Facades.PageSize newPageSize)
{
using (var pdfInfo = new PdfFileInfo(this._fileName))
{
foreach (int page in pages)
{
if (page < 1 || page > pdfInfo.NumberOfPages)
{
return new ActionStatus(ErrorCodes.Error,
new InvalidOperationException(string.Format(“page’s value must be between 1 and {0}”,
pdfInfo.NumberOfPages)));
}
}
}
string tempFile = string.Empty;
using (var p = new PdfPageEditor())
{
try
{
tempFile = this._fileName.Insert(this._fileName.LastIndexOf(“.”), “_temp”);
if (FileUtility.FileInUse(_fileName))
return new ActionStatus(ErrorCodes.Error,
new InvalidOperationException(string.Format(“File ‘{0}’ is in use by another process”,
_fileName)));
File.Copy(this._fileName, tempFile);
//p = new PdfPageEditor();
p.BindPdf(tempFile);
p.PageSize = newPageSize;
p.Pages = pages;
p.Save(this._fileName);
}
catch (Exception ex)
{
return new ActionStatus(ErrorCodes.Error, ex);
}
finally
{
//p = null;
File.Delete(tempFile);
}
}
return new ActionStatus(ErrorCodes.NoError);
}

Hi Team,

Could you please provide me an update on the queries posted.

@Febinbabu

We are checking the case at the moment and will be writing you back shortly.

@Febinbabu

We have gone through the inquiries in this forum thread. Yes, the code snippet to convert an image into PDF is correct and optimized. You can keep using it in your project using the latest version of the API.

Furthermore, yes, you can use Aspose.Pdf.PageSize in the latest version of the API. About pages, all the PDF pages can be now accessed at Document level as new Aspose.Pdf API implements DOM approach. Below is a sample code example to access PDF pages and its different properties:

Document doc = new Document("Input.pdf");
foreach (Page page in doc.Pages)
{
 // Access page number and other properties
 var number = page.Number;
}

Please also check Working with Pages section in the API documentation and feel free to let us know in case you need further assistance.

Hi Asad,
Please clarify my below queries.

1. We were using below code with Aspose.Pdf version 7.3. After upgrading to Aspose 23.12, Aspose.Pdf.PageSize is a sealed class and can’t be inherited.
How to implement the same with Aspose.PDF.23.12?
public class PageSize : Aspose.Pdf.Generator.PageSize
{
public float Height { get; set; }
public virtual bool IsLandscape { get; set; }
public float Width { get; set; }

        public static readonly PageSize LEGAL_Landscape = new PageSize() { Width = Aspose.Pdf.Generator.PageSize.LegalWidth, Height = Aspose.Pdf.Generator.PageSize.LegalHeight, IsLandscape = true };
        public static readonly PageSize LETTER_Landscape = new PageSize() { Width = Aspose.Pdf.Generator.PageSize.LetterWidth, Height = Aspose.Pdf.Generator.PageSize.LetterHeight, IsLandscape = true };

        public PageSize() : base() { }

    }
  1. Below code is working fine with Aspose.PDF version 7.3. How do we re write the code with Aspose.PDF version 23.12?

Aspose.Pdf.Generator.TextInfo tinfo = new Aspose.Pdf.Generator.TextInfo { FontSize = 8, FontName = “Tahoma” };

Are these both properties same?

PdfPageEditor.Pages in Apose.Pdf 7.3 and PdfPageEditor.ProcessPages in Aspose.PDF 23.1

@Febinbabu

You would need to change your approach here. Instead of using your own extensions, you can use PageSize class directly as it contains all page sizes. Furthermore, you can set IsLandscape property on page level by Page.PageInfo.IsLandscape.

These settings can be accessed through TextState Class of TextFragment. e.g.

// Create text fragment
TextFragment textFragment1 = new TextFragment("Paragraph Text");

// Create text fragment
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment1.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.Blue;

We recommend that you use the latest (24.1) version of the API if you have already planned to upgrade. Furthermore, above method in the latest version is used to specify which pages should be processed by PdfPageEditor. If you do not specify them, all pages will be processed by default.

HI,

I have upgraded Aspose.PDF dll from version 7.3 to 23.1

Aspose.Pdf.Save method in version 23.1 not accepting stream as an input parameter
Issue.png (40.0 KB)

How to resolve this issue?

Facing issue with Concatenate() in the PdfFileEditor in Aspose.PDF 23.1

Code in the below screenshot works fine with version 7.3. How to rewrite it according to the 23.1 version
concatenate.png (20.9 KB)

How to merge files in different format (.docx,.html,.txt,.xlsx and image files) as a single pdf file by using aspose.pdf version 23.1?
requesting you to provide an example

@Febinbabu

First of all, we recommend that you use 24.12 version of the API that is the latest version. We tested in our environment and it is not creating any issues.

Please check below help articles for the code examples:

You will need to convert these files into PDF first and then merge all files using the approach shared above. You can use below API for conversion:

Also, we request you please create a sample console application if you face any issues and share that with us so that we can try to replicate in our environment and address it accordingly.

Hi Asad,
I tried merging an image and .docx file as a pdf file using aspose.pdf 24.12 with the below code. An empty page is getting added after the image in the generated pdf file. Providing the output file here
MergeDo4.pdf (91.4 KB)

. Could you please let me know how to remove the empty page.

public static void MergeDocuments(string[] files, string destinationFilePath)
{
License license = new License();
license.SetLicense(“C:\Users\666\source\repos\ConsoleApp1-Aspose23\ConsoleApp1-Aspose23\Aspose.Total.lic”);
using (Document pdfDocument = new Document())
{
foreach (string filePath in files)
{
string extension = Path.GetExtension(filePath).ToLower();
Page page = pdfDocument.Pages.Add();
switch (extension)
{
case “.jpg”:
AddImageToPdf(filePath, page);
break;
case “.docx”:
AddDocxToPdf(filePath, pdfDocument);
break;
}
}
pdfDocument.Save(destinationFilePath);
}

    }
    private static void AddImageToPdf(string filePath, Page page)
    {
        using (var imagestream = new FileStream(filePath, FileMode.Open))
        {
            page.AddImage(imagestream, new Rectangle(10, 10, 580, 800));
        }
    }
    private static void AddDocxToPdf(string filePath, Document pdfDocument)
    {
        License license = new License();
        license.SetLicense("C:\\Users\\666\\source\\repos\\ConsoleApp1-Aspose23\\ConsoleApp1-Aspose23\\Aspose.Total.lic");
        var doc = new Aspose.Words.Document(filePath);
        using (MemoryStream pdfStream = new MemoryStream())
        {
            doc.Save(pdfStream, Aspose.Words.SaveFormat.Pdf);
            pdfStream.Position = 0;

            using (Document docPdf = new Document(pdfStream))
            {
                pdfDocument.Pages.Add(docPdf.Pages);
            }
        }
    }

@Febinbabu

We used your code to add image inside PDF using 24.12 version and could not notice an extra page:

var pdf = new Aspose.Pdf.Document();
var pdfImageSection = pdf.Pages.Add();
using (var imagestream = new FileStream(dataDir + "car.jpg", FileMode.Open))
{
    pdfImageSection.AddImage(imagestream, new Rectangle(10, 10, 580, 800));
}

Image2Pdf_out.pdf (102.3 KB)

The issue may be occurring while converting and adding DOCX file. Please try setting the license for Aspose.Words using full namespace as below and see if issue still persists:

Aspose.Words.License wLic = new Aspose.Words.License();
wlic.SetLicense("Path");

Hi Team,
I am trying to convert an html file and image file into stream and concatenate it using
PdfFileEditor.Concatenate method

I am getting below exception when concatenating.
AsposePDFConcatenate.png (51.4 KB)

Providing the code also. Requesting you to help me to resolve the issue.
Merge.zip (1.5 KB)

@Febinbabu

Can you please also share the sample files for our reference so that we can test it accordingly?

Hi Asad,
The html file and jpg file are given below.
files.zip (43.2 KB)

@Febinbabu

You might be facing the error because you were using Stream inside using statement and it was likely being disposed with the using block exit. We tested the code with some modifications as below and were not able to notice any issues:

private static void MergeImageAndHTML(string dataDir)
{
    string[] files = new[] { dataDir + "first.html", dataDir + "bugatti.jpg" };
    var pdfFiles = new MemoryStream[files.Length];

    try
    {
        int index = 0;
        foreach (var fileName in files)
        {
            switch (Path.GetExtension(fileName).ToLower())
            {
                case ".html":
                    pdfFiles[index] = ConvertHtmlToPdf(fileName);
                    break;
                case ".jpg":
                case ".jpeg":
                case ".bmp":
                case ".png":
                case ".tiff":
                case ".tif":
                    pdfFiles[index] = ConvertImageToPdf(fileName);
                    break;
            }
            index++;
        }

        Facades.PdfFileEditor editor = new Facades.PdfFileEditor();
        using (FileStream destination = new FileStream(dataDir + "merged.pdf", FileMode.Create))
        {
            editor.Concatenate(pdfFiles, destination);
        }
    }
    finally
    {
        // Dispose all streams to release resources
        foreach (var stream in pdfFiles)
        {
            stream?.Dispose();
        }
    }
}

private static MemoryStream ConvertHtmlToPdf(string fileName)
{
    MemoryStream pdfOutPutStream = new MemoryStream();
    try
    {
        HtmlLoadOptions options = new HtmlLoadOptions();

        using (var document = new Aspose.Pdf.Document(fileName, options))
        {
            // Save the PDF document to the memory stream
            document.Save(pdfOutPutStream);
        }
        pdfOutPutStream.Position = 0; // Reset stream position
    }
    catch (Exception ex)
    {
        throw new Exception($"Failed to convert {fileName} to PDF.", ex);
    }
    return pdfOutPutStream;
}

private static MemoryStream ConvertImageToPdf(string fileName)
{
    MemoryStream pdfOutPutStream = new MemoryStream();
    try
    {
        using (var pdf = new Aspose.Pdf.Document())
        {
            Aspose.Pdf.Page section = pdf.Pages.Add();
            Aspose.Pdf.Image image = new Aspose.Pdf.Image();
            image.File = fileName;
            section.Paragraphs.Add(image);
            pdf.Save(pdfOutPutStream, Aspose.Pdf.SaveFormat.Pdf);
        }
        pdfOutPutStream.Position = 0; // Reset stream position
    }
    catch (Exception ex)
    {
        throw new Exception($"Failed to convert {fileName} to PDF.", ex);
    }
    return pdfOutPutStream;
}

Merged.pdf (45.0 KB)

Hi Asad,

Requesting your help on another issue.

I am merging an image and .xml file with aspose pdf version 24.12.

Facing following issues

  1. The image is not getting merged with correct aspect ratio.
    2.The XML data and its format is not correct in the new doc got generated. Also, some special characters are also appearing.

Providing the source code
SourceCode.zip (1.4 KB)

Input files
InputFiles.zip (43.4 KB)

and output file
OutputFile.zip (57.2 KB)

Thanks,
Febin