2016-11-02 193 views
0

我正在使用iTextSharp將PDF文檔合併在一起。我的問題是我想合併一個包含書籤的大型PDF。我目前的功能是使用PdfWriter來合併文檔。我知道PdfStamper會工作,但我無法弄清楚如何改變功能正常工作。itextsharp從pdfwriter更改爲pdfstamper以保留PDF中的書籤

當我在下面的示例中將PdfWriter更改爲PdfStamper時,出現錯誤。

代碼示例:

writer = PdfStamper.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate)) 

錯誤消息:

'的GetInstance' 不是 'iTextSharp.text.pdf.PdfStamper'

這裏是一個整體構件功能:

Public Shared Function MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String) As Boolean 
    Dim result As Boolean = False 
    Dim pdfCount As Integer = 0  
    Dim f As Integer = 0  
    Dim fName As String 
    Dim reader As iTextSharp.text.pdf.PdfReader = Nothing 
    Dim pageCount As Integer = 0 
    Dim pdfDoc As iTextSharp.text.Document = Nothing  
    Dim writer As PdfWriter = Nothing 
    Dim cb As PdfContentByte = Nothing 

    Dim page As PdfImportedPage = Nothing 
    Dim rotation As Integer = 0 

    Try 
     pdfCount = pdfFiles.Length 
     If pdfCount > 1 Then 
      fName = pdfFiles(f) 
      reader = New iTextSharp.text.pdf.PdfReader(fName) 
      pageCount = reader.NumberOfPages 

      pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18) 

      writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate)) 

      With pdfDoc 
       .Open() 
      End With 
      cb = writer.DirectContent 
      While f < pdfCount 
       Dim i As Integer = 0 
       While i < pageCount 
        i += 1 
        pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i)) 
        pdfDoc.NewPage() 
        page = writer.GetImportedPage(reader, i) 
        rotation = reader.GetPageRotation(i) 
        If rotation = 90 Then 
         cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height) 
        ElseIf rotation = 270 Then 
         cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30) 
        Else 
         cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0) 
        End If 
       End While 
       f += 1 
       If f < pdfCount Then 
        fName = pdfFiles(f) 
        reader = New iTextSharp.text.pdf.PdfReader(fName) 
        pageCount = reader.NumberOfPages 
       End If 
      End While 
      pdfDoc.Close() 
      result = True 
     End If 
    Catch ex As Exception 
     MessageBox.Show(ex.Message) 
     Return False 
    End Try 
    Return result 
End Function 

回答

1

您不能只是將PdfWriter更改爲PdfStamper。您neex創建與讀者壓模和輸出流:

PdfReader reader = new PdfReader(pathToSrc); 
PdfStamper.GetInstance(reader, New FileStream(outputPath, FileMode.OpenOrCreate)); 
// do stuff 
stamper.Close(); 

如果使用PdfStamper你並不需要一個Document實例;您只需要更仔細閱讀文檔。

上述一切是你沒用,因爲PdfStamper是當你操縱單個文件使用類。如果要合併不同的文件,你需要使用PdfCopyPdfSmartCopy

請大家看看ConcatenateBookmarks例子。如果您不瞭解Java,那麼頁面底部會有一個C#示例。

瀏覽官方網站的iText如果您還有其他問題。