Reputation: 144
I have a program that adds a second page to PDFs submitted to the website. I use C# and PDFSharp. Most documents work fine, but a few users are getting "Object reference not set to an instance of an object."
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing.Layout;
PdfDocument rosterInput = PdfReader.Open(FilePath, PdfDocumentOpenMode.Import);
PdfPage rpage = rosterInput.Pages[0];
The error occurs on the second line. When I debug, it says PageCount = 0, which is weird because it is a 1 page document.
Upvotes: 1
Views: 21344
Reputation: 11
Thank you very much you saved my day!, my only suggestion to improve the solution is to use the memorystream inside on a using block like this:
Using memoryStream As MemoryStream = ReturnCompatiblePdf(File.FullName)
Dim DocPdf As PdfDocument = PdfReader.Open(memoryStream, PdfDocumentOpenMode.Import)
//Your code here.....
End Using
Upvotes: 1
Reputation: 19
I had the same issue but resolved by the below code, issue was by PDF compatibility.
PdfSharp.Pdf.IO.PdfReader.Open(ReturnCompatiblePdf("PDF FILE PATH"), PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import)
Private Function ReturnCompatiblePdf(ByVal sFilename As String) As MemoryStream
Dim reader As New iTextSharp.text.pdf.PdfReader(sFilename)
Dim output_stream As New MemoryStream
' we retrieve the total number of pages
Dim n As Integer = reader.NumberOfPages
' step 1: creation of a document-object
Dim document As New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1))
' step 2: we create a writer that listens to the document
Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, output_stream)
'write pdf that pdfsharp can understand
writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4)
' step 3: we open the document
document.Open()
Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
Dim page As iTextSharp.text.pdf.PdfImportedPage
Dim rotation As Integer
Dim i As Integer = 0
While i < n
i += 1
document.SetPageSize(reader.GetPageSizeWithRotation(i))
document.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 OrElse rotation = 270 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _
reader.GetPageSizeWithRotation(i).Height)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _
0)
End If
End While
'---- Keep the stream open!
writer.CloseStream = False
' step 5: we close the document
document.Close()
Return output_stream
End Function
Upvotes: 0