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);
}
@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.
After upgrading to verion 23.12 , PageSize is not there in the above 2 places, instead it is moved to Aspose.Pdf.PageSize.
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?
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);
}
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.
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() { }
}
Below code is working fine with Aspose.PDF version 7.3. How do we re write the code with Aspose.PDF version 23.12?
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.
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
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:
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);
}
}
}
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));
}
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");
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;
}
I am merging an image and .xml file with aspose pdf version 24.12.
Facing following issues
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.
Sets consent for sending user data to Google for online advertising purposes.
Sets consent for personalized advertising.
Cookie Notice
To provide you with the best experience, we use cookies for personalization, analytics, and ads. By using our site, you agree to our cookie policy.
More info
Enables storage, such as cookies, related to analytics.
Enables storage, such as cookies, related to advertising.
Sets consent for sending user data to Google for online advertising purposes.
Sets consent for personalized advertising.
Cookie Notice
To provide you with the best experience, we use cookies for personalization, analytics, and ads. By using our site, you agree to our cookie policy.
More info
Enables storage, such as cookies, related to analytics.
Enables storage, such as cookies, related to advertising.
Sets consent for sending user data to Google for online advertising purposes.