I found an internal "object reference not set to an instance of an object" exception when my code call method "page.CreateTemplate()".
this is my code:
- Code: Select all
PdfDocument pdfDocument = new();
pdfDocument.LoadFromFile("file.pdf")
using MemoryStream ms = new();
using PdfDocument destinationPdfDocument = new();
SizeF newPageSize;
SizeF pageVisibleSize;
float resizeMargin;
float widthFactor;
float heightFactor;
float resizeXFactor;
float resizeYFactor;
PdfPageBase newPage;
PdfMargins newPageMargins;
PdfPageBase page;
for (int i = 0; i < pdfDocument.Pages.Count; i++)
{
page = pdfDocument.Pages[i];
newPageMargins = (PdfMargins)margins.Clone();
newPageSize = PdfPageSize.A4;
if ((page.IsLandscape() && !page.IsRotated())
|| (!page.IsLandscape() && page.IsRotated()))
{
newPageSize = new SizeF(PdfPageSize.A4.Height, PdfPageSize.A4.Width);
}
pageVisibleSize = page.GetVisibleSize();
widthFactor = (newPageSize.Width - (newPageMargins.Left + newPageMargins.Right)) / pageVisibleSize.Width;
heightFactor = (newPageSize.Height - (newPageMargins.Top + newPageMargins.Bottom)) / pageVisibleSize.Height;
resizeXFactor = widthFactor;
resizeYFactor = heightFactor;
if (heightFactor < widthFactor)
{
resizeXFactor = heightFactor;
resizeMargin = (newPageSize.Width - (pageVisibleSize.Width * heightFactor)) / 2;
newPageMargins.Left = resizeMargin;
newPageMargins.Right = resizeMargin;
}
else if (heightFactor > widthFactor)
{
resizeYFactor = widthFactor;
resizeMargin = (newPageSize.Height - (pageVisibleSize.Height * widthFactor)) / 2;
if (resizeMargin > newPageMargins.Top)
{
newPageMargins.Top = resizeMargin;
newPageMargins.Bottom = resizeMargin;
}
}
newPage = destinationPdfDocument.Pages.Add(newPageSize, newPageMargins);
newPage.Canvas.ScaleTransform(resizeXFactor, resizeYFactor);
newPage.Canvas.DrawTemplate(page.CreateTemplate(), PointF.Empty);
}
destinationPdfDocument.SaveToStream(ms);
and this is the error message :
System.NullReferenceException: Object reference not set to an instance of an object.
at spr鉟.逯()
at Spire.Pdf.Graphics.PdfTemplate..ctor(sprꅏ A_0)
at Spire.Pdf.PdfPageBase.CreateTemplate()
i can't share the document for a GDPR policy, but i can send if you provide me a safer way.
Regards
Fabrizio