Free Support Forum - aspose.com

NullReferenceException when saving PDF with TIFF content to memory stream


#1

I’m having problems saving TIFF files as PDFs. I’ve noticed that smaller files seem to work, but the larger examples I’m working with fail with the following error:


System.NullReferenceException: Object reference not set to an instance of an object. at –..(‚ , Int32 , ImageFileType , String , String , String , Int32 , Int32 , Boolean , Boolean , Boolean , Boolean , Byte[] , Stream , a , Single ) at –.‚.›(Image , ImageFileType , String , String , String , Int32 , Int32 , Boolean , Boolean , Byte[] , Stream , a ) at Ž.˜.–(Pdf , Image ) at Ž.˜.(Pdf , Section , Table , Row , Cell , Image , e , ) at Ž.™.˜(Pdf , Section , HeaderFooter , Table , Row , Cell , Image , e , , Boolean ) at Ž..–—(Pdf , Section , e ) at Ž.‰.•(Pdf ) at Ž.’.—•( , Pdf ) at Aspose.Pdf.Generator.Pdf.Save(Stream stream)

I’m using 11.0.0.0.

Code snippet here:

using (Stream contentStream = new MemoryStream(contentToConvert))
{
Pdf.Generator.Pdf pdf = new Pdf.Generator.Pdf
{
PageSetup =
{
Margin =
{
Left = 0,
Right = 0,
Top = 0,
Bottom = 0
}
}
};

Section pdfSection = pdf.Sections.Add();

Image pdfImage = new Image(pdfSection)
{
ImageInfo =
{
ImageFileType = ImageFileType.Tiff,
ImageStream = contentStream,
TiffFrame = -1,
IsAllFramesInNewPage = true
}
};

pdfSection.Paragraphs.Add(pdfImage);

using (MemoryStream saveStream = new MemoryStream())
{
pdf.Save(saveStream);
return saveStream.ToArray();
}
}

Any advice would be greatly appreciated!

Many thanks,

Dan

#2

Hi Dan,


Thanks for your inquiry. Please use new DOM approach for Image to PDF conversion. It will help you to accomplish the task, as it is more efficient and improved.


However, if you face any issue then please share you source TIFF image, we will look into it and guide you accordingly.

We are sorry for the inconvenience caused.

Best Regards,

#3

Hi, thanks for the suggestion, but with this approach I get the following error on save:


