2012-07-05 76 views
5

我需要能夠從PDF文件中讀取QR碼。我正在使用接受圖像並返回保存在QR碼中的數據的.thirds.QRCode。我有那部分工作。將PDF轉換爲圖像以便讀取QR碼

但是,我需要能夠接受多頁PDF文件並將每個頁面作爲圖像發送到QR閱讀器。然後,我需要將原始PDF的每頁保存爲以QR碼中包含的數據命名的單頁PDF。

你會推薦哪個庫用於這個項目?我見過的許多創造永久圖像,但我只是想臨時的。有什麼可以輕易讓我做到嗎?是否有另一個QR閱讀器可以閱讀pdf?

感謝您的任何建議,您可能可以借出!

回答

5

我使用itextsharp和libtiff.NET從PDF文件中提取tiff圖像到內存中。底線是itextsharp會給你訪問的圖像,但如果它們被編碼,你需要自己做編碼或使用另一個庫,這是libtiff.NET進來的地方。

下面的代碼是基於我問了一個問題的答案:PDF Add Text and Flatten

Private Shared Function ExtractImages(ByVal pdf As Byte()) As List(Of Byte()) 
    Dim images As New List(Of Byte()) 
    Dim reader As New PdfReader(pdf) 

    If (reader IsNot Nothing) Then 
     ' Loop through all of the references in the PDF. 
     For refIndex = 0 To (reader.XrefSize - 1) 
      ' Get the object. 
      Dim obj = reader.GetPdfObject(refIndex) 

      ' Make sure we have something and that it is a stream. 
      If (obj IsNot Nothing) AndAlso obj.IsStream() Then 
       ' Cast it to a dictionary object. 
       Dim pdfDict = DirectCast(obj, iTextSharp.text.pdf.PdfDictionary) 

       ' See if it has a subtype property that is set to /IMAGE. 
       If pdfDict.Contains(iTextSharp.text.pdf.PdfName.SUBTYPE) AndAlso (pdfDict.Get(iTextSharp.text.pdf.PdfName.SUBTYPE).ToString() = iTextSharp.text.pdf.PdfName.IMAGE.ToString()) Then 
        ' Grab various properties of the image. 
        Dim filter = pdfDict.Get(iTextSharp.text.pdf.PdfName.FILTER).ToString() 
        Dim width = pdfDict.Get(iTextSharp.text.pdf.PdfName.WIDTH).ToString() 
        Dim height = pdfDict.Get(iTextSharp.text.pdf.PdfName.HEIGHT).ToString() 
        Dim bpp = pdfDict.Get(iTextSharp.text.pdf.PdfName.BITSPERCOMPONENT).ToString() 

        ' Grab the raw bytes of the image 
        Dim bytes = PdfReader.GetStreamBytesRaw(DirectCast(obj, PRStream)) 

        ' Images can be encoded in various ways. 
        ' All of our images are encoded with a single filter. 
        ' If there is a need to decode another filter, it will need to be added. 
        If (filter = iTextSharp.text.pdf.PdfName.CCITTFAXDECODE.ToString()) Then 
         Using ms = New MemoryStream() 
          Using tiff As Tiff = tiff.ClientOpen("memory", "w", ms, New TiffStream()) 
           tiff.SetField(TiffTag.IMAGEWIDTH, width) 
           tiff.SetField(TiffTag.IMAGELENGTH, height) 
           tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4) 
           tiff.SetField(TiffTag.BITSPERSAMPLE, bpp) 
           tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1) 

           tiff.WriteRawStrip(0, bytes, bytes.Length) 
           tiff.Flush() 
           images.Add(ms.ToArray()) 
           tiff.Close() 
          End Using 
         End Using 
        Else 
         Throw New NotImplementedException("Decoding this filter has not been implemented") 
        End If 
       End If 
      End If 
     Next 
    End If 

    Return images 
End Function