使用带有/ JBIG2过滤器的PDFSharp从pdf中提取图像

问题描述 投票:0回答:1

我正在尝试使用PDFsharp从PDF文件中提取图像。我运行代码的测试文件显示过滤器类型为/ JBIG2。我想帮助理解如何解码此图像并保存它,如果它尽可能使用PDFSharp。

我用来提取图像然后保存它的代码如下:

const string filename = "../../../test.pdf";            
PdfDocument document = PdfReader.Open(filename);
int imageCount = 0;

foreach (PdfPage page in document.Pages) { // Iterate pages
  // Get resources dictionary
  PdfDictionary resources = page.Elements.GetDictionary("/Resources");

  if (resources != null) {
    // Get external objects dictionary
    PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");

    if (xObjects != null) {
      ICollection<PdfItem> items = xObjects.Elements.Values;

      foreach (PdfItem item in items) { // Iterate references to external objects
        PdfReference reference = item as PdfReference;

        if (reference != null) {
          PdfDictionary xObject = reference.Value as PdfDictionary;

          // Is external object an image?
          if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image") {
            ExportImage(xObject, ref imageCount);
          }
        }
      }
    }
  }
}

static void ExportImage(PdfDictionary image, ref int count) {
   string filter = image.Elements.GetName("/Filter");

   switch (filter) {
     case "/DCTDecode":
       ExportJpegImage(image, ref count);
       break;
     case "/FlateDecode":
       ExportAsPngImage(image, ref count);
       break;
   }  
}

static void ExportJpegImage(PdfDictionary image, ref int count) {
  // Fortunately, JPEG has native support in PDF and exporting an image is just writing the stream to a file.
  byte[] stream = image.Stream.Value;
  FileStream fs = new FileStream(
    String.Format("Image{0}.jpeg", count++), FileMode.Create, FileAccess.Write
  );
  BinaryWriter bw = new BinaryWriter(fs);
  bw.Write(stream);
  bw.Close();
}

在上面,我得到的过滤器类型为/JBIG2,我确实得到了支持。上面的代码用于PDFSharp: Export Images Sample

c# image pdf pdfsharp jbig2
1个回答
-1
投票

JBIG2在PDF中使用最为广泛,但PDF之外则是另一回事。尽管.jbig2是一种栅格图像格式,但对图像查看器而言,它的支持非常稀少。你最好的选择是将它作为CCITT4压缩的TIFF导出,就像Acrobat那样。

© www.soinside.com 2019 - 2024. All rights reserved.