System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. at System.Drawing.Bitmap…ctor(Stream stream) at Aspose.Pdf.Image.Process(Double& curX, Double& rightX, Double& curY, Boolean isScaleParagraph, MarginInfo marginInfo, Double realWidth, Double height, Page page, List`1 operators, Boolean isCalculatedMode, Boolean isNextParagraphInline, Paragraphs& paragraphs) at š..Process() at Aspose.Pdf.Page.(Page ) at Aspose.Pdf.Page.ProcessParagraphs() at Aspose.Pdf.Document.ProcessParagraphs() at Aspose.Pdf.Document.Save(Stream output)

Code snippet:

// Instantiate Document Object
Pdf.Document doc = new Pdf.Document();
// Add a page to pages collection of document
Pdf.Page page = doc.Pages.Add();
// Set margins so image will fit, etc.
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;

page.CropBox = new Aspose.Pdf.Rectangle(0, 0, 2480, 3507);
// Create an image object
Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();
// Add the image into paragraphs collection of the section
page.Paragraphs.Add(image1);
using (MemoryStream ms = new MemoryStream(contentToConvert))
{
// Set the image file stream
image1.ImageStream = ms;
// Save resultant PDF file
doc.Save(“c:/pdftest/Image2PDF_DOM.pdf”);
}

I’ve attached an example tiff file with which I can recreate the problem with either approach.

As a workaround, I have had success using Aspose.Imaging to convert the tiff and then add to a PDF but this isn’t really fast enough for my needs.

Thanks for your help,

Dan



#4

Hi Dan,


Thanks for sharing the resource file.

I have tested the scenario of TIFF to PDF conversion using Aspose.Pdf for .NET and I am able to
notice the same problem. For the sake of correction, I have logged this problem
as PDFNEWNET-39989 in our issue tracking system. We will
further look into the details of this problem and will keep you updated on the
status of correction. Please be patient and spare us little time. We are sorry
for this inconvenience.

#5

Brilliant, thank you very much!


#6

Hi Aspose Team, is there any update on this error?


#7

@AdamGr

Thanks for contacting support.

I am afraid that earlier logged issue is not yet resolved due to other high priority issues in the queue. However, we have recorded your concerns and will definitely consider them during issue resolution. Furthermore, would you please share your sample TIFF image with us, which is generating issue at your end while converting it into PDF. We will test the scenario in our environment and address it accordingly.


#8

Hi Aspose Team,

it is just a white image (684 px, 236 px) with a black text in the middle, like “test content”). I don’t think it matters. You can check with any white tiff image.
Is there any chance you will fix it this week?


#9

Hi Aspose Team,

I will additionally explain why I have this issue. I am migrating code to the newest Aspose. Below the old and new code. If you think I am doing something wrong, maybe you can just correct my code.
In the old code I used namespace:
using Aspose.Pdf.Generator;
using Aspose.Pdf.Text;

and in the new code:
using Aspose.Pdf;

Regards

Old code:
public void ProcessTiff(byte[] sourceFile)
{
Pdf pdf = new Pdf();
var section = pdf.Sections.Add();
section.PageInfo.PageWidth = PageSize.A4Width;
section.PageInfo.PageHeight = PageSize.A4Height;
MarginInfo marginInfo = new MarginInfo();
marginInfo.Top = 0;
marginInfo.Bottom = 0;
marginInfo.Left = 0;
marginInfo.Right = 0;
section.PageInfo.Margin = marginInfo;

        using (MemoryStream imageStream = new MemoryStream(sourceFile))
        {
            var image = new Image(section);
            image.ImageInfo.ImageStream = imageStream;
            image.ImageInfo.ImageFileType = ImageFileType.Tiff;
            section.Paragraphs.Add(image);
            image.ImageInfo.TiffFrame = -1;

            using (var pdfDocument = new Aspose.Pdf.Document(pdf))
			{

New code:

		public void ProcessTiff(byte[] sourceFile)
		{
			Document pdf = new Document();
			var section = pdf.Pages.Add();
			section.PageInfo.Width = PageSize.A4.Width;
			section.PageInfo.Height = PageSize.A4.Height;
			MarginInfo marginInfo = new MarginInfo();
			marginInfo.Top = 0;
			marginInfo.Bottom = 0;
			marginInfo.Left = 0;
			marginInfo.Right = 0;
			section.PageInfo.Margin = marginInfo;

			using (MemoryStream imageStream = new MemoryStream(sourceFile))
			{
				var image = new Image();
				image.Margin = marginInfo;
				image.FixWidth = PageSize.A4.Width;
				image.FixHeight = PageSize.A4.Height;
				image.ImageStream = imageStream;
				image.FileType = ImageFileType.Svg;
				section.Paragraphs.Add(image);
				//image.ImageInfo.TiffFrame = -1;

				var ms = new MemoryStream();
				pdf.Save(ms, SaveFormat.Pdf);
				using (var pdfDocument = new Document(ms))

#10

@AdamGr

Thanks for your feedback.

Please try using following code snippet in your environment and let us know about the results you get after executing it. In case it still produces any issue, it would be helpful if you can please share the same input TIFF file with us. We will further test it in our environment and share our feedback accordingly.

Document pdf1 = new Document();
MemoryStream ms = new MemoryStream();
new FileStream(dataDir + @"input.tif", FileMode.Open).CopyTo(ms);
Bitmap myimage = new Bitmap(ms);

FrameDimension dimension = new FrameDimension(myimage.FrameDimensionsList[0]);
int frameCount = myimage.GetFrameCount(dimension);

for (int frameIdx = 0; frameIdx <= frameCount - 1; frameIdx++)
{
  Page sec = pdf1.Pages.Add();
  myimage.SelectActiveFrame(dimension, frameIdx);
  MemoryStream currentImage = new MemoryStream();
  myimage.Save(currentImage, ImageFormat.Tiff);

  if (myimage.Width > myimage.Height)
  {
   sec.PageInfo.IsLandscape = true;
  }
  else
  {
   sec.PageInfo.IsLandscape = false;
  }

  Aspose.Pdf.Image imageht = new Aspose.Pdf.Image();
  imageht.ImageStream = currentImage;
  sec.Paragraphs.Add(imageht);
}
pdf1.Save(dataDir + "TifftoPDF.pdf"); 

#11

Hi Aspose Team,

thank you for fast answer. This solves the NullReference exception. But now my code breaks in next line which is:
pdfDocument.Convert(CallBackMethod); without even going to the callback method.
The Exception is:
Invalid index: index should be in the range [1…n] where n equals to the operators count.
Please let me know whether we can fix this.

Regards

Current code:
public void ProcessTiff(byte[] sourceFile)
{
Document pdf = new Document();
var section = pdf.Pages.Add();
section.PageInfo.Width = PageSize.A4.Width;
section.PageInfo.Height = PageSize.A4.Height;
MarginInfo marginInfo = new MarginInfo();
marginInfo.Top = 0;
marginInfo.Bottom = 0;
marginInfo.Left = 0;
marginInfo.Right = 0;
section.PageInfo.Margin = marginInfo;

        using (MemoryStream imageStream = new MemoryStream(sourceFile))
        {
            var image = new Bitmap(imageStream);
            FrameDimension dimension = new FrameDimension(image.FrameDimensionsList[0]);
            int frameCount = image.GetFrameCount(dimension);

            for (int frameIdx = 0; frameIdx <= frameCount - 1; frameIdx++)
            {
                Page sec = pdf.Pages.Add();
                image.SelectActiveFrame(dimension, frameIdx);
                MemoryStream currentImage = new MemoryStream();
                image.Save(currentImage, ImageFormat.Tiff);

                if (image.Width > image.Height)
                {
                    sec.PageInfo.IsLandscape = true;
                }
                else
                {
                    sec.PageInfo.IsLandscape = false;
                }

                Aspose.Pdf.Image imageht = new Aspose.Pdf.Image();
                imageht.ImageStream = currentImage;
                sec.Paragraphs.Add(imageht);
            }

            var ms = new MemoryStream();
            pdf.Save(ms, SaveFormat.Pdf);
            using (var pdfDocument = new Document(ms))
            {
                pdfDocument.Convert(CallBackMethod);

#12

@AdamGr

Thanks for writing back.

Would you please share the definition of CallBackMethod method which you are using at your side. We will test the scenario in our environment and address it accordingly.


#13

Hi Aspose Team,

the method looks more or less like following code. I cut business logic. targetFile is a .html file.

private string CallBackMethod(System.Drawing.Image img)
{
string tick = DateTime.Now.Ticks.ToString();

        string hocr;
        using (StreamReader streamReader = new StreamReader(targetFile))
        {
            hocr = streamReader.ReadToEnd();
        }

        return hocr;
    }

#14

@AdamGr

Thanks for sharing requested details.

We have tested the scenario in our environment using one of our sample TIFF images and were unable to replicate the issue which you have mentioned. Would you please share a sample console application along with input/output files so that we can again test the scenario in our environment and address it accordingly.


#15

Hi Aspose Team,

maybe this will help you. This is the stack trace I get:
at Aspose.Pdf.OperatorCollection.#=zq1cTQVs=(Int32 #=zsGb6rag=)
at #=z6zd4MBENZVcZkTeMiSOQCCv_p6hxq13KByg7N4tV7s1cM7AxRDkHf7Y=.#=zK7XUQHA=(CallBackGetHocr #=z1OgK1w$yYSKF, Document #=zcbz2dKo=)
after this there is stack trace of my code.
Exception: Invalid index: index should be in the range [1…n] where n equals to the operators count.
Asposepdf.dll: 19.1.0.0
Exact callback method name is CallBackGetHocr.

Please let me know if this is sufficient for you.

Best regards


#16

@AdamGr

Thanks for sharing the stack trace.

By looking at the stack trace it seems that issue is related to some operators collection in PDF and there could be more than single reasons of that. I regret that this information is not sufficient to investigate the issue you are facing and that is why we requested you to share a sample console application able to reproduce the issue. This would help us replicating the scenario in our environment and address it accordingly.