0

我有一个程序可以为提交到网站的 PDF 添加第二页。我使用 C# 和 PDFSharp。大多数文档工作正常,但少数用户收到“对象引用未设置为对象实例”。

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];

错误发生在第二行。当我调试时,它显示 PageCount = 0,这很奇怪,因为它是一个 1 页文档。

4

2 回答 2

0

非常感谢您拯救了我的一天!,我改进解决方案的唯一建议是在 using 块上使用内存流,如下所示:

  Using memoryStream As MemoryStream = ReturnCompatiblePdf(File.FullName)
      Dim DocPdf As PdfDocument = PdfReader.Open(memoryStream, PdfDocumentOpenMode.Import)
      //Your code here.....
  End Using
于 2016-09-15T19:45:51.870 回答
-1

我有同样的问题,但通过下面的代码解决,问题是 PDF 兼容性。

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
于 2015-09-09T09:05:25.750 回